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": "ffee\n# Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai>\n\nmodule.exports.buyer =\n name: \"Buyer\"\n inputs",
"end": 75,
"score": 0.9999099969863892,
"start": 61,
"tag": "EMAIL",
"value": "legal@fuzzy.ai"
},
{
"context": "<legal@fuzzy.ai>\n\nmodule.exports.buyer =\n name: \"Buyer\"\n inputs:\n price:\n veryLow: [0, 1.25]\n ",
"end": 115,
"score": 0.729443371295929,
"start": 110,
"tag": "NAME",
"value": "Buyer"
}
] | src/agents.coffee | enterstudio/lemonade-stand | 2 | # agents.coffee
# Copyright 2016 9165584 Canada Corporation <legal@fuzzy.ai>
module.exports.buyer =
name: "Buyer"
inputs:
price:
veryLow: [0, 1.25]
low: [0, 1.25, 2.5]
medium: [1.25, 2.5, 3.75]
high: [2.5, 3.75, 5]
veryHigh: [3.75, 5]
numBuyers:
"very low": [0, 5]
"low": [0, 5, 10]
"medium": [5, 10, 15]
"high": [10, 15, 20]
"very high": [15, 20]
temperature:
"very low": [0, 25]
"low": [0, 25, 50]
"medium": [25, 50, 75]
"high": [50, 75, 100]
"very high": [75, 100]
sunny:
false: [0, 0.5]
true: [0.5, 1]
outputs:
willBuy:
hellNo: [0, 0.25]
no: [0, 0.25, 0.5]
maybe: [0.25, 0.5, 0.75]
yes: [0.5, 0.75, 1]
omgYes: [0.75, 1]
rules: [
'''price DECREASES willBuy WITH 1.0'''
'''numBuyers DECREASES willBuy WITH 0.10'''
'''temperature DECREASES willBuy WITH 0.75'''
'''IF sunny IS true THEN willBuy IS no WITH 0.5'''
'''IF sunny IS false THEN willBuy IS yes WITH 0.5'''
]
module.exports.seller =
inputs:
numBuyers:
"very low": [0, 5]
"low": [0, 5, 10]
"medium": [5, 10, 15]
"high": [10, 15, 20]
"very high": [15, 20]
temperature:
"very low": [0, 25]
"low": [0, 25, 50]
"medium": [25, 50, 75]
"high": [50, 75, 100]
"very high": [75, 100]
sunny:
false: [0, 0.5]
true: [0.5, 1]
outputs:
price:
"very low": [0, 1.25]
"low": [0, 1.25, 2.5]
"medium": [1.25, 2.5, 3.75]
"high": [2.5, 3.75, 5]
"very high": [3.75, 5]
performance:
profit: "maximize"
rules: [
'''numBuyers DECREASES price WITH 0.10'''
'''temperature DECREASES price WITH 1.0'''
'''IF sunny IS true THEN price IS low WITH 0.50'''
'''IF sunny IS false THEN price IS high WITH 0.50'''
]
| 78363 | # agents.coffee
# Copyright 2016 9165584 Canada Corporation <<EMAIL>>
module.exports.buyer =
name: "<NAME>"
inputs:
price:
veryLow: [0, 1.25]
low: [0, 1.25, 2.5]
medium: [1.25, 2.5, 3.75]
high: [2.5, 3.75, 5]
veryHigh: [3.75, 5]
numBuyers:
"very low": [0, 5]
"low": [0, 5, 10]
"medium": [5, 10, 15]
"high": [10, 15, 20]
"very high": [15, 20]
temperature:
"very low": [0, 25]
"low": [0, 25, 50]
"medium": [25, 50, 75]
"high": [50, 75, 100]
"very high": [75, 100]
sunny:
false: [0, 0.5]
true: [0.5, 1]
outputs:
willBuy:
hellNo: [0, 0.25]
no: [0, 0.25, 0.5]
maybe: [0.25, 0.5, 0.75]
yes: [0.5, 0.75, 1]
omgYes: [0.75, 1]
rules: [
'''price DECREASES willBuy WITH 1.0'''
'''numBuyers DECREASES willBuy WITH 0.10'''
'''temperature DECREASES willBuy WITH 0.75'''
'''IF sunny IS true THEN willBuy IS no WITH 0.5'''
'''IF sunny IS false THEN willBuy IS yes WITH 0.5'''
]
module.exports.seller =
inputs:
numBuyers:
"very low": [0, 5]
"low": [0, 5, 10]
"medium": [5, 10, 15]
"high": [10, 15, 20]
"very high": [15, 20]
temperature:
"very low": [0, 25]
"low": [0, 25, 50]
"medium": [25, 50, 75]
"high": [50, 75, 100]
"very high": [75, 100]
sunny:
false: [0, 0.5]
true: [0.5, 1]
outputs:
price:
"very low": [0, 1.25]
"low": [0, 1.25, 2.5]
"medium": [1.25, 2.5, 3.75]
"high": [2.5, 3.75, 5]
"very high": [3.75, 5]
performance:
profit: "maximize"
rules: [
'''numBuyers DECREASES price WITH 0.10'''
'''temperature DECREASES price WITH 1.0'''
'''IF sunny IS true THEN price IS low WITH 0.50'''
'''IF sunny IS false THEN price IS high WITH 0.50'''
]
| true | # agents.coffee
# Copyright 2016 9165584 Canada Corporation <PI:EMAIL:<EMAIL>END_PI>
module.exports.buyer =
name: "PI:NAME:<NAME>END_PI"
inputs:
price:
veryLow: [0, 1.25]
low: [0, 1.25, 2.5]
medium: [1.25, 2.5, 3.75]
high: [2.5, 3.75, 5]
veryHigh: [3.75, 5]
numBuyers:
"very low": [0, 5]
"low": [0, 5, 10]
"medium": [5, 10, 15]
"high": [10, 15, 20]
"very high": [15, 20]
temperature:
"very low": [0, 25]
"low": [0, 25, 50]
"medium": [25, 50, 75]
"high": [50, 75, 100]
"very high": [75, 100]
sunny:
false: [0, 0.5]
true: [0.5, 1]
outputs:
willBuy:
hellNo: [0, 0.25]
no: [0, 0.25, 0.5]
maybe: [0.25, 0.5, 0.75]
yes: [0.5, 0.75, 1]
omgYes: [0.75, 1]
rules: [
'''price DECREASES willBuy WITH 1.0'''
'''numBuyers DECREASES willBuy WITH 0.10'''
'''temperature DECREASES willBuy WITH 0.75'''
'''IF sunny IS true THEN willBuy IS no WITH 0.5'''
'''IF sunny IS false THEN willBuy IS yes WITH 0.5'''
]
module.exports.seller =
inputs:
numBuyers:
"very low": [0, 5]
"low": [0, 5, 10]
"medium": [5, 10, 15]
"high": [10, 15, 20]
"very high": [15, 20]
temperature:
"very low": [0, 25]
"low": [0, 25, 50]
"medium": [25, 50, 75]
"high": [50, 75, 100]
"very high": [75, 100]
sunny:
false: [0, 0.5]
true: [0.5, 1]
outputs:
price:
"very low": [0, 1.25]
"low": [0, 1.25, 2.5]
"medium": [1.25, 2.5, 3.75]
"high": [2.5, 3.75, 5]
"very high": [3.75, 5]
performance:
profit: "maximize"
rules: [
'''numBuyers DECREASES price WITH 0.10'''
'''temperature DECREASES price WITH 1.0'''
'''IF sunny IS true THEN price IS low WITH 0.50'''
'''IF sunny IS false THEN price IS high WITH 0.50'''
]
|
[
{
"context": "$authWithPassword({\n\t\t\t\temail: email\n\t\t\t\tpassword: encodedPassword\n\t\t\t}, {remember: remember})\n\t\t\t.then ->\n\t\t\t\tupdat",
"end": 955,
"score": 0.9983924031257629,
"start": 940,
"tag": "PASSWORD",
"value": "encodedPassword"
},
{
"context": "hWithPassword({\n\t\t\t\t\t\temail: email\n\t\t\t\t\t\tpassword: password\n\t\t\t\t\t}, {remember: remember})\n\t\t\t\t\t.then ->\n\t\t\t\t\t",
"end": 1189,
"score": 0.9958063364028931,
"start": 1181,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "xtend user.info,\n\t\t\t\tfirstName: null\n\t\t\t\tlastName: null\n\t\t\t\temail: null\n\t\t\t\twallet: null\n\t\t\t\tfacebook: nu",
"end": 2048,
"score": 0.5029095411300659,
"start": 2044,
"tag": "NAME",
"value": "null"
},
{
"context": "e</a> to login and vote.'\n\t\t\t\t}, {\n\t\t\t\t\tname : 'password',\n\t\t\t\t\tcontent: credentials.password\n\t\t\t\t}, {\n\t\t\t",
"end": 4414,
"score": 0.6504011154174805,
"start": 4406,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "'\n\t\t\t\t}, {\n\t\t\t\t\tname : 'password',\n\t\t\t\t\tcontent: credentials.password\n\t\t\t\t}, {\n\t\t\t\t\tname : 'email',\n\t\t\t\t\tcon",
"end": 4442,
"score": 0.9799729585647583,
"start": 4431,
"tag": "PASSWORD",
"value": "credentials"
},
{
"context": "\t\t\tname : 'password',\n\t\t\t\t\tcontent: credentials.password\n\t\t\t\t}, {\n\t\t\t\t\tname : 'email',\n\t\t\t\t\tcontent: cre",
"end": 4451,
"score": 0.8111711144447327,
"start": 4443,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\tself = this\n\t\t\tdefer = $q.defer()\n\t\t\tpassphrase = password\n\t\t\tpassword = this.encodePassword password\n\t\t\taut",
"end": 5094,
"score": 0.998953104019165,
"start": 5086,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "\t\tuserData.email = login\n\t\t\t\tuserData.passphrase = passphrase\n\t\t\t\tdefer.resolve userData\n\t\t\t\tif data\n\t\t\t\t\tself.",
"end": 5267,
"score": 0.9747093915939331,
"start": 5257,
"tag": "PASSWORD",
"value": "passphrase"
},
{
"context": "poraryPassword\n\t\t\t\t\tself.update temporaryPassword: newPasswordEncoded\n\t\t\t\tself.update newPasswordRequired: null\n\t\t\t\t.th",
"end": 6180,
"score": 0.9274556040763855,
"start": 6162,
"tag": "PASSWORD",
"value": "newPasswordEncoded"
},
{
"context": "oraryPassword\n\t\t\t\t\t\tself.update temporaryPassword: newPasswordEncoded\n\t\t\t\t\tself.update newPasswordRequired: null\n\t\t\t\t\t.",
"end": 6466,
"score": 0.8815976977348328,
"start": 6448,
"tag": "PASSWORD",
"value": "newPasswordEncoded"
},
{
"context": "llet: results.votingWallet\n\t\t\t\t\ttemporaryPassword: results.temporaryPassword\n\t\t\t\t\tvotings: results.votings\n\t\t\t\t\tallowMultiOpti",
"end": 7994,
"score": 0.9975628852844238,
"start": 7969,
"tag": "PASSWORD",
"value": "results.temporaryPassword"
}
] | js/services/user.coffee | SwarmCorp/razzledazzle | 0 | window.app.service 'User', ($rootScope, $q, $route, $firebase, $firebaseAuth, firebaseUrl, Firebase, Sidebar, mandrill, dazzleUrl, Counterparty) ->
ref = new Firebase(firebaseUrl)
authClient = $firebaseAuth ref
user =
# Check if user is logged in
isLoggedIn: -> authClient.$getAuth()?
# User information (name, email etc) object
info:
id: null
firstName: null
lastName: null
email: null
wallet: null
facebook: null
newPasswordRequired: null
votingWallet: null
temporaryPassword: null
role: null # Available roles: ['admin', 'voting-admin']
avatar: null
votings: null
project: null
dco: null
loaded: false
allowMultiOptionsVote: false
allUsers: null
# Method to log user in
login: (email, password, remember) ->
Firebase.goOnline()
encodedPassword = this.encodePassword password
defer = $q.defer()
authClient.$authWithPassword({
email: email
password: encodedPassword
}, {remember: remember})
.then ->
updateInfo().then ->
defer.resolve()
.then null, (reason) ->
if reason.code == 'INVALID_PASSWORD'
authClient.$authWithPassword({
email: email
password: password
}, {remember: remember})
.then ->
updateInfo({newPasswordRequired: true}).then ->
defer.resolve()
.then null, (reason)->
defer.reject(reason)
else
defer.reject(reason)
return defer.promise
# Method to log user in with Facebook account
facebookLogin: () ->
self = this
defer = $q.defer()
authClient.$authWithOAuthPopup 'facebook', scope: 'email'
.then (authData)->
userData =
first_name: authData.facebook.cachedUserProfile.first_name
last_name: authData.facebook.cachedUserProfile.last_name
email: authData.facebook.cachedUserProfile.email
facebook: true
self.update userData
.then ->
defer.resolve()
return defer.promise
# Method to log user out
logout: ->
authClient.$unauth()
angular.extend user.info,
firstName: null
lastName: null
email: null
wallet: null
facebook: null
newPasswordRequired: null
role: null
avatar: null
votingWallet: null
temporaryPassword: null
votings: null
project: null
dco: null
loaded: null
allowMultiOptionsVote: false
Sidebar.hide()
Sidebar.switchSection('User')
location.reload()
generatePassphrase: (length = 12) ->
switch length
when 3 then complexity = 32
when 6 then complexity = 64
when 9 then complexity = 92
when 12 then complexity = 128
else complexity = 128
return new Mnemonic complexity
.toWords().join(' ')
getAsset: (assetName) ->
self = this
defer = $q.defer()
assetQuantity = 0
new Counterparty(self.info.privateKey).getAssets()
.then (data) ->
if data.length == 0
defer.resolve assetQuantity
else
for asssetObj in data
if asssetObj.asset == assetName
assetQuantity = asssetObj.quantity
defer.resolve assetQuantity
.then null, (reason)->
defer.resolve 0
return defer.promise
getUserDataByEmail: (email)->
# self = this
defer = $q.defer()
# console.log 'sss'
this.allUsers.forEach (user, id)->
if user.email == email
return defer.resolve {uid: id, userData: user}
return defer.promise
# self.getUidByEmail email
# .then (uid)->
# console.log 'aaaa'
# defer.resolve {uid: uid, userData: self.allUsers[uid]}
getAllUsers: ()->
self = this
defer = $q.defer()
ref = new Firebase(firebaseUrl).child 'users'
$firebase(ref).$asObject().$loaded()
.then (data) ->
self.allUsers = data
defer.resolve()
return defer.promise
getUidByEmail: (email)->
defer = $q.defer()
this.allUsers.forEach (user, id)->
if user.email == email
return defer.resolve(id)
return defer.promise
emailNotification: (credentials, template = 'votingwalletinvite', options) ->
defer = $q.defer()
params =
template_name: template
template_content: [{
name : 'registrationLink'
content: '<a href="' + dazzleUrl + '/login" target="_blank">here</a>'
},{
name : 'signupLink'
content: '<a href="' + dazzleUrl + '/login" target="_blank">here</a>'
},{
name : 'loginLink'
content: 'Click <a href="' + dazzleUrl + '/login" target="_blank">here</a> to login and vote.'
}, {
name : 'password',
content: credentials.password
}, {
name : 'email',
content: credentials.login
}]
message:
to: [{
email: credentials.login,
name: credentials.userName || ''
}]
mandrill.sendTemplate params, defer.resolve, defer.reject
# Encode password
encodePassword: (password) ->
bitcore = require 'bitcore'
bitcoreBuffer = bitcore.util.buffer
newBuffer = new bitcoreBuffer.EMPTY_BUFFER.constructor password
key = bitcore.crypto.Hash.sha256 newBuffer
return bitcoreBuffer.bufferToHex key
# Method to create new user
create: (login, password, data) ->
self = this
defer = $q.defer()
passphrase = password
password = this.encodePassword password
authClient.$createUser(login, password)
.then (userData) ->
userData.email = login
userData.passphrase = passphrase
defer.resolve userData
if data
self.update data, userData.uid
.then null, (reason) ->
reason.userData = {
email: login
}
defer.reject reason
return defer.promise
# Method to update user data
update: (data, userId) ->
defer = $q.defer()
uid = userId || authClient.$getAuth().uid
ref = new Firebase(firebaseUrl + '/users/' + uid)
$firebase(ref).$update data
.then ->
updateInfo()
defer.resolve()
.then null, (reason) ->
defer.reject reason
return defer.promise
updatePassword: (oldPassword, newPassword) ->
self = this
defer = $q.defer()
newPasswordEncoded = this.encodePassword newPassword
oldPasswordEncoded = this.encodePassword oldPassword
authClient.$changePassword self.info.email, oldPassword, newPasswordEncoded
.then ->
if self.info.temporaryPassword
self.update temporaryPassword: newPasswordEncoded
self.update newPasswordRequired: null
.then ->
defer.resolve()
.then null, ->
authClient.$changePassword self.info.email, oldPasswordEncoded, newPasswordEncoded
.then ->
if self.info.temporaryPassword
self.update temporaryPassword: newPasswordEncoded
self.update newPasswordRequired: null
.then ->
defer.resolve()
.then null, (reason) ->
defer.reject reason
return defer.promise
resetPassword: (email) ->
authClient.$resetPassword email
# Method to remove user
remove: (email, password, uid) ->
self = this
authClient.$getAuth()
.then (result) ->
if result.uid == uid
self.logout()
sync = $firebase ref.child 'users/'
sync.$remove result.uid
.then null, (reason) ->
console.error 'User.remove.sync.$remove', reason
authClient.$removeUser(email, password)
.then null, (reason) ->
console.error 'User.remove', reason
# Method to update user info. Used in login, signin adn signout methods
do updateInfo = (updatedData = {})->
defer = $q.defer()
auth = authClient.$getAuth()
if auth
userInfo =
id: auth.uid
email: auth.password?.email
loaded: false
angular.extend user.info, userInfo
ref = new Firebase(firebaseUrl + '/users/' + auth.uid)
$firebase(ref).$asObject().$loaded()
.then (results) ->
userInfo =
firstName: results.first_name
lastName: results.last_name
email: if !userInfo.email then results.email else userInfo.email
wallet: results.wallet
facebook: userInfo.id.indexOf('facebook:') > -1
newPasswordRequired: results.newPasswordRequired || updatedData?.newPasswordRequired
role: results.role
avatar: results.avatar
votingWallet: results.votingWallet
temporaryPassword: results.temporaryPassword
votings: results.votings
allowMultiOptionsVote: results.allowMultiOptionsVote
project: results.project
dco: results.dco
loaded: true
angular.extend user.info, userInfo
if results.votingWallet
Sidebar.show()
defer.resolve()
return defer.promise
return user | 200036 | window.app.service 'User', ($rootScope, $q, $route, $firebase, $firebaseAuth, firebaseUrl, Firebase, Sidebar, mandrill, dazzleUrl, Counterparty) ->
ref = new Firebase(firebaseUrl)
authClient = $firebaseAuth ref
user =
# Check if user is logged in
isLoggedIn: -> authClient.$getAuth()?
# User information (name, email etc) object
info:
id: null
firstName: null
lastName: null
email: null
wallet: null
facebook: null
newPasswordRequired: null
votingWallet: null
temporaryPassword: null
role: null # Available roles: ['admin', 'voting-admin']
avatar: null
votings: null
project: null
dco: null
loaded: false
allowMultiOptionsVote: false
allUsers: null
# Method to log user in
login: (email, password, remember) ->
Firebase.goOnline()
encodedPassword = this.encodePassword password
defer = $q.defer()
authClient.$authWithPassword({
email: email
password: <PASSWORD>
}, {remember: remember})
.then ->
updateInfo().then ->
defer.resolve()
.then null, (reason) ->
if reason.code == 'INVALID_PASSWORD'
authClient.$authWithPassword({
email: email
password: <PASSWORD>
}, {remember: remember})
.then ->
updateInfo({newPasswordRequired: true}).then ->
defer.resolve()
.then null, (reason)->
defer.reject(reason)
else
defer.reject(reason)
return defer.promise
# Method to log user in with Facebook account
facebookLogin: () ->
self = this
defer = $q.defer()
authClient.$authWithOAuthPopup 'facebook', scope: 'email'
.then (authData)->
userData =
first_name: authData.facebook.cachedUserProfile.first_name
last_name: authData.facebook.cachedUserProfile.last_name
email: authData.facebook.cachedUserProfile.email
facebook: true
self.update userData
.then ->
defer.resolve()
return defer.promise
# Method to log user out
logout: ->
authClient.$unauth()
angular.extend user.info,
firstName: null
lastName: <NAME>
email: null
wallet: null
facebook: null
newPasswordRequired: null
role: null
avatar: null
votingWallet: null
temporaryPassword: null
votings: null
project: null
dco: null
loaded: null
allowMultiOptionsVote: false
Sidebar.hide()
Sidebar.switchSection('User')
location.reload()
generatePassphrase: (length = 12) ->
switch length
when 3 then complexity = 32
when 6 then complexity = 64
when 9 then complexity = 92
when 12 then complexity = 128
else complexity = 128
return new Mnemonic complexity
.toWords().join(' ')
getAsset: (assetName) ->
self = this
defer = $q.defer()
assetQuantity = 0
new Counterparty(self.info.privateKey).getAssets()
.then (data) ->
if data.length == 0
defer.resolve assetQuantity
else
for asssetObj in data
if asssetObj.asset == assetName
assetQuantity = asssetObj.quantity
defer.resolve assetQuantity
.then null, (reason)->
defer.resolve 0
return defer.promise
getUserDataByEmail: (email)->
# self = this
defer = $q.defer()
# console.log 'sss'
this.allUsers.forEach (user, id)->
if user.email == email
return defer.resolve {uid: id, userData: user}
return defer.promise
# self.getUidByEmail email
# .then (uid)->
# console.log 'aaaa'
# defer.resolve {uid: uid, userData: self.allUsers[uid]}
getAllUsers: ()->
self = this
defer = $q.defer()
ref = new Firebase(firebaseUrl).child 'users'
$firebase(ref).$asObject().$loaded()
.then (data) ->
self.allUsers = data
defer.resolve()
return defer.promise
getUidByEmail: (email)->
defer = $q.defer()
this.allUsers.forEach (user, id)->
if user.email == email
return defer.resolve(id)
return defer.promise
emailNotification: (credentials, template = 'votingwalletinvite', options) ->
defer = $q.defer()
params =
template_name: template
template_content: [{
name : 'registrationLink'
content: '<a href="' + dazzleUrl + '/login" target="_blank">here</a>'
},{
name : 'signupLink'
content: '<a href="' + dazzleUrl + '/login" target="_blank">here</a>'
},{
name : 'loginLink'
content: 'Click <a href="' + dazzleUrl + '/login" target="_blank">here</a> to login and vote.'
}, {
name : '<PASSWORD>',
content: <PASSWORD>.<PASSWORD>
}, {
name : 'email',
content: credentials.login
}]
message:
to: [{
email: credentials.login,
name: credentials.userName || ''
}]
mandrill.sendTemplate params, defer.resolve, defer.reject
# Encode password
encodePassword: (password) ->
bitcore = require 'bitcore'
bitcoreBuffer = bitcore.util.buffer
newBuffer = new bitcoreBuffer.EMPTY_BUFFER.constructor password
key = bitcore.crypto.Hash.sha256 newBuffer
return bitcoreBuffer.bufferToHex key
# Method to create new user
create: (login, password, data) ->
self = this
defer = $q.defer()
passphrase = <PASSWORD>
password = this.encodePassword password
authClient.$createUser(login, password)
.then (userData) ->
userData.email = login
userData.passphrase = <PASSWORD>
defer.resolve userData
if data
self.update data, userData.uid
.then null, (reason) ->
reason.userData = {
email: login
}
defer.reject reason
return defer.promise
# Method to update user data
update: (data, userId) ->
defer = $q.defer()
uid = userId || authClient.$getAuth().uid
ref = new Firebase(firebaseUrl + '/users/' + uid)
$firebase(ref).$update data
.then ->
updateInfo()
defer.resolve()
.then null, (reason) ->
defer.reject reason
return defer.promise
updatePassword: (oldPassword, newPassword) ->
self = this
defer = $q.defer()
newPasswordEncoded = this.encodePassword newPassword
oldPasswordEncoded = this.encodePassword oldPassword
authClient.$changePassword self.info.email, oldPassword, newPasswordEncoded
.then ->
if self.info.temporaryPassword
self.update temporaryPassword: <PASSWORD>
self.update newPasswordRequired: null
.then ->
defer.resolve()
.then null, ->
authClient.$changePassword self.info.email, oldPasswordEncoded, newPasswordEncoded
.then ->
if self.info.temporaryPassword
self.update temporaryPassword: <PASSWORD>
self.update newPasswordRequired: null
.then ->
defer.resolve()
.then null, (reason) ->
defer.reject reason
return defer.promise
resetPassword: (email) ->
authClient.$resetPassword email
# Method to remove user
remove: (email, password, uid) ->
self = this
authClient.$getAuth()
.then (result) ->
if result.uid == uid
self.logout()
sync = $firebase ref.child 'users/'
sync.$remove result.uid
.then null, (reason) ->
console.error 'User.remove.sync.$remove', reason
authClient.$removeUser(email, password)
.then null, (reason) ->
console.error 'User.remove', reason
# Method to update user info. Used in login, signin adn signout methods
do updateInfo = (updatedData = {})->
defer = $q.defer()
auth = authClient.$getAuth()
if auth
userInfo =
id: auth.uid
email: auth.password?.email
loaded: false
angular.extend user.info, userInfo
ref = new Firebase(firebaseUrl + '/users/' + auth.uid)
$firebase(ref).$asObject().$loaded()
.then (results) ->
userInfo =
firstName: results.first_name
lastName: results.last_name
email: if !userInfo.email then results.email else userInfo.email
wallet: results.wallet
facebook: userInfo.id.indexOf('facebook:') > -1
newPasswordRequired: results.newPasswordRequired || updatedData?.newPasswordRequired
role: results.role
avatar: results.avatar
votingWallet: results.votingWallet
temporaryPassword: <PASSWORD>
votings: results.votings
allowMultiOptionsVote: results.allowMultiOptionsVote
project: results.project
dco: results.dco
loaded: true
angular.extend user.info, userInfo
if results.votingWallet
Sidebar.show()
defer.resolve()
return defer.promise
return user | true | window.app.service 'User', ($rootScope, $q, $route, $firebase, $firebaseAuth, firebaseUrl, Firebase, Sidebar, mandrill, dazzleUrl, Counterparty) ->
ref = new Firebase(firebaseUrl)
authClient = $firebaseAuth ref
user =
# Check if user is logged in
isLoggedIn: -> authClient.$getAuth()?
# User information (name, email etc) object
info:
id: null
firstName: null
lastName: null
email: null
wallet: null
facebook: null
newPasswordRequired: null
votingWallet: null
temporaryPassword: null
role: null # Available roles: ['admin', 'voting-admin']
avatar: null
votings: null
project: null
dco: null
loaded: false
allowMultiOptionsVote: false
allUsers: null
# Method to log user in
login: (email, password, remember) ->
Firebase.goOnline()
encodedPassword = this.encodePassword password
defer = $q.defer()
authClient.$authWithPassword({
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
}, {remember: remember})
.then ->
updateInfo().then ->
defer.resolve()
.then null, (reason) ->
if reason.code == 'INVALID_PASSWORD'
authClient.$authWithPassword({
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
}, {remember: remember})
.then ->
updateInfo({newPasswordRequired: true}).then ->
defer.resolve()
.then null, (reason)->
defer.reject(reason)
else
defer.reject(reason)
return defer.promise
# Method to log user in with Facebook account
facebookLogin: () ->
self = this
defer = $q.defer()
authClient.$authWithOAuthPopup 'facebook', scope: 'email'
.then (authData)->
userData =
first_name: authData.facebook.cachedUserProfile.first_name
last_name: authData.facebook.cachedUserProfile.last_name
email: authData.facebook.cachedUserProfile.email
facebook: true
self.update userData
.then ->
defer.resolve()
return defer.promise
# Method to log user out
logout: ->
authClient.$unauth()
angular.extend user.info,
firstName: null
lastName: PI:NAME:<NAME>END_PI
email: null
wallet: null
facebook: null
newPasswordRequired: null
role: null
avatar: null
votingWallet: null
temporaryPassword: null
votings: null
project: null
dco: null
loaded: null
allowMultiOptionsVote: false
Sidebar.hide()
Sidebar.switchSection('User')
location.reload()
generatePassphrase: (length = 12) ->
switch length
when 3 then complexity = 32
when 6 then complexity = 64
when 9 then complexity = 92
when 12 then complexity = 128
else complexity = 128
return new Mnemonic complexity
.toWords().join(' ')
getAsset: (assetName) ->
self = this
defer = $q.defer()
assetQuantity = 0
new Counterparty(self.info.privateKey).getAssets()
.then (data) ->
if data.length == 0
defer.resolve assetQuantity
else
for asssetObj in data
if asssetObj.asset == assetName
assetQuantity = asssetObj.quantity
defer.resolve assetQuantity
.then null, (reason)->
defer.resolve 0
return defer.promise
getUserDataByEmail: (email)->
# self = this
defer = $q.defer()
# console.log 'sss'
this.allUsers.forEach (user, id)->
if user.email == email
return defer.resolve {uid: id, userData: user}
return defer.promise
# self.getUidByEmail email
# .then (uid)->
# console.log 'aaaa'
# defer.resolve {uid: uid, userData: self.allUsers[uid]}
getAllUsers: ()->
self = this
defer = $q.defer()
ref = new Firebase(firebaseUrl).child 'users'
$firebase(ref).$asObject().$loaded()
.then (data) ->
self.allUsers = data
defer.resolve()
return defer.promise
getUidByEmail: (email)->
defer = $q.defer()
this.allUsers.forEach (user, id)->
if user.email == email
return defer.resolve(id)
return defer.promise
emailNotification: (credentials, template = 'votingwalletinvite', options) ->
defer = $q.defer()
params =
template_name: template
template_content: [{
name : 'registrationLink'
content: '<a href="' + dazzleUrl + '/login" target="_blank">here</a>'
},{
name : 'signupLink'
content: '<a href="' + dazzleUrl + '/login" target="_blank">here</a>'
},{
name : 'loginLink'
content: 'Click <a href="' + dazzleUrl + '/login" target="_blank">here</a> to login and vote.'
}, {
name : 'PI:PASSWORD:<PASSWORD>END_PI',
content: PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI
}, {
name : 'email',
content: credentials.login
}]
message:
to: [{
email: credentials.login,
name: credentials.userName || ''
}]
mandrill.sendTemplate params, defer.resolve, defer.reject
# Encode password
encodePassword: (password) ->
bitcore = require 'bitcore'
bitcoreBuffer = bitcore.util.buffer
newBuffer = new bitcoreBuffer.EMPTY_BUFFER.constructor password
key = bitcore.crypto.Hash.sha256 newBuffer
return bitcoreBuffer.bufferToHex key
# Method to create new user
create: (login, password, data) ->
self = this
defer = $q.defer()
passphrase = PI:PASSWORD:<PASSWORD>END_PI
password = this.encodePassword password
authClient.$createUser(login, password)
.then (userData) ->
userData.email = login
userData.passphrase = PI:PASSWORD:<PASSWORD>END_PI
defer.resolve userData
if data
self.update data, userData.uid
.then null, (reason) ->
reason.userData = {
email: login
}
defer.reject reason
return defer.promise
# Method to update user data
update: (data, userId) ->
defer = $q.defer()
uid = userId || authClient.$getAuth().uid
ref = new Firebase(firebaseUrl + '/users/' + uid)
$firebase(ref).$update data
.then ->
updateInfo()
defer.resolve()
.then null, (reason) ->
defer.reject reason
return defer.promise
updatePassword: (oldPassword, newPassword) ->
self = this
defer = $q.defer()
newPasswordEncoded = this.encodePassword newPassword
oldPasswordEncoded = this.encodePassword oldPassword
authClient.$changePassword self.info.email, oldPassword, newPasswordEncoded
.then ->
if self.info.temporaryPassword
self.update temporaryPassword: PI:PASSWORD:<PASSWORD>END_PI
self.update newPasswordRequired: null
.then ->
defer.resolve()
.then null, ->
authClient.$changePassword self.info.email, oldPasswordEncoded, newPasswordEncoded
.then ->
if self.info.temporaryPassword
self.update temporaryPassword: PI:PASSWORD:<PASSWORD>END_PI
self.update newPasswordRequired: null
.then ->
defer.resolve()
.then null, (reason) ->
defer.reject reason
return defer.promise
resetPassword: (email) ->
authClient.$resetPassword email
# Method to remove user
remove: (email, password, uid) ->
self = this
authClient.$getAuth()
.then (result) ->
if result.uid == uid
self.logout()
sync = $firebase ref.child 'users/'
sync.$remove result.uid
.then null, (reason) ->
console.error 'User.remove.sync.$remove', reason
authClient.$removeUser(email, password)
.then null, (reason) ->
console.error 'User.remove', reason
# Method to update user info. Used in login, signin adn signout methods
do updateInfo = (updatedData = {})->
defer = $q.defer()
auth = authClient.$getAuth()
if auth
userInfo =
id: auth.uid
email: auth.password?.email
loaded: false
angular.extend user.info, userInfo
ref = new Firebase(firebaseUrl + '/users/' + auth.uid)
$firebase(ref).$asObject().$loaded()
.then (results) ->
userInfo =
firstName: results.first_name
lastName: results.last_name
email: if !userInfo.email then results.email else userInfo.email
wallet: results.wallet
facebook: userInfo.id.indexOf('facebook:') > -1
newPasswordRequired: results.newPasswordRequired || updatedData?.newPasswordRequired
role: results.role
avatar: results.avatar
votingWallet: results.votingWallet
temporaryPassword: PI:PASSWORD:<PASSWORD>END_PI
votings: results.votings
allowMultiOptionsVote: results.allowMultiOptionsVote
project: results.project
dco: results.dco
loaded: true
angular.extend user.info, userInfo
if results.votingWallet
Sidebar.show()
defer.resolve()
return defer.promise
return user |
[
{
"context": "###\nAdmin Plugin\n\n@author Markus M. May\n@website http://www.javafreedom.org\n@copyrigh",
"end": 44,
"score": 0.9998876452445984,
"start": 31,
"tag": "NAME",
"value": "Markus M. May"
},
{
"context": "ebsite http://www.javafreedom.org\n@copyright Markus M. May 2013\n\nProvides some basic functionalities like ch",
"end": 111,
"score": 0.9998823404312134,
"start": 98,
"tag": "NAME",
"value": "Markus M. May"
}
] | plugins/admin.coffee | andreineculau/coffee-bot | 0 | ###
Admin Plugin
@author Markus M. May
@website http://www.javafreedom.org
@copyright Markus M. May 2013
Provides some basic functionalities like changing nick
###
Plugin = require '../lib/plugin'
Channel = require '../lib/channel'
module.exports = class PluginGlobal extends Plugin
module.exports = class PluginAdmin extends Plugin
constructor: (ph) ->
super
@addTrigger 'admin', @trigAdmin
trigAdmin: (msg) ->
{args, answer} = @parse msg
command = args.shift()
switch command
when 'nick'
return if typeof args[0] is 'undefined'
@irc.raw 'NICK', args[0]
answer 'there! better?'
when 'join'
return if typeof args[0] is 'undefined'
chan = new Channel(@irc, args[0], true, args[1])
@irc.channels[chan.name] = chan
answer "joined #{chan.name}"
when 'part'
return if typeof args[0] is 'undefined'
chan = @irc.channels[args[0]]
if typeof chan isnt 'undefined'
# could lead to errors, need to fix
chan.part 'admin requested me to leave!'
delete @irc.channels[args[0]]
answer "parted #{chan.name}"
| 88862 | ###
Admin Plugin
@author <NAME>
@website http://www.javafreedom.org
@copyright <NAME> 2013
Provides some basic functionalities like changing nick
###
Plugin = require '../lib/plugin'
Channel = require '../lib/channel'
module.exports = class PluginGlobal extends Plugin
module.exports = class PluginAdmin extends Plugin
constructor: (ph) ->
super
@addTrigger 'admin', @trigAdmin
trigAdmin: (msg) ->
{args, answer} = @parse msg
command = args.shift()
switch command
when 'nick'
return if typeof args[0] is 'undefined'
@irc.raw 'NICK', args[0]
answer 'there! better?'
when 'join'
return if typeof args[0] is 'undefined'
chan = new Channel(@irc, args[0], true, args[1])
@irc.channels[chan.name] = chan
answer "joined #{chan.name}"
when 'part'
return if typeof args[0] is 'undefined'
chan = @irc.channels[args[0]]
if typeof chan isnt 'undefined'
# could lead to errors, need to fix
chan.part 'admin requested me to leave!'
delete @irc.channels[args[0]]
answer "parted #{chan.name}"
| true | ###
Admin Plugin
@author PI:NAME:<NAME>END_PI
@website http://www.javafreedom.org
@copyright PI:NAME:<NAME>END_PI 2013
Provides some basic functionalities like changing nick
###
Plugin = require '../lib/plugin'
Channel = require '../lib/channel'
module.exports = class PluginGlobal extends Plugin
module.exports = class PluginAdmin extends Plugin
constructor: (ph) ->
super
@addTrigger 'admin', @trigAdmin
trigAdmin: (msg) ->
{args, answer} = @parse msg
command = args.shift()
switch command
when 'nick'
return if typeof args[0] is 'undefined'
@irc.raw 'NICK', args[0]
answer 'there! better?'
when 'join'
return if typeof args[0] is 'undefined'
chan = new Channel(@irc, args[0], true, args[1])
@irc.channels[chan.name] = chan
answer "joined #{chan.name}"
when 'part'
return if typeof args[0] is 'undefined'
chan = @irc.channels[args[0]]
if typeof chan isnt 'undefined'
# could lead to errors, need to fix
chan.part 'admin requested me to leave!'
delete @irc.channels[args[0]]
answer "parted #{chan.name}"
|
[
{
"context": ": ->\n text:\n header: \"Login\"\n name: \"Username\"\n pw: \"Password\"\n button: \"login\"\n ",
"end": 1555,
"score": 0.9989860653877258,
"start": 1547,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "header: \"Login\"\n name: \"Username\"\n pw: \"Password\"\n button: \"login\"\n error: \"Login failed",
"end": 1576,
"score": 0.9992324113845825,
"start": 1568,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "ve\n @reject = reject\n watch:\n name: \"onActiveName\"\n pw: \"onActivePW\"\n \"modal.open\": (val) ->\n",
"end": 3417,
"score": 0.9836426377296448,
"start": 3405,
"tag": "USERNAME",
"value": "onActiveName"
}
] | src/login-modal-component.coffee | ceri-widgets/ceri-login-modal | 0 |
module.exports =
mixins: [
require "ceri/lib/structure"
require "ceri/lib/computed"
require "ceri/lib/class"
require "ceri/lib/#model"
require "ceri/lib/#if"
]
structure: template 1, """
<ceri-modal #ref=modal>
<div #ref=content>
<h4 #ref=header :text="text.header"></h4>
<div class=row>
<div #ref=nameContainer>
<ceri-icon :name=icon.name #ref=nameIcon></ceri-icon>
<input
#ref=nameInput
#model=name
@keyup=focusPW
@input=nameChanged
@focus=onActiveName
@blur=onActiveName
/>
<label #ref=nameLabel :text="text.name"></label>
</div>
</div>
<div class=row>
<div #ref=pwContainer>
<ceri-icon :name=icon.pw #ref=pwIcon></ceri-icon>
<input
#ref=pwInput
#model=pw
@keyup=loginEvent
type="password"
@focus=onActivePW
@blur=onActivePW
/>
<label #ref=pwLabel :text="text.pw"></label>
</div>
</div>
<div class=row>
<div #ref=btnContainer>
<button
@click=loginEvent
#ref=btn
:text=text.button
:disabled=disabled
>
</button>
</div>
</div>
</div>
</ceri-modal>
"""
data: ->
text:
header: "Login"
name: "Username"
pw: "Password"
button: "login"
error: "Login failed"
timeout: "Login failed"
icon:
name: ""
pw: ""
name: ""
pw: ""
activeLabel: ""
timeout: 2000
disabled: false
methods:
setActiveLabel: (input,label) ->
return unless input and label
if input != document.activeElement and input.value == ""
@$class.setStr label, ""
else
@$class.setStr label, @activeLabel
onActiveName: ->
@setActiveLabel @nameInput, @nameLabel
onActivePW: ->
@setActiveLabel @pwInput, @pwLabel
@disabled = @pw == ""
focusPW: (e) ->
if e.keyCode == 13
if @pw == ""
@pwInput.focus()
else
@loginEvent(e)
loginEvent: (e) ->
return if e.type == "keyup" and e.keyCode != 13
close = @$progress
el: @modal
zIndex: 2000
timeout: @timeout
onTimeout: =>
@disabled = false
@$toast text: @text.error
@disabled = true
success = (result) =>
close()
@cb?(result)
@resolve?(result)
@resolve = null
@reject = null
@cb = null
@pw = ""
@modal.hide()
failed = =>
close()
@pw = ""
@pwInput.focus()
@$toast text: @text.error
cb = (result) ->
if result
success(result)
else
failed()
promise = @login? @name, @pw, cb
promise?.then?(success).catch(failed)
nameChanged: -> @pw = ""
open: (cb) ->
@cb = cb
document.body.appendChild(@)
@$nextTick =>
@modal.show()
@nameInput.focus()
@onActivePW()
if @Promise
return new @Promise (resolve, reject) =>
@resolve = resolve
@reject = reject
watch:
name: "onActiveName"
pw: "onActivePW"
"modal.open": (val) ->
if val == false
@cb?(false)
@cb = null
@reject?()
@reject = null
@resolve = null
connectedCallback: ->
if @_isFirstConnect
@Promise ?= Promise | 65623 |
module.exports =
mixins: [
require "ceri/lib/structure"
require "ceri/lib/computed"
require "ceri/lib/class"
require "ceri/lib/#model"
require "ceri/lib/#if"
]
structure: template 1, """
<ceri-modal #ref=modal>
<div #ref=content>
<h4 #ref=header :text="text.header"></h4>
<div class=row>
<div #ref=nameContainer>
<ceri-icon :name=icon.name #ref=nameIcon></ceri-icon>
<input
#ref=nameInput
#model=name
@keyup=focusPW
@input=nameChanged
@focus=onActiveName
@blur=onActiveName
/>
<label #ref=nameLabel :text="text.name"></label>
</div>
</div>
<div class=row>
<div #ref=pwContainer>
<ceri-icon :name=icon.pw #ref=pwIcon></ceri-icon>
<input
#ref=pwInput
#model=pw
@keyup=loginEvent
type="password"
@focus=onActivePW
@blur=onActivePW
/>
<label #ref=pwLabel :text="text.pw"></label>
</div>
</div>
<div class=row>
<div #ref=btnContainer>
<button
@click=loginEvent
#ref=btn
:text=text.button
:disabled=disabled
>
</button>
</div>
</div>
</div>
</ceri-modal>
"""
data: ->
text:
header: "Login"
name: "Username"
pw: "<PASSWORD>"
button: "login"
error: "Login failed"
timeout: "Login failed"
icon:
name: ""
pw: ""
name: ""
pw: ""
activeLabel: ""
timeout: 2000
disabled: false
methods:
setActiveLabel: (input,label) ->
return unless input and label
if input != document.activeElement and input.value == ""
@$class.setStr label, ""
else
@$class.setStr label, @activeLabel
onActiveName: ->
@setActiveLabel @nameInput, @nameLabel
onActivePW: ->
@setActiveLabel @pwInput, @pwLabel
@disabled = @pw == ""
focusPW: (e) ->
if e.keyCode == 13
if @pw == ""
@pwInput.focus()
else
@loginEvent(e)
loginEvent: (e) ->
return if e.type == "keyup" and e.keyCode != 13
close = @$progress
el: @modal
zIndex: 2000
timeout: @timeout
onTimeout: =>
@disabled = false
@$toast text: @text.error
@disabled = true
success = (result) =>
close()
@cb?(result)
@resolve?(result)
@resolve = null
@reject = null
@cb = null
@pw = ""
@modal.hide()
failed = =>
close()
@pw = ""
@pwInput.focus()
@$toast text: @text.error
cb = (result) ->
if result
success(result)
else
failed()
promise = @login? @name, @pw, cb
promise?.then?(success).catch(failed)
nameChanged: -> @pw = ""
open: (cb) ->
@cb = cb
document.body.appendChild(@)
@$nextTick =>
@modal.show()
@nameInput.focus()
@onActivePW()
if @Promise
return new @Promise (resolve, reject) =>
@resolve = resolve
@reject = reject
watch:
name: "onActiveName"
pw: "onActivePW"
"modal.open": (val) ->
if val == false
@cb?(false)
@cb = null
@reject?()
@reject = null
@resolve = null
connectedCallback: ->
if @_isFirstConnect
@Promise ?= Promise | true |
module.exports =
mixins: [
require "ceri/lib/structure"
require "ceri/lib/computed"
require "ceri/lib/class"
require "ceri/lib/#model"
require "ceri/lib/#if"
]
structure: template 1, """
<ceri-modal #ref=modal>
<div #ref=content>
<h4 #ref=header :text="text.header"></h4>
<div class=row>
<div #ref=nameContainer>
<ceri-icon :name=icon.name #ref=nameIcon></ceri-icon>
<input
#ref=nameInput
#model=name
@keyup=focusPW
@input=nameChanged
@focus=onActiveName
@blur=onActiveName
/>
<label #ref=nameLabel :text="text.name"></label>
</div>
</div>
<div class=row>
<div #ref=pwContainer>
<ceri-icon :name=icon.pw #ref=pwIcon></ceri-icon>
<input
#ref=pwInput
#model=pw
@keyup=loginEvent
type="password"
@focus=onActivePW
@blur=onActivePW
/>
<label #ref=pwLabel :text="text.pw"></label>
</div>
</div>
<div class=row>
<div #ref=btnContainer>
<button
@click=loginEvent
#ref=btn
:text=text.button
:disabled=disabled
>
</button>
</div>
</div>
</div>
</ceri-modal>
"""
data: ->
text:
header: "Login"
name: "Username"
pw: "PI:PASSWORD:<PASSWORD>END_PI"
button: "login"
error: "Login failed"
timeout: "Login failed"
icon:
name: ""
pw: ""
name: ""
pw: ""
activeLabel: ""
timeout: 2000
disabled: false
methods:
setActiveLabel: (input,label) ->
return unless input and label
if input != document.activeElement and input.value == ""
@$class.setStr label, ""
else
@$class.setStr label, @activeLabel
onActiveName: ->
@setActiveLabel @nameInput, @nameLabel
onActivePW: ->
@setActiveLabel @pwInput, @pwLabel
@disabled = @pw == ""
focusPW: (e) ->
if e.keyCode == 13
if @pw == ""
@pwInput.focus()
else
@loginEvent(e)
loginEvent: (e) ->
return if e.type == "keyup" and e.keyCode != 13
close = @$progress
el: @modal
zIndex: 2000
timeout: @timeout
onTimeout: =>
@disabled = false
@$toast text: @text.error
@disabled = true
success = (result) =>
close()
@cb?(result)
@resolve?(result)
@resolve = null
@reject = null
@cb = null
@pw = ""
@modal.hide()
failed = =>
close()
@pw = ""
@pwInput.focus()
@$toast text: @text.error
cb = (result) ->
if result
success(result)
else
failed()
promise = @login? @name, @pw, cb
promise?.then?(success).catch(failed)
nameChanged: -> @pw = ""
open: (cb) ->
@cb = cb
document.body.appendChild(@)
@$nextTick =>
@modal.show()
@nameInput.focus()
@onActivePW()
if @Promise
return new @Promise (resolve, reject) =>
@resolve = resolve
@reject = reject
watch:
name: "onActiveName"
pw: "onActivePW"
"modal.open": (val) ->
if val == false
@cb?(false)
@cb = null
@reject?()
@reject = null
@resolve = null
connectedCallback: ->
if @_isFirstConnect
@Promise ?= Promise |
[
{
"context": "t = fp.toString('hex')\n ret.body.key.key_id = @km().get_pgp_key_id().toString('hex')\n\n if @eldes",
"end": 11874,
"score": 0.6129372715950012,
"start": 11871,
"tag": "KEY",
"value": "@km"
},
{
"context": "toString('hex')\n ret.body.key.key_id = @km().get_pgp_key_id().toString('hex')\n\n if @eldest_kid?",
"end": 11880,
"score": 0.5456647276878357,
"start": 11877,
"tag": "KEY",
"value": "get"
},
{
"context": "ring('hex')\n ret.body.key.key_id = @km().get_pgp_key_id().toString('hex')\n\n if @eldest_kid?\n ",
"end": 11884,
"score": 0.545828104019165,
"start": 11881,
"tag": "KEY",
"value": "pgp"
},
{
"context": "x')\n ret.body.key.key_id = @km().get_pgp_key_id().toString('hex')\n\n if @eldest_kid?\n ret.",
"end": 11891,
"score": 0.5915659070014954,
"start": 11889,
"tag": "KEY",
"value": "id"
},
{
"context": " ret.body.key.key_id = @km().get_pgp_key_id().toString('hex')\n\n if @eldest_kid?\n ret.body.key.el",
"end": 11902,
"score": 0.9308868050575256,
"start": 11894,
"tag": "KEY",
"value": "toString"
},
{
"context": "ody.key.key_id = @km().get_pgp_key_id().toString('hex')\n\n if @eldest_kid?\n ret.body.key.eldest_",
"end": 11907,
"score": 0.5282544493675232,
"start": 11904,
"tag": "KEY",
"value": "hex"
}
] | node_modules/keybase-proofs/src/base.iced | AngelKey/Angelkey.nodeclient | 151 | {proof_type_to_string,constants} = require './constants'
pgp_utils = require('pgp-utils')
{trim,katch,akatch,bufeq_secure,json_stringify_sorted,unix_time,base64u,streq_secure} = pgp_utils.util
triplesec = require('triplesec')
{WordArray} = triplesec
{SHA256} = triplesec.hash
kbpgp = require 'kbpgp'
{make_esc} = require 'iced-error'
util = require 'util'
{base64_extract} = require './b64extract'
#==========================================================================
exports.hash_sig = hash_sig = (sig_body) ->
(new SHA256).bufhash(sig_body)
#------
add_ids = (sig_body, out) ->
hash = hash_sig sig_body
id = hash.toString('hex')
short_id = sig_id_to_short_id hash
out.id = id
out.med_id = sig_id_to_med_id hash
out.short_id = short_id
#------
make_ids = (sig_body) ->
out = {}
add_ids sig_body, out
return out
#------
sig_id_to_med_id = (sig_id) -> base64u.encode sig_id
#------
sig_id_to_short_id = (sig_id) ->
base64u.encode sig_id[0...constants.short_id_bytes]
#================================================================================
proof_text_check_to_med_id = (proof_text_check) ->
{med_id} = make_ids(new Buffer proof_text_check, 'base64')
med_id
#================================================================================
exports.cieq = cieq = (a,b) -> (a? and b? and (a.toLowerCase() is b.toLowerCase()))
#==========================================================================
class Verifier
constructor : ({@armored, @id, @short_id, @skip_ids, @make_ids, @strict}, @sig_eng, @base) ->
#---------------
km : () -> @sig_eng.get_km()
#---------------
get_etime : () ->
if @json.ctime? and @json.expire_in then (@json.ctime + @json.expire_in)
else null
#---------------
verify : (cb) ->
esc = make_esc cb, "Verifier::verfiy"
await @_parse_and_process esc defer()
await @_check_json esc defer json_obj, json_str
await @_check_expired esc defer()
cb null, json_obj, json_str
#---------------
_check_ids : (body, cb) ->
{short_id, id} = make_ids body
err = if not (@id? and streq_secure id, @id)
new Error "Long IDs aren't equal; wanted #{id} but got #{@id}"
else if not (@short_id? and streq_secure short_id, @short_id)
new Error "Short IDs aren't equal: wanted #{short_id} but got #{@short_id}"
else null
cb err
#---------------
_check_expired : (cb) ->
err = null
now = unix_time()
if not @json.ctime? then err = new Error "No `ctime` in signature"
else if not @json.expire_in? then err = new Error "No `expire_in` in signature"
else if not @json.expire_in then @etime = null
else if (expired = (now - @json.ctime - @json.expire_in)) > 0
err = new Error "Expired #{expired}s ago"
else
@etime = @json.ctime + @json.expire_in
cb err
#---------------
_parse_and_process : (cb) ->
err = null
await @sig_eng.unbox @armored, defer err, @payload, body
if not err? and not @skip_ids
await @_check_ids body, defer err
if not err? and @make_ids
{@short_id, @id} = make_ids body
cb err
#---------------
_check_json : (cb) ->
json_str_buf = @payload
# Before we run any checks on the input json, let's trim any leading
# or trailing whitespace.
json_str_utf8 = json_str_buf.toString('utf8')
json_str_utf8_trimmed = trim json_str_utf8
err = null
if not /^[\x20-\x7e]+$/.test json_str_utf8_trimmed
err = new Error "All JSON proof characters must be in the visible ASCII set (properly escaped UTF8 is permissible)"
else
[e, @json] = katch (() -> JSON.parse json_str_buf)
err = new Error "Couldn't parse JSON signed message: #{e.message}" if e?
if not err?
if @strict and ((ours = trim(json_stringify_sorted(@json))) isnt json_str_utf8_trimmed)
err = new Error "non-canonlical JSON found in strict mode (#{ours} v #{json_str_utf8_trimmed})"
else
await @base._v_check {@json}, defer err
cb err, @json, json_str_utf8
#==========================================================================
class Base
#------
constructor : ({@sig_eng, @seqno, @user, @host, @prev, @client, @merkle_root, @revoke, @seq_type, @eldest_kid, @expire_in, @ctime}) ->
#------
proof_type_str : () ->
if (t = @proof_type())? then proof_type_to_string[t]
else null
#------
_v_check_key : (key) ->
checks = 0
if key?.kid?
checks++
err = @_v_check_kid key.kid
if not err? and key?.fingerprint?
checks++
err = @_v_check_fingerprint key
if not err? and checks is 0
err = new Error "need either a 'body.key.kid' or a 'body.key.fingerprint'"
err
#------
_v_check_kid : (kid) ->
if not bufeq_secure (a = @km().get_ekid()), (new Buffer kid, "hex")
err = new Error "Verification key doesn't match packet (via kid): #{a.toString('hex')} != #{kid}"
else
null
#------
_v_check_fingerprint : (key) ->
if not (key_id = key?.key_id)?
new Error "Needed a body.key.key_id but none given"
else if not bufeq_secure (a = @km().get_pgp_key_id()), (new Buffer key_id, "hex")
new Error "Verification key doesn't match packet (via key ID): #{a.toString('hex')} != #{key_id}"
else if not (fp = key?.fingerprint)?
new Error "Needed a body.key.fingerprint but none given"
else if not bufeq_secure @km().get_pgp_fingerprint(), (new Buffer fp, "hex")
new Error "Verifiation key doesn't match packet (via fingerprint)"
else
null
#------
# true if PGP details (full_hash and fingerprint) should be inserted at
# @_v_pgp_details_dest()
_v_include_pgp_details : -> false
# true if this link type is only valid if it includes PGP details
_v_require_pgp_details : -> false
# Given the JSON body, the object where PGP key details should end up
_v_pgp_details_dest : (body) -> body.key
# If @_v_include_pgp_details() is true, a KeyManager containing a PGP key
_v_pgp_km : () -> null
# Generates (and caches) a hash for PGP keys, returns null for other kinds of keys
full_pgp_hash : (opts, cb) ->
if @_full_pgp_hash is undefined
esc = make_esc cb
await @_v_pgp_km()?.pgp_full_hash {}, esc defer @_full_pgp_hash
cb null, @_full_pgp_hash
# Adds the PGP hash and fingerprint to `body`. Noop for non-PGP keys (unless
# @_v_require_pgp_details returns true, then returns an error.)
_add_pgp_details : ({body}, cb) ->
return cb(null) unless @_v_include_pgp_details()
dest = @_v_pgp_details_dest(body)
await @full_pgp_hash {}, defer err, full_hash
if err then # noop
else if full_hash?
dest.full_hash = full_hash
dest.fingerprint = @_v_pgp_km().get_pgp_fingerprint().toString('hex') unless dest.fingerprint?
else if @_v_require_pgp_details()
err = new Error "#{@proof_type_str()} proofs require a PGP key"
cb err
_check_pgp_details: ({json}, cb) ->
err = null
details = @_v_pgp_details_dest(json.body)
if not (hash_in = details?.full_hash)? or not (fp_in = details?.fingerprint)? or not (kid_in = details?.kid)?
if @_v_require_pgp_details()
err = new Error "#{@proof_type_str()} proofs require a PGP key's KID, fingerprint, and full_hash but one or more were missing."
else
await @full_pgp_hash {}, defer err, hash_real
if err? then # noop
else if not hash_real?
err = new Error "A PGP key hash (#{hash_in}) was in the sig body but no key was provided"
else if hash_in isnt hash_real
err = new Error "New PGP key's hash (#{hash_real}) doesn't match hash in signature (#{hash_in})"
else if fp_in isnt (fp_real = @_v_pgp_km().get_pgp_fingerprint().toString('hex'))
err = new Error "New PGP key's fingerprint (#{fp_real}) doesn't match fingerprint in signature (#{fp_in})"
else if kid_in isnt (kid_real = @_v_pgp_km().get_ekid().toString('hex'))
err = new Error "New PGP key's KID (#{kid_real}) doesn't match KID in signature (#{kid_in})"
cb err
#------
_v_check : ({json}, cb) ->
# The default seq_type is PUBLIC
seq_type = (v) -> if v? then v else constants.seq_types.PUBLIC
err = if not cieq (a = json?.body?.key?.username), (b = @user.local.username)
new Error "Wrong local user: got '#{a}' but wanted '#{b}'"
else if (a = json?.body?.key?.uid) isnt (b = @user.local.uid)
new Error "Wrong local uid: got '#{a}' but wanted '#{b}'"
else if not cieq (a = json?.body?.key?.host), (b = @host)
new Error "Wrong host: got '#{a}' but wanted '#{b}'"
else if (a = @_type())? and ((b = json?.body?.type) isnt a)
# Don't check if it's a "generic_binding", which doesn't much
# care what the signature type is. Imagine the case of just trying to
# get the user's keybinding. Then any signature will do.
new Error "Wrong signature type; got '#{a}' but wanted '#{b}'"
else if (a = @prev) and (a isnt (b = json?.prev))
new Error "Wrong previous hash; wanted '#{a}' but got '#{b}'"
else if (a = @seqno) and (a isnt (b = json?.seqno))
new Error "Wrong seqno; wanted '#{a}' but got '#{b}"
else if @seqno and (a = seq_type(json?.seq_type)) isnt (b = seq_type(@seq_type))
new Error "Wrong seq_type: wanted '#{a}' but got '#{b}'"
else if not (key = json?.body?.key)?
new Error "no 'body.key' block in signature"
else if (section_error = @_check_sections(json))?
section_error
else
@_v_check_key key
if not err?
await @_check_pgp_details {json}, defer err
cb err
#------
_required_sections : () -> ["key", "type", "version"]
#------
_optional_sections : () -> ["client", "merkle_root"]
_is_wildcard_link : () -> false
#------
# Return a JavaScript Error on failure, or null if no failure.
_check_sections : (json) ->
for section in @_required_sections()
unless json?.body?[section]
return new Error "Missing '#{section}' section #{if json.seqno? then "in seqno " + json.seqno else ""}, required for #{json.body.type} signatures"
# Sometimes we don't really need to check, we just need a "key" section
unless @_is_wildcard_link()
for section, _ of json?.body
unless (section in @_required_sections()) or (section in @_optional_sections())
return new Error "'#{section}' section #{if json.seqno? then "in seqno " + json.seqno else ""} is not allowed for #{json.body.type} signatures"
null
#------
is_remote_proof : () -> false
#------
has_revoke : () ->
if not @revoke? then false
else if @revoke.sig_id? then true
else if (@revoke.sig_ids?.length > 0) then true
else if @revoke.kid? then true
else if (@revoke.kids?.length > 0) then true
else false
#------
_v_customize_json : (ret) ->
#------
generate_json : ({expire_in} = {}, cb) ->
err = null
# Cache the unix_time() we generate in case we need to call @generate_json()
# twice. This happens for reverse signatures!
ctime = if @ctime? then @ctime else (@ctime = unix_time())
pick = (v...) ->
for e in v when e?
return e
return null
ret = {
seqno : @seqno
prev : @prev
ctime : ctime
tag : constants.tags.sig
expire_in : pick(expire_in, @expire_in, constants.expire_in)
body :
version : constants.versions.sig
type : @_type()
key :
host : @host
username : @user.local.username
uid : @user.local.uid
}
# Can't access ekids from GnuPG. We'd have to parse the keys (possible).
if (ekid = @km().get_ekid())?
ret.body.key.kid = ekid.toString('hex')
if (fp = @km().get_pgp_fingerprint())?
ret.body.key.fingerprint = fp.toString('hex')
ret.body.key.key_id = @km().get_pgp_key_id().toString('hex')
if @eldest_kid?
ret.body.key.eldest_kid = @eldest_kid
# Can be:
#
# NONE : 0
# PUBLIC : 1 # this is the default!
# PRIVATE : 2
# SEMIPRIVATE : 3
#
ret.seq_type = @seq_type if @seq_type?
ret.body.client = @client if @client?
ret.body.merkle_root = @merkle_root if @merkle_root?
ret.body.revoke = @revoke if @has_revoke()
@_v_customize_json ret
await @_add_pgp_details {body: ret.body}, defer err
cb err, json_stringify_sorted ret
#------
_v_generate : (opts, cb) -> cb null
#------
generate : (cb) ->
esc = make_esc cb, "generate"
out = null
await @_v_generate {}, esc defer()
await @generate_json {}, esc defer json
await @sig_eng.box json, esc defer {pgp, raw, armored}
{short_id, id} = make_ids raw
out = { pgp, json, id, short_id, raw, armored }
cb null, out
#------
# @param {Object} obj with options as specified:
# @option obj {string} pgp The PGP signature that's being uploaded
# @option obj {string} id The keybase-appropriate ID that's the PGP signature's hash
# @option obj {string} short_id The shortened sig ID that's for the tweet (or similar)
# @option obj {bool} skip_ids Don't bother checking IDs
# @option obj {bool} make_ids Make Ids when verifying
# @option obj {bool} strict Turn on all strict-mode checks
verify : (obj, cb) ->
verifier = new Verifier obj, @sig_eng, @
await verifier.verify defer err, json_obj, json_str
id = short_id = null
if obj.make_ids
id = obj.id = verifier.id
short_id = obj.short_id = verifier.short_id
out = if err? then {}
else {json_obj, json_str, id, short_id, etime : verifier.get_etime(), @reverse_sig_kid }
cb err, out
#-------
km : () -> @sig_eng.get_km()
#-------
check_inputs : () -> null
#-------
# Check this proof against the existing proofs
check_existing : () -> null
#-------
# Some proofs are shortened, like Twitter, due to the space-constraints on the medium.
is_short : () -> false
#-------
# Check the server's work when we ask for it to generate a proof text.
# Make sure our sig shows up in there but no one else's. This will
# vary between long and short signatures.
sanity_check_proof_text : ({ args, proof_text}, cb) ->
if @is_short()
check_for = args.sig_id_short
len_floor = constants.short_id_bytes
slack = 3
else
[ err, msg ] = kbpgp.ukm.decode_sig { armored: args.sig }
if not err? and (msg.type isnt kbpgp.const.openpgp.message_types.generic)
err = new Error "wrong message type; expected a generic message; got #{msg.type}"
if not err?
check_for = msg.body.toString('base64')
len_floor = constants.shortest_pgp_signature
slack = 30 # 30 bytes of prefix/suffix data available
unless err?
b64s = base64_extract proof_text
for b in b64s when (b.length >= len_floor)
if b.indexOf(check_for) < 0 or (s = (b.length - check_for.length)) > slack
err = new Error "Found a bad signature in proof text: #{b[0...60]} != #{check_for[0...60]} (slack=#{s})"
break
cb err
#==========================================================================
class GenericBinding extends Base
_type : () -> null
resource_id : () -> ""
_service_obj_check : () -> true
_is_wildcard_link : () -> true
#==========================================================================
exports.Base = Base
exports.GenericBinding = GenericBinding
exports.sig_id_to_short_id = sig_id_to_short_id
exports.sig_id_to_med_id = sig_id_to_med_id
exports.make_ids = make_ids
exports.add_ids = add_ids
exports.proof_text_check_to_med_id = proof_text_check_to_med_id
#==========================================================================
| 172878 | {proof_type_to_string,constants} = require './constants'
pgp_utils = require('pgp-utils')
{trim,katch,akatch,bufeq_secure,json_stringify_sorted,unix_time,base64u,streq_secure} = pgp_utils.util
triplesec = require('triplesec')
{WordArray} = triplesec
{SHA256} = triplesec.hash
kbpgp = require 'kbpgp'
{make_esc} = require 'iced-error'
util = require 'util'
{base64_extract} = require './b64extract'
#==========================================================================
exports.hash_sig = hash_sig = (sig_body) ->
(new SHA256).bufhash(sig_body)
#------
add_ids = (sig_body, out) ->
hash = hash_sig sig_body
id = hash.toString('hex')
short_id = sig_id_to_short_id hash
out.id = id
out.med_id = sig_id_to_med_id hash
out.short_id = short_id
#------
make_ids = (sig_body) ->
out = {}
add_ids sig_body, out
return out
#------
sig_id_to_med_id = (sig_id) -> base64u.encode sig_id
#------
sig_id_to_short_id = (sig_id) ->
base64u.encode sig_id[0...constants.short_id_bytes]
#================================================================================
proof_text_check_to_med_id = (proof_text_check) ->
{med_id} = make_ids(new Buffer proof_text_check, 'base64')
med_id
#================================================================================
exports.cieq = cieq = (a,b) -> (a? and b? and (a.toLowerCase() is b.toLowerCase()))
#==========================================================================
class Verifier
constructor : ({@armored, @id, @short_id, @skip_ids, @make_ids, @strict}, @sig_eng, @base) ->
#---------------
km : () -> @sig_eng.get_km()
#---------------
get_etime : () ->
if @json.ctime? and @json.expire_in then (@json.ctime + @json.expire_in)
else null
#---------------
verify : (cb) ->
esc = make_esc cb, "Verifier::verfiy"
await @_parse_and_process esc defer()
await @_check_json esc defer json_obj, json_str
await @_check_expired esc defer()
cb null, json_obj, json_str
#---------------
_check_ids : (body, cb) ->
{short_id, id} = make_ids body
err = if not (@id? and streq_secure id, @id)
new Error "Long IDs aren't equal; wanted #{id} but got #{@id}"
else if not (@short_id? and streq_secure short_id, @short_id)
new Error "Short IDs aren't equal: wanted #{short_id} but got #{@short_id}"
else null
cb err
#---------------
_check_expired : (cb) ->
err = null
now = unix_time()
if not @json.ctime? then err = new Error "No `ctime` in signature"
else if not @json.expire_in? then err = new Error "No `expire_in` in signature"
else if not @json.expire_in then @etime = null
else if (expired = (now - @json.ctime - @json.expire_in)) > 0
err = new Error "Expired #{expired}s ago"
else
@etime = @json.ctime + @json.expire_in
cb err
#---------------
_parse_and_process : (cb) ->
err = null
await @sig_eng.unbox @armored, defer err, @payload, body
if not err? and not @skip_ids
await @_check_ids body, defer err
if not err? and @make_ids
{@short_id, @id} = make_ids body
cb err
#---------------
_check_json : (cb) ->
json_str_buf = @payload
# Before we run any checks on the input json, let's trim any leading
# or trailing whitespace.
json_str_utf8 = json_str_buf.toString('utf8')
json_str_utf8_trimmed = trim json_str_utf8
err = null
if not /^[\x20-\x7e]+$/.test json_str_utf8_trimmed
err = new Error "All JSON proof characters must be in the visible ASCII set (properly escaped UTF8 is permissible)"
else
[e, @json] = katch (() -> JSON.parse json_str_buf)
err = new Error "Couldn't parse JSON signed message: #{e.message}" if e?
if not err?
if @strict and ((ours = trim(json_stringify_sorted(@json))) isnt json_str_utf8_trimmed)
err = new Error "non-canonlical JSON found in strict mode (#{ours} v #{json_str_utf8_trimmed})"
else
await @base._v_check {@json}, defer err
cb err, @json, json_str_utf8
#==========================================================================
class Base
#------
constructor : ({@sig_eng, @seqno, @user, @host, @prev, @client, @merkle_root, @revoke, @seq_type, @eldest_kid, @expire_in, @ctime}) ->
#------
proof_type_str : () ->
if (t = @proof_type())? then proof_type_to_string[t]
else null
#------
_v_check_key : (key) ->
checks = 0
if key?.kid?
checks++
err = @_v_check_kid key.kid
if not err? and key?.fingerprint?
checks++
err = @_v_check_fingerprint key
if not err? and checks is 0
err = new Error "need either a 'body.key.kid' or a 'body.key.fingerprint'"
err
#------
_v_check_kid : (kid) ->
if not bufeq_secure (a = @km().get_ekid()), (new Buffer kid, "hex")
err = new Error "Verification key doesn't match packet (via kid): #{a.toString('hex')} != #{kid}"
else
null
#------
_v_check_fingerprint : (key) ->
if not (key_id = key?.key_id)?
new Error "Needed a body.key.key_id but none given"
else if not bufeq_secure (a = @km().get_pgp_key_id()), (new Buffer key_id, "hex")
new Error "Verification key doesn't match packet (via key ID): #{a.toString('hex')} != #{key_id}"
else if not (fp = key?.fingerprint)?
new Error "Needed a body.key.fingerprint but none given"
else if not bufeq_secure @km().get_pgp_fingerprint(), (new Buffer fp, "hex")
new Error "Verifiation key doesn't match packet (via fingerprint)"
else
null
#------
# true if PGP details (full_hash and fingerprint) should be inserted at
# @_v_pgp_details_dest()
_v_include_pgp_details : -> false
# true if this link type is only valid if it includes PGP details
_v_require_pgp_details : -> false
# Given the JSON body, the object where PGP key details should end up
_v_pgp_details_dest : (body) -> body.key
# If @_v_include_pgp_details() is true, a KeyManager containing a PGP key
_v_pgp_km : () -> null
# Generates (and caches) a hash for PGP keys, returns null for other kinds of keys
full_pgp_hash : (opts, cb) ->
if @_full_pgp_hash is undefined
esc = make_esc cb
await @_v_pgp_km()?.pgp_full_hash {}, esc defer @_full_pgp_hash
cb null, @_full_pgp_hash
# Adds the PGP hash and fingerprint to `body`. Noop for non-PGP keys (unless
# @_v_require_pgp_details returns true, then returns an error.)
_add_pgp_details : ({body}, cb) ->
return cb(null) unless @_v_include_pgp_details()
dest = @_v_pgp_details_dest(body)
await @full_pgp_hash {}, defer err, full_hash
if err then # noop
else if full_hash?
dest.full_hash = full_hash
dest.fingerprint = @_v_pgp_km().get_pgp_fingerprint().toString('hex') unless dest.fingerprint?
else if @_v_require_pgp_details()
err = new Error "#{@proof_type_str()} proofs require a PGP key"
cb err
_check_pgp_details: ({json}, cb) ->
err = null
details = @_v_pgp_details_dest(json.body)
if not (hash_in = details?.full_hash)? or not (fp_in = details?.fingerprint)? or not (kid_in = details?.kid)?
if @_v_require_pgp_details()
err = new Error "#{@proof_type_str()} proofs require a PGP key's KID, fingerprint, and full_hash but one or more were missing."
else
await @full_pgp_hash {}, defer err, hash_real
if err? then # noop
else if not hash_real?
err = new Error "A PGP key hash (#{hash_in}) was in the sig body but no key was provided"
else if hash_in isnt hash_real
err = new Error "New PGP key's hash (#{hash_real}) doesn't match hash in signature (#{hash_in})"
else if fp_in isnt (fp_real = @_v_pgp_km().get_pgp_fingerprint().toString('hex'))
err = new Error "New PGP key's fingerprint (#{fp_real}) doesn't match fingerprint in signature (#{fp_in})"
else if kid_in isnt (kid_real = @_v_pgp_km().get_ekid().toString('hex'))
err = new Error "New PGP key's KID (#{kid_real}) doesn't match KID in signature (#{kid_in})"
cb err
#------
_v_check : ({json}, cb) ->
# The default seq_type is PUBLIC
seq_type = (v) -> if v? then v else constants.seq_types.PUBLIC
err = if not cieq (a = json?.body?.key?.username), (b = @user.local.username)
new Error "Wrong local user: got '#{a}' but wanted '#{b}'"
else if (a = json?.body?.key?.uid) isnt (b = @user.local.uid)
new Error "Wrong local uid: got '#{a}' but wanted '#{b}'"
else if not cieq (a = json?.body?.key?.host), (b = @host)
new Error "Wrong host: got '#{a}' but wanted '#{b}'"
else if (a = @_type())? and ((b = json?.body?.type) isnt a)
# Don't check if it's a "generic_binding", which doesn't much
# care what the signature type is. Imagine the case of just trying to
# get the user's keybinding. Then any signature will do.
new Error "Wrong signature type; got '#{a}' but wanted '#{b}'"
else if (a = @prev) and (a isnt (b = json?.prev))
new Error "Wrong previous hash; wanted '#{a}' but got '#{b}'"
else if (a = @seqno) and (a isnt (b = json?.seqno))
new Error "Wrong seqno; wanted '#{a}' but got '#{b}"
else if @seqno and (a = seq_type(json?.seq_type)) isnt (b = seq_type(@seq_type))
new Error "Wrong seq_type: wanted '#{a}' but got '#{b}'"
else if not (key = json?.body?.key)?
new Error "no 'body.key' block in signature"
else if (section_error = @_check_sections(json))?
section_error
else
@_v_check_key key
if not err?
await @_check_pgp_details {json}, defer err
cb err
#------
_required_sections : () -> ["key", "type", "version"]
#------
_optional_sections : () -> ["client", "merkle_root"]
_is_wildcard_link : () -> false
#------
# Return a JavaScript Error on failure, or null if no failure.
_check_sections : (json) ->
for section in @_required_sections()
unless json?.body?[section]
return new Error "Missing '#{section}' section #{if json.seqno? then "in seqno " + json.seqno else ""}, required for #{json.body.type} signatures"
# Sometimes we don't really need to check, we just need a "key" section
unless @_is_wildcard_link()
for section, _ of json?.body
unless (section in @_required_sections()) or (section in @_optional_sections())
return new Error "'#{section}' section #{if json.seqno? then "in seqno " + json.seqno else ""} is not allowed for #{json.body.type} signatures"
null
#------
is_remote_proof : () -> false
#------
has_revoke : () ->
if not @revoke? then false
else if @revoke.sig_id? then true
else if (@revoke.sig_ids?.length > 0) then true
else if @revoke.kid? then true
else if (@revoke.kids?.length > 0) then true
else false
#------
_v_customize_json : (ret) ->
#------
generate_json : ({expire_in} = {}, cb) ->
err = null
# Cache the unix_time() we generate in case we need to call @generate_json()
# twice. This happens for reverse signatures!
ctime = if @ctime? then @ctime else (@ctime = unix_time())
pick = (v...) ->
for e in v when e?
return e
return null
ret = {
seqno : @seqno
prev : @prev
ctime : ctime
tag : constants.tags.sig
expire_in : pick(expire_in, @expire_in, constants.expire_in)
body :
version : constants.versions.sig
type : @_type()
key :
host : @host
username : @user.local.username
uid : @user.local.uid
}
# Can't access ekids from GnuPG. We'd have to parse the keys (possible).
if (ekid = @km().get_ekid())?
ret.body.key.kid = ekid.toString('hex')
if (fp = @km().get_pgp_fingerprint())?
ret.body.key.fingerprint = fp.toString('hex')
ret.body.key.key_id = <KEY>().<KEY>_<KEY>_key_<KEY>().<KEY>('<KEY>')
if @eldest_kid?
ret.body.key.eldest_kid = @eldest_kid
# Can be:
#
# NONE : 0
# PUBLIC : 1 # this is the default!
# PRIVATE : 2
# SEMIPRIVATE : 3
#
ret.seq_type = @seq_type if @seq_type?
ret.body.client = @client if @client?
ret.body.merkle_root = @merkle_root if @merkle_root?
ret.body.revoke = @revoke if @has_revoke()
@_v_customize_json ret
await @_add_pgp_details {body: ret.body}, defer err
cb err, json_stringify_sorted ret
#------
_v_generate : (opts, cb) -> cb null
#------
generate : (cb) ->
esc = make_esc cb, "generate"
out = null
await @_v_generate {}, esc defer()
await @generate_json {}, esc defer json
await @sig_eng.box json, esc defer {pgp, raw, armored}
{short_id, id} = make_ids raw
out = { pgp, json, id, short_id, raw, armored }
cb null, out
#------
# @param {Object} obj with options as specified:
# @option obj {string} pgp The PGP signature that's being uploaded
# @option obj {string} id The keybase-appropriate ID that's the PGP signature's hash
# @option obj {string} short_id The shortened sig ID that's for the tweet (or similar)
# @option obj {bool} skip_ids Don't bother checking IDs
# @option obj {bool} make_ids Make Ids when verifying
# @option obj {bool} strict Turn on all strict-mode checks
verify : (obj, cb) ->
verifier = new Verifier obj, @sig_eng, @
await verifier.verify defer err, json_obj, json_str
id = short_id = null
if obj.make_ids
id = obj.id = verifier.id
short_id = obj.short_id = verifier.short_id
out = if err? then {}
else {json_obj, json_str, id, short_id, etime : verifier.get_etime(), @reverse_sig_kid }
cb err, out
#-------
km : () -> @sig_eng.get_km()
#-------
check_inputs : () -> null
#-------
# Check this proof against the existing proofs
check_existing : () -> null
#-------
# Some proofs are shortened, like Twitter, due to the space-constraints on the medium.
is_short : () -> false
#-------
# Check the server's work when we ask for it to generate a proof text.
# Make sure our sig shows up in there but no one else's. This will
# vary between long and short signatures.
sanity_check_proof_text : ({ args, proof_text}, cb) ->
if @is_short()
check_for = args.sig_id_short
len_floor = constants.short_id_bytes
slack = 3
else
[ err, msg ] = kbpgp.ukm.decode_sig { armored: args.sig }
if not err? and (msg.type isnt kbpgp.const.openpgp.message_types.generic)
err = new Error "wrong message type; expected a generic message; got #{msg.type}"
if not err?
check_for = msg.body.toString('base64')
len_floor = constants.shortest_pgp_signature
slack = 30 # 30 bytes of prefix/suffix data available
unless err?
b64s = base64_extract proof_text
for b in b64s when (b.length >= len_floor)
if b.indexOf(check_for) < 0 or (s = (b.length - check_for.length)) > slack
err = new Error "Found a bad signature in proof text: #{b[0...60]} != #{check_for[0...60]} (slack=#{s})"
break
cb err
#==========================================================================
class GenericBinding extends Base
_type : () -> null
resource_id : () -> ""
_service_obj_check : () -> true
_is_wildcard_link : () -> true
#==========================================================================
exports.Base = Base
exports.GenericBinding = GenericBinding
exports.sig_id_to_short_id = sig_id_to_short_id
exports.sig_id_to_med_id = sig_id_to_med_id
exports.make_ids = make_ids
exports.add_ids = add_ids
exports.proof_text_check_to_med_id = proof_text_check_to_med_id
#==========================================================================
| true | {proof_type_to_string,constants} = require './constants'
pgp_utils = require('pgp-utils')
{trim,katch,akatch,bufeq_secure,json_stringify_sorted,unix_time,base64u,streq_secure} = pgp_utils.util
triplesec = require('triplesec')
{WordArray} = triplesec
{SHA256} = triplesec.hash
kbpgp = require 'kbpgp'
{make_esc} = require 'iced-error'
util = require 'util'
{base64_extract} = require './b64extract'
#==========================================================================
exports.hash_sig = hash_sig = (sig_body) ->
(new SHA256).bufhash(sig_body)
#------
add_ids = (sig_body, out) ->
hash = hash_sig sig_body
id = hash.toString('hex')
short_id = sig_id_to_short_id hash
out.id = id
out.med_id = sig_id_to_med_id hash
out.short_id = short_id
#------
make_ids = (sig_body) ->
out = {}
add_ids sig_body, out
return out
#------
sig_id_to_med_id = (sig_id) -> base64u.encode sig_id
#------
sig_id_to_short_id = (sig_id) ->
base64u.encode sig_id[0...constants.short_id_bytes]
#================================================================================
proof_text_check_to_med_id = (proof_text_check) ->
{med_id} = make_ids(new Buffer proof_text_check, 'base64')
med_id
#================================================================================
exports.cieq = cieq = (a,b) -> (a? and b? and (a.toLowerCase() is b.toLowerCase()))
#==========================================================================
class Verifier
constructor : ({@armored, @id, @short_id, @skip_ids, @make_ids, @strict}, @sig_eng, @base) ->
#---------------
km : () -> @sig_eng.get_km()
#---------------
get_etime : () ->
if @json.ctime? and @json.expire_in then (@json.ctime + @json.expire_in)
else null
#---------------
verify : (cb) ->
esc = make_esc cb, "Verifier::verfiy"
await @_parse_and_process esc defer()
await @_check_json esc defer json_obj, json_str
await @_check_expired esc defer()
cb null, json_obj, json_str
#---------------
_check_ids : (body, cb) ->
{short_id, id} = make_ids body
err = if not (@id? and streq_secure id, @id)
new Error "Long IDs aren't equal; wanted #{id} but got #{@id}"
else if not (@short_id? and streq_secure short_id, @short_id)
new Error "Short IDs aren't equal: wanted #{short_id} but got #{@short_id}"
else null
cb err
#---------------
_check_expired : (cb) ->
err = null
now = unix_time()
if not @json.ctime? then err = new Error "No `ctime` in signature"
else if not @json.expire_in? then err = new Error "No `expire_in` in signature"
else if not @json.expire_in then @etime = null
else if (expired = (now - @json.ctime - @json.expire_in)) > 0
err = new Error "Expired #{expired}s ago"
else
@etime = @json.ctime + @json.expire_in
cb err
#---------------
_parse_and_process : (cb) ->
err = null
await @sig_eng.unbox @armored, defer err, @payload, body
if not err? and not @skip_ids
await @_check_ids body, defer err
if not err? and @make_ids
{@short_id, @id} = make_ids body
cb err
#---------------
_check_json : (cb) ->
json_str_buf = @payload
# Before we run any checks on the input json, let's trim any leading
# or trailing whitespace.
json_str_utf8 = json_str_buf.toString('utf8')
json_str_utf8_trimmed = trim json_str_utf8
err = null
if not /^[\x20-\x7e]+$/.test json_str_utf8_trimmed
err = new Error "All JSON proof characters must be in the visible ASCII set (properly escaped UTF8 is permissible)"
else
[e, @json] = katch (() -> JSON.parse json_str_buf)
err = new Error "Couldn't parse JSON signed message: #{e.message}" if e?
if not err?
if @strict and ((ours = trim(json_stringify_sorted(@json))) isnt json_str_utf8_trimmed)
err = new Error "non-canonlical JSON found in strict mode (#{ours} v #{json_str_utf8_trimmed})"
else
await @base._v_check {@json}, defer err
cb err, @json, json_str_utf8
#==========================================================================
class Base
#------
constructor : ({@sig_eng, @seqno, @user, @host, @prev, @client, @merkle_root, @revoke, @seq_type, @eldest_kid, @expire_in, @ctime}) ->
#------
proof_type_str : () ->
if (t = @proof_type())? then proof_type_to_string[t]
else null
#------
_v_check_key : (key) ->
checks = 0
if key?.kid?
checks++
err = @_v_check_kid key.kid
if not err? and key?.fingerprint?
checks++
err = @_v_check_fingerprint key
if not err? and checks is 0
err = new Error "need either a 'body.key.kid' or a 'body.key.fingerprint'"
err
#------
_v_check_kid : (kid) ->
if not bufeq_secure (a = @km().get_ekid()), (new Buffer kid, "hex")
err = new Error "Verification key doesn't match packet (via kid): #{a.toString('hex')} != #{kid}"
else
null
#------
_v_check_fingerprint : (key) ->
if not (key_id = key?.key_id)?
new Error "Needed a body.key.key_id but none given"
else if not bufeq_secure (a = @km().get_pgp_key_id()), (new Buffer key_id, "hex")
new Error "Verification key doesn't match packet (via key ID): #{a.toString('hex')} != #{key_id}"
else if not (fp = key?.fingerprint)?
new Error "Needed a body.key.fingerprint but none given"
else if not bufeq_secure @km().get_pgp_fingerprint(), (new Buffer fp, "hex")
new Error "Verifiation key doesn't match packet (via fingerprint)"
else
null
#------
# true if PGP details (full_hash and fingerprint) should be inserted at
# @_v_pgp_details_dest()
_v_include_pgp_details : -> false
# true if this link type is only valid if it includes PGP details
_v_require_pgp_details : -> false
# Given the JSON body, the object where PGP key details should end up
_v_pgp_details_dest : (body) -> body.key
# If @_v_include_pgp_details() is true, a KeyManager containing a PGP key
_v_pgp_km : () -> null
# Generates (and caches) a hash for PGP keys, returns null for other kinds of keys
full_pgp_hash : (opts, cb) ->
if @_full_pgp_hash is undefined
esc = make_esc cb
await @_v_pgp_km()?.pgp_full_hash {}, esc defer @_full_pgp_hash
cb null, @_full_pgp_hash
# Adds the PGP hash and fingerprint to `body`. Noop for non-PGP keys (unless
# @_v_require_pgp_details returns true, then returns an error.)
_add_pgp_details : ({body}, cb) ->
return cb(null) unless @_v_include_pgp_details()
dest = @_v_pgp_details_dest(body)
await @full_pgp_hash {}, defer err, full_hash
if err then # noop
else if full_hash?
dest.full_hash = full_hash
dest.fingerprint = @_v_pgp_km().get_pgp_fingerprint().toString('hex') unless dest.fingerprint?
else if @_v_require_pgp_details()
err = new Error "#{@proof_type_str()} proofs require a PGP key"
cb err
_check_pgp_details: ({json}, cb) ->
err = null
details = @_v_pgp_details_dest(json.body)
if not (hash_in = details?.full_hash)? or not (fp_in = details?.fingerprint)? or not (kid_in = details?.kid)?
if @_v_require_pgp_details()
err = new Error "#{@proof_type_str()} proofs require a PGP key's KID, fingerprint, and full_hash but one or more were missing."
else
await @full_pgp_hash {}, defer err, hash_real
if err? then # noop
else if not hash_real?
err = new Error "A PGP key hash (#{hash_in}) was in the sig body but no key was provided"
else if hash_in isnt hash_real
err = new Error "New PGP key's hash (#{hash_real}) doesn't match hash in signature (#{hash_in})"
else if fp_in isnt (fp_real = @_v_pgp_km().get_pgp_fingerprint().toString('hex'))
err = new Error "New PGP key's fingerprint (#{fp_real}) doesn't match fingerprint in signature (#{fp_in})"
else if kid_in isnt (kid_real = @_v_pgp_km().get_ekid().toString('hex'))
err = new Error "New PGP key's KID (#{kid_real}) doesn't match KID in signature (#{kid_in})"
cb err
#------
_v_check : ({json}, cb) ->
# The default seq_type is PUBLIC
seq_type = (v) -> if v? then v else constants.seq_types.PUBLIC
err = if not cieq (a = json?.body?.key?.username), (b = @user.local.username)
new Error "Wrong local user: got '#{a}' but wanted '#{b}'"
else if (a = json?.body?.key?.uid) isnt (b = @user.local.uid)
new Error "Wrong local uid: got '#{a}' but wanted '#{b}'"
else if not cieq (a = json?.body?.key?.host), (b = @host)
new Error "Wrong host: got '#{a}' but wanted '#{b}'"
else if (a = @_type())? and ((b = json?.body?.type) isnt a)
# Don't check if it's a "generic_binding", which doesn't much
# care what the signature type is. Imagine the case of just trying to
# get the user's keybinding. Then any signature will do.
new Error "Wrong signature type; got '#{a}' but wanted '#{b}'"
else if (a = @prev) and (a isnt (b = json?.prev))
new Error "Wrong previous hash; wanted '#{a}' but got '#{b}'"
else if (a = @seqno) and (a isnt (b = json?.seqno))
new Error "Wrong seqno; wanted '#{a}' but got '#{b}"
else if @seqno and (a = seq_type(json?.seq_type)) isnt (b = seq_type(@seq_type))
new Error "Wrong seq_type: wanted '#{a}' but got '#{b}'"
else if not (key = json?.body?.key)?
new Error "no 'body.key' block in signature"
else if (section_error = @_check_sections(json))?
section_error
else
@_v_check_key key
if not err?
await @_check_pgp_details {json}, defer err
cb err
#------
_required_sections : () -> ["key", "type", "version"]
#------
_optional_sections : () -> ["client", "merkle_root"]
_is_wildcard_link : () -> false
#------
# Return a JavaScript Error on failure, or null if no failure.
_check_sections : (json) ->
for section in @_required_sections()
unless json?.body?[section]
return new Error "Missing '#{section}' section #{if json.seqno? then "in seqno " + json.seqno else ""}, required for #{json.body.type} signatures"
# Sometimes we don't really need to check, we just need a "key" section
unless @_is_wildcard_link()
for section, _ of json?.body
unless (section in @_required_sections()) or (section in @_optional_sections())
return new Error "'#{section}' section #{if json.seqno? then "in seqno " + json.seqno else ""} is not allowed for #{json.body.type} signatures"
null
#------
is_remote_proof : () -> false
#------
has_revoke : () ->
if not @revoke? then false
else if @revoke.sig_id? then true
else if (@revoke.sig_ids?.length > 0) then true
else if @revoke.kid? then true
else if (@revoke.kids?.length > 0) then true
else false
#------
_v_customize_json : (ret) ->
#------
generate_json : ({expire_in} = {}, cb) ->
err = null
# Cache the unix_time() we generate in case we need to call @generate_json()
# twice. This happens for reverse signatures!
ctime = if @ctime? then @ctime else (@ctime = unix_time())
pick = (v...) ->
for e in v when e?
return e
return null
ret = {
seqno : @seqno
prev : @prev
ctime : ctime
tag : constants.tags.sig
expire_in : pick(expire_in, @expire_in, constants.expire_in)
body :
version : constants.versions.sig
type : @_type()
key :
host : @host
username : @user.local.username
uid : @user.local.uid
}
# Can't access ekids from GnuPG. We'd have to parse the keys (possible).
if (ekid = @km().get_ekid())?
ret.body.key.kid = ekid.toString('hex')
if (fp = @km().get_pgp_fingerprint())?
ret.body.key.fingerprint = fp.toString('hex')
ret.body.key.key_id = PI:KEY:<KEY>END_PI().PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI_key_PI:KEY:<KEY>END_PI().PI:KEY:<KEY>END_PI('PI:KEY:<KEY>END_PI')
if @eldest_kid?
ret.body.key.eldest_kid = @eldest_kid
# Can be:
#
# NONE : 0
# PUBLIC : 1 # this is the default!
# PRIVATE : 2
# SEMIPRIVATE : 3
#
ret.seq_type = @seq_type if @seq_type?
ret.body.client = @client if @client?
ret.body.merkle_root = @merkle_root if @merkle_root?
ret.body.revoke = @revoke if @has_revoke()
@_v_customize_json ret
await @_add_pgp_details {body: ret.body}, defer err
cb err, json_stringify_sorted ret
#------
_v_generate : (opts, cb) -> cb null
#------
generate : (cb) ->
esc = make_esc cb, "generate"
out = null
await @_v_generate {}, esc defer()
await @generate_json {}, esc defer json
await @sig_eng.box json, esc defer {pgp, raw, armored}
{short_id, id} = make_ids raw
out = { pgp, json, id, short_id, raw, armored }
cb null, out
#------
# @param {Object} obj with options as specified:
# @option obj {string} pgp The PGP signature that's being uploaded
# @option obj {string} id The keybase-appropriate ID that's the PGP signature's hash
# @option obj {string} short_id The shortened sig ID that's for the tweet (or similar)
# @option obj {bool} skip_ids Don't bother checking IDs
# @option obj {bool} make_ids Make Ids when verifying
# @option obj {bool} strict Turn on all strict-mode checks
verify : (obj, cb) ->
verifier = new Verifier obj, @sig_eng, @
await verifier.verify defer err, json_obj, json_str
id = short_id = null
if obj.make_ids
id = obj.id = verifier.id
short_id = obj.short_id = verifier.short_id
out = if err? then {}
else {json_obj, json_str, id, short_id, etime : verifier.get_etime(), @reverse_sig_kid }
cb err, out
#-------
km : () -> @sig_eng.get_km()
#-------
check_inputs : () -> null
#-------
# Check this proof against the existing proofs
check_existing : () -> null
#-------
# Some proofs are shortened, like Twitter, due to the space-constraints on the medium.
is_short : () -> false
#-------
# Check the server's work when we ask for it to generate a proof text.
# Make sure our sig shows up in there but no one else's. This will
# vary between long and short signatures.
sanity_check_proof_text : ({ args, proof_text}, cb) ->
if @is_short()
check_for = args.sig_id_short
len_floor = constants.short_id_bytes
slack = 3
else
[ err, msg ] = kbpgp.ukm.decode_sig { armored: args.sig }
if not err? and (msg.type isnt kbpgp.const.openpgp.message_types.generic)
err = new Error "wrong message type; expected a generic message; got #{msg.type}"
if not err?
check_for = msg.body.toString('base64')
len_floor = constants.shortest_pgp_signature
slack = 30 # 30 bytes of prefix/suffix data available
unless err?
b64s = base64_extract proof_text
for b in b64s when (b.length >= len_floor)
if b.indexOf(check_for) < 0 or (s = (b.length - check_for.length)) > slack
err = new Error "Found a bad signature in proof text: #{b[0...60]} != #{check_for[0...60]} (slack=#{s})"
break
cb err
#==========================================================================
class GenericBinding extends Base
_type : () -> null
resource_id : () -> ""
_service_obj_check : () -> true
_is_wildcard_link : () -> true
#==========================================================================
exports.Base = Base
exports.GenericBinding = GenericBinding
exports.sig_id_to_short_id = sig_id_to_short_id
exports.sig_id_to_med_id = sig_id_to_med_id
exports.make_ids = make_ids
exports.add_ids = add_ids
exports.proof_text_check_to_med_id = proof_text_check_to_med_id
#==========================================================================
|
[
{
"context": "MetisMenu`\n NAME = 'metisMenu'\n DATA_KEY = 'metisMenu'\n EVENT_KEY = '.' + DATA_KEY\n DATA_API_KEY ",
"end": 1582,
"score": 0.9968569874763489,
"start": 1573,
"tag": "KEY",
"value": "metisMenu"
},
{
"context": " EVENT_KEY = '.' + DATA_KEY\n DATA_API_KEY = '.data-api'\n JQUERY_NO_CONFLICT = $.fn[NAME]\n TRANSITI",
"end": 1644,
"score": 0.9683321118354797,
"start": 1636,
"tag": "KEY",
"value": "data-api"
},
{
"context": " return\n\n }\n {\n key: '_show'\n value: (element) ->\n if @_t",
"end": 5909,
"score": 0.964776873588562,
"start": 5903,
"tag": "KEY",
"value": "'_show"
}
] | app/assets/javascripts/metis-menu.coffee | atefth/advocacy | 0 | ((global, factory) ->
if typeof define == 'function' and define.amd
define [ 'jquery' ], factory
else if typeof exports != 'undefined'
factory require('jquery')
else
mod = exports: {}
factory global.jquery
global.metisMenu = mod.exports
return
) this, (_jquery) ->
_interopRequireDefault = (obj) ->
if obj and obj.__esModule then obj else default: obj
_classCallCheck = (instance, Constructor) ->
if !(instance instanceof Constructor)
throw new TypeError('Cannot call a class as a function')
return
'use strict'
_jquery2 = _interopRequireDefault(_jquery)
_typeof = if typeof Symbol == 'function' and typeof Symbol.iterator == 'symbol' then ((obj) ->
typeof obj
) else ((obj) ->
if obj and typeof Symbol == 'function' and obj.constructor == Symbol and obj != Symbol.prototype then 'symbol' else typeof obj
)
_createClass = do ->
defineProperties = (target, props) ->
i = 0
while i < props.length
descriptor = props[i]
descriptor.enumerable = descriptor.enumerable or false
descriptor.configurable = true
if 'value' of descriptor
descriptor.writable = true
Object.defineProperty target, descriptor.key, descriptor
i++
return
(Constructor, protoProps, staticProps) ->
if protoProps
defineProperties Constructor.prototype, protoProps
if staticProps
defineProperties Constructor, staticProps
Constructor
MetisMenu = (($) ->
`var MetisMenu`
NAME = 'metisMenu'
DATA_KEY = 'metisMenu'
EVENT_KEY = '.' + DATA_KEY
DATA_API_KEY = '.data-api'
JQUERY_NO_CONFLICT = $.fn[NAME]
TRANSITION_DURATION = 350
Default =
toggle: true
doubleTapToGo: false
preventDefault: true
activeClass: 'active'
collapseClass: 'collapse'
collapseInClass: 'in'
collapsingClass: 'collapsing'
Event =
SHOW: 'show' + EVENT_KEY
SHOWN: 'shown' + EVENT_KEY
HIDE: 'hide' + EVENT_KEY
HIDDEN: 'hidden' + EVENT_KEY
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
transition = false
TransitionEndEvent =
WebkitTransition: 'webkitTransitionEnd'
MozTransition: 'transitionend'
OTransition: 'oTransitionEnd otransitionend'
transition: 'transitionend'
Util =
TRANSITION_END: 'mmTransitionEnd'
triggerTransitionEnd: (element) ->
$(element).trigger transition.end
return
supportsTransitionEnd: ->
Boolean transition
getSpecialTransitionEndEvent = ->
{
bindType: transition.end
delegateType: transition.end
handle: (event) ->
if $(event.target).is(this)
return event.handleObj.handler.apply(this, arguments)
return
}
transitionEndTest = ->
if window.QUnit
return false
el = document.createElement('mm')
for name of TransitionEndEvent
if el.style[name] != undefined
return { end: TransitionEndEvent[name] }
false
transitionEndEmulator = (duration) ->
_this2 = this
called = false
$(this).one Util.TRANSITION_END, ->
called = true
return
setTimeout (->
if !called
Util.triggerTransitionEnd _this2
return
), duration
return
setTransitionEndSupport = ->
transition = transitionEndTest()
if Util.supportsTransitionEnd()
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent()
return
setTransitionEndSupport()
MetisMenu = do ->
`var MetisMenu`
MetisMenu = (element, config) ->
_classCallCheck this, MetisMenu
@_element = element
@_config = @_getConfig(config)
@_transitioning = null
@init()
return
_createClass MetisMenu, [
{
key: 'init'
value: ->
self = this
$(@_element).find('li.' + @_config.activeClass).has('ul').children('ul').attr('aria-expanded', true).addClass @_config.collapseClass + ' ' + @_config.collapseInClass
$(@_element).find('li').not('.' + @_config.activeClass).has('ul').children('ul').attr('aria-expanded', false).addClass @_config.collapseClass
#add the 'doubleTapToGo' class to active items if needed
if @_config.doubleTapToGo
$(@_element).find('li.' + @_config.activeClass).has('ul').children('a').addClass 'doubleTapToGo'
$(@_element).find('li').has('ul').children('a').on Event.CLICK_DATA_API, (e) ->
_this = $(this)
_parent = _this.parent('li')
_siblings = _parent.siblings('li').children('a')
_list = _parent.children('ul')
if self._config.preventDefault
e.preventDefault()
if _this.attr('aria-disabled') == 'true'
return
if _parent.hasClass(self._config.activeClass) and !self._config.doubleTapToGo
_this.attr 'aria-expanded', false
self._hide _list
else
self._show _list
_this.attr 'aria-expanded', true
if self._config.toggle
_siblings.attr 'aria-expanded', false
if self._config.onTransitionStart
self._config.onTransitionStart e
#Do we need to enable the double tap
if self._config.doubleTapToGo
#if we hit a second time on the link and the href is valid, navigate to that url
if self._doubleTapToGo(_this) and _this.attr('href') != '#' and _this.attr('href') != ''
e.stopPropagation()
document.location = _this.attr('href')
return
return
return
}
{
key: '_show'
value: (element) ->
if @_transitioning or $(element).hasClass(@_config.collapsingClass)
return
_this = this
_el = $(element)
startEvent = $.Event(Event.SHOW)
_el.trigger startEvent
if startEvent.isDefaultPrevented()
return
_el.parent('li').addClass @_config.activeClass
if @_config.toggle
@_hide _el.parent('li').siblings().children('ul.' + @_config.collapseInClass).attr('aria-expanded', false)
_el.removeClass(@_config.collapseClass).addClass(@_config.collapsingClass).height 0
@setTransitioning true
complete = ->
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass + ' ' + _this._config.collapseInClass).height('').attr 'aria-expanded', true
_this.setTransitioning false
_el.trigger Event.SHOWN
return
if !Util.supportsTransitionEnd()
complete()
return
_el.height(_el[0].scrollHeight).one Util.TRANSITION_END, complete
transitionEndEmulator TRANSITION_DURATION
return
}
{
key: '_hide'
value: (element) ->
if @_transitioning or !$(element).hasClass(@_config.collapseInClass)
return
_this = this
_el = $(element)
startEvent = $.Event(Event.HIDE)
_el.trigger startEvent
if startEvent.isDefaultPrevented()
return
_el.parent('li').removeClass @_config.activeClass
_el.height(_el.height())[0].offsetHeight
_el.addClass(@_config.collapsingClass).removeClass(@_config.collapseClass).removeClass @_config.collapseInClass
@setTransitioning true
complete = ->
if _this._transitioning and _this._config.onTransitionEnd
_this._config.onTransitionEnd()
_this.setTransitioning false
_el.trigger Event.HIDDEN
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass).attr 'aria-expanded', false
return
if !Util.supportsTransitionEnd()
complete()
return
if _el.height() == 0 or _el.css('display') == 'none' then complete() else _el.height(0).one(Util.TRANSITION_END, complete)
transitionEndEmulator TRANSITION_DURATION
return
}
{
key: '_doubleTapToGo'
value: (element) ->
if element.hasClass('doubleTapToGo')
element.removeClass 'doubleTapToGo'
return true
if element.parent().children('ul').length
$(@_element).find('.doubleTapToGo').removeClass 'doubleTapToGo'
element.addClass 'doubleTapToGo'
return false
return
}
{
key: 'setTransitioning'
value: (isTransitioning) ->
@_transitioning = isTransitioning
return
}
{
key: 'dispose'
value: ->
$.removeData @_element, DATA_KEY
$(@_element).find('li').has('ul').children('a').off 'click'
@_transitioning = null
@_config = null
@_element = null
return
}
{
key: '_getConfig'
value: (config) ->
config = $.extend({}, Default, config)
config
}
], [ {
key: '_jQueryInterface'
value: (config) ->
@each ->
$this = $(this)
data = $this.data(DATA_KEY)
_config = $.extend({}, Default, $this.data(), (if typeof config == 'undefined' then 'undefined' else _typeof(config)) == 'object' and config)
if !data and /dispose/.test(config)
@dispose()
if !data
data = new MetisMenu(this, _config)
$this.data DATA_KEY, data
if typeof config == 'string'
if data[config] == undefined
throw new Error('No method named "' + config + '"')
data[config]()
return
} ]
MetisMenu
$.fn[NAME] = MetisMenu._jQueryInterface
$.fn[NAME].Constructor = MetisMenu
$.fn[NAME].noConflict = ->
$.fn[NAME] = JQUERY_NO_CONFLICT
MetisMenu._jQueryInterface
MetisMenu
)(jQuery)
return | 181898 | ((global, factory) ->
if typeof define == 'function' and define.amd
define [ 'jquery' ], factory
else if typeof exports != 'undefined'
factory require('jquery')
else
mod = exports: {}
factory global.jquery
global.metisMenu = mod.exports
return
) this, (_jquery) ->
_interopRequireDefault = (obj) ->
if obj and obj.__esModule then obj else default: obj
_classCallCheck = (instance, Constructor) ->
if !(instance instanceof Constructor)
throw new TypeError('Cannot call a class as a function')
return
'use strict'
_jquery2 = _interopRequireDefault(_jquery)
_typeof = if typeof Symbol == 'function' and typeof Symbol.iterator == 'symbol' then ((obj) ->
typeof obj
) else ((obj) ->
if obj and typeof Symbol == 'function' and obj.constructor == Symbol and obj != Symbol.prototype then 'symbol' else typeof obj
)
_createClass = do ->
defineProperties = (target, props) ->
i = 0
while i < props.length
descriptor = props[i]
descriptor.enumerable = descriptor.enumerable or false
descriptor.configurable = true
if 'value' of descriptor
descriptor.writable = true
Object.defineProperty target, descriptor.key, descriptor
i++
return
(Constructor, protoProps, staticProps) ->
if protoProps
defineProperties Constructor.prototype, protoProps
if staticProps
defineProperties Constructor, staticProps
Constructor
MetisMenu = (($) ->
`var MetisMenu`
NAME = 'metisMenu'
DATA_KEY = '<KEY>'
EVENT_KEY = '.' + DATA_KEY
DATA_API_KEY = '.<KEY>'
JQUERY_NO_CONFLICT = $.fn[NAME]
TRANSITION_DURATION = 350
Default =
toggle: true
doubleTapToGo: false
preventDefault: true
activeClass: 'active'
collapseClass: 'collapse'
collapseInClass: 'in'
collapsingClass: 'collapsing'
Event =
SHOW: 'show' + EVENT_KEY
SHOWN: 'shown' + EVENT_KEY
HIDE: 'hide' + EVENT_KEY
HIDDEN: 'hidden' + EVENT_KEY
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
transition = false
TransitionEndEvent =
WebkitTransition: 'webkitTransitionEnd'
MozTransition: 'transitionend'
OTransition: 'oTransitionEnd otransitionend'
transition: 'transitionend'
Util =
TRANSITION_END: 'mmTransitionEnd'
triggerTransitionEnd: (element) ->
$(element).trigger transition.end
return
supportsTransitionEnd: ->
Boolean transition
getSpecialTransitionEndEvent = ->
{
bindType: transition.end
delegateType: transition.end
handle: (event) ->
if $(event.target).is(this)
return event.handleObj.handler.apply(this, arguments)
return
}
transitionEndTest = ->
if window.QUnit
return false
el = document.createElement('mm')
for name of TransitionEndEvent
if el.style[name] != undefined
return { end: TransitionEndEvent[name] }
false
transitionEndEmulator = (duration) ->
_this2 = this
called = false
$(this).one Util.TRANSITION_END, ->
called = true
return
setTimeout (->
if !called
Util.triggerTransitionEnd _this2
return
), duration
return
setTransitionEndSupport = ->
transition = transitionEndTest()
if Util.supportsTransitionEnd()
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent()
return
setTransitionEndSupport()
MetisMenu = do ->
`var MetisMenu`
MetisMenu = (element, config) ->
_classCallCheck this, MetisMenu
@_element = element
@_config = @_getConfig(config)
@_transitioning = null
@init()
return
_createClass MetisMenu, [
{
key: 'init'
value: ->
self = this
$(@_element).find('li.' + @_config.activeClass).has('ul').children('ul').attr('aria-expanded', true).addClass @_config.collapseClass + ' ' + @_config.collapseInClass
$(@_element).find('li').not('.' + @_config.activeClass).has('ul').children('ul').attr('aria-expanded', false).addClass @_config.collapseClass
#add the 'doubleTapToGo' class to active items if needed
if @_config.doubleTapToGo
$(@_element).find('li.' + @_config.activeClass).has('ul').children('a').addClass 'doubleTapToGo'
$(@_element).find('li').has('ul').children('a').on Event.CLICK_DATA_API, (e) ->
_this = $(this)
_parent = _this.parent('li')
_siblings = _parent.siblings('li').children('a')
_list = _parent.children('ul')
if self._config.preventDefault
e.preventDefault()
if _this.attr('aria-disabled') == 'true'
return
if _parent.hasClass(self._config.activeClass) and !self._config.doubleTapToGo
_this.attr 'aria-expanded', false
self._hide _list
else
self._show _list
_this.attr 'aria-expanded', true
if self._config.toggle
_siblings.attr 'aria-expanded', false
if self._config.onTransitionStart
self._config.onTransitionStart e
#Do we need to enable the double tap
if self._config.doubleTapToGo
#if we hit a second time on the link and the href is valid, navigate to that url
if self._doubleTapToGo(_this) and _this.attr('href') != '#' and _this.attr('href') != ''
e.stopPropagation()
document.location = _this.attr('href')
return
return
return
}
{
key: <KEY>'
value: (element) ->
if @_transitioning or $(element).hasClass(@_config.collapsingClass)
return
_this = this
_el = $(element)
startEvent = $.Event(Event.SHOW)
_el.trigger startEvent
if startEvent.isDefaultPrevented()
return
_el.parent('li').addClass @_config.activeClass
if @_config.toggle
@_hide _el.parent('li').siblings().children('ul.' + @_config.collapseInClass).attr('aria-expanded', false)
_el.removeClass(@_config.collapseClass).addClass(@_config.collapsingClass).height 0
@setTransitioning true
complete = ->
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass + ' ' + _this._config.collapseInClass).height('').attr 'aria-expanded', true
_this.setTransitioning false
_el.trigger Event.SHOWN
return
if !Util.supportsTransitionEnd()
complete()
return
_el.height(_el[0].scrollHeight).one Util.TRANSITION_END, complete
transitionEndEmulator TRANSITION_DURATION
return
}
{
key: '_hide'
value: (element) ->
if @_transitioning or !$(element).hasClass(@_config.collapseInClass)
return
_this = this
_el = $(element)
startEvent = $.Event(Event.HIDE)
_el.trigger startEvent
if startEvent.isDefaultPrevented()
return
_el.parent('li').removeClass @_config.activeClass
_el.height(_el.height())[0].offsetHeight
_el.addClass(@_config.collapsingClass).removeClass(@_config.collapseClass).removeClass @_config.collapseInClass
@setTransitioning true
complete = ->
if _this._transitioning and _this._config.onTransitionEnd
_this._config.onTransitionEnd()
_this.setTransitioning false
_el.trigger Event.HIDDEN
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass).attr 'aria-expanded', false
return
if !Util.supportsTransitionEnd()
complete()
return
if _el.height() == 0 or _el.css('display') == 'none' then complete() else _el.height(0).one(Util.TRANSITION_END, complete)
transitionEndEmulator TRANSITION_DURATION
return
}
{
key: '_doubleTapToGo'
value: (element) ->
if element.hasClass('doubleTapToGo')
element.removeClass 'doubleTapToGo'
return true
if element.parent().children('ul').length
$(@_element).find('.doubleTapToGo').removeClass 'doubleTapToGo'
element.addClass 'doubleTapToGo'
return false
return
}
{
key: 'setTransitioning'
value: (isTransitioning) ->
@_transitioning = isTransitioning
return
}
{
key: 'dispose'
value: ->
$.removeData @_element, DATA_KEY
$(@_element).find('li').has('ul').children('a').off 'click'
@_transitioning = null
@_config = null
@_element = null
return
}
{
key: '_getConfig'
value: (config) ->
config = $.extend({}, Default, config)
config
}
], [ {
key: '_jQueryInterface'
value: (config) ->
@each ->
$this = $(this)
data = $this.data(DATA_KEY)
_config = $.extend({}, Default, $this.data(), (if typeof config == 'undefined' then 'undefined' else _typeof(config)) == 'object' and config)
if !data and /dispose/.test(config)
@dispose()
if !data
data = new MetisMenu(this, _config)
$this.data DATA_KEY, data
if typeof config == 'string'
if data[config] == undefined
throw new Error('No method named "' + config + '"')
data[config]()
return
} ]
MetisMenu
$.fn[NAME] = MetisMenu._jQueryInterface
$.fn[NAME].Constructor = MetisMenu
$.fn[NAME].noConflict = ->
$.fn[NAME] = JQUERY_NO_CONFLICT
MetisMenu._jQueryInterface
MetisMenu
)(jQuery)
return | true | ((global, factory) ->
if typeof define == 'function' and define.amd
define [ 'jquery' ], factory
else if typeof exports != 'undefined'
factory require('jquery')
else
mod = exports: {}
factory global.jquery
global.metisMenu = mod.exports
return
) this, (_jquery) ->
_interopRequireDefault = (obj) ->
if obj and obj.__esModule then obj else default: obj
_classCallCheck = (instance, Constructor) ->
if !(instance instanceof Constructor)
throw new TypeError('Cannot call a class as a function')
return
'use strict'
_jquery2 = _interopRequireDefault(_jquery)
_typeof = if typeof Symbol == 'function' and typeof Symbol.iterator == 'symbol' then ((obj) ->
typeof obj
) else ((obj) ->
if obj and typeof Symbol == 'function' and obj.constructor == Symbol and obj != Symbol.prototype then 'symbol' else typeof obj
)
_createClass = do ->
defineProperties = (target, props) ->
i = 0
while i < props.length
descriptor = props[i]
descriptor.enumerable = descriptor.enumerable or false
descriptor.configurable = true
if 'value' of descriptor
descriptor.writable = true
Object.defineProperty target, descriptor.key, descriptor
i++
return
(Constructor, protoProps, staticProps) ->
if protoProps
defineProperties Constructor.prototype, protoProps
if staticProps
defineProperties Constructor, staticProps
Constructor
MetisMenu = (($) ->
`var MetisMenu`
NAME = 'metisMenu'
DATA_KEY = 'PI:KEY:<KEY>END_PI'
EVENT_KEY = '.' + DATA_KEY
DATA_API_KEY = '.PI:KEY:<KEY>END_PI'
JQUERY_NO_CONFLICT = $.fn[NAME]
TRANSITION_DURATION = 350
Default =
toggle: true
doubleTapToGo: false
preventDefault: true
activeClass: 'active'
collapseClass: 'collapse'
collapseInClass: 'in'
collapsingClass: 'collapsing'
Event =
SHOW: 'show' + EVENT_KEY
SHOWN: 'shown' + EVENT_KEY
HIDE: 'hide' + EVENT_KEY
HIDDEN: 'hidden' + EVENT_KEY
CLICK_DATA_API: 'click' + EVENT_KEY + DATA_API_KEY
transition = false
TransitionEndEvent =
WebkitTransition: 'webkitTransitionEnd'
MozTransition: 'transitionend'
OTransition: 'oTransitionEnd otransitionend'
transition: 'transitionend'
Util =
TRANSITION_END: 'mmTransitionEnd'
triggerTransitionEnd: (element) ->
$(element).trigger transition.end
return
supportsTransitionEnd: ->
Boolean transition
getSpecialTransitionEndEvent = ->
{
bindType: transition.end
delegateType: transition.end
handle: (event) ->
if $(event.target).is(this)
return event.handleObj.handler.apply(this, arguments)
return
}
transitionEndTest = ->
if window.QUnit
return false
el = document.createElement('mm')
for name of TransitionEndEvent
if el.style[name] != undefined
return { end: TransitionEndEvent[name] }
false
transitionEndEmulator = (duration) ->
_this2 = this
called = false
$(this).one Util.TRANSITION_END, ->
called = true
return
setTimeout (->
if !called
Util.triggerTransitionEnd _this2
return
), duration
return
setTransitionEndSupport = ->
transition = transitionEndTest()
if Util.supportsTransitionEnd()
$.event.special[Util.TRANSITION_END] = getSpecialTransitionEndEvent()
return
setTransitionEndSupport()
MetisMenu = do ->
`var MetisMenu`
MetisMenu = (element, config) ->
_classCallCheck this, MetisMenu
@_element = element
@_config = @_getConfig(config)
@_transitioning = null
@init()
return
_createClass MetisMenu, [
{
key: 'init'
value: ->
self = this
$(@_element).find('li.' + @_config.activeClass).has('ul').children('ul').attr('aria-expanded', true).addClass @_config.collapseClass + ' ' + @_config.collapseInClass
$(@_element).find('li').not('.' + @_config.activeClass).has('ul').children('ul').attr('aria-expanded', false).addClass @_config.collapseClass
#add the 'doubleTapToGo' class to active items if needed
if @_config.doubleTapToGo
$(@_element).find('li.' + @_config.activeClass).has('ul').children('a').addClass 'doubleTapToGo'
$(@_element).find('li').has('ul').children('a').on Event.CLICK_DATA_API, (e) ->
_this = $(this)
_parent = _this.parent('li')
_siblings = _parent.siblings('li').children('a')
_list = _parent.children('ul')
if self._config.preventDefault
e.preventDefault()
if _this.attr('aria-disabled') == 'true'
return
if _parent.hasClass(self._config.activeClass) and !self._config.doubleTapToGo
_this.attr 'aria-expanded', false
self._hide _list
else
self._show _list
_this.attr 'aria-expanded', true
if self._config.toggle
_siblings.attr 'aria-expanded', false
if self._config.onTransitionStart
self._config.onTransitionStart e
#Do we need to enable the double tap
if self._config.doubleTapToGo
#if we hit a second time on the link and the href is valid, navigate to that url
if self._doubleTapToGo(_this) and _this.attr('href') != '#' and _this.attr('href') != ''
e.stopPropagation()
document.location = _this.attr('href')
return
return
return
}
{
key: PI:KEY:<KEY>END_PI'
value: (element) ->
if @_transitioning or $(element).hasClass(@_config.collapsingClass)
return
_this = this
_el = $(element)
startEvent = $.Event(Event.SHOW)
_el.trigger startEvent
if startEvent.isDefaultPrevented()
return
_el.parent('li').addClass @_config.activeClass
if @_config.toggle
@_hide _el.parent('li').siblings().children('ul.' + @_config.collapseInClass).attr('aria-expanded', false)
_el.removeClass(@_config.collapseClass).addClass(@_config.collapsingClass).height 0
@setTransitioning true
complete = ->
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass + ' ' + _this._config.collapseInClass).height('').attr 'aria-expanded', true
_this.setTransitioning false
_el.trigger Event.SHOWN
return
if !Util.supportsTransitionEnd()
complete()
return
_el.height(_el[0].scrollHeight).one Util.TRANSITION_END, complete
transitionEndEmulator TRANSITION_DURATION
return
}
{
key: '_hide'
value: (element) ->
if @_transitioning or !$(element).hasClass(@_config.collapseInClass)
return
_this = this
_el = $(element)
startEvent = $.Event(Event.HIDE)
_el.trigger startEvent
if startEvent.isDefaultPrevented()
return
_el.parent('li').removeClass @_config.activeClass
_el.height(_el.height())[0].offsetHeight
_el.addClass(@_config.collapsingClass).removeClass(@_config.collapseClass).removeClass @_config.collapseInClass
@setTransitioning true
complete = ->
if _this._transitioning and _this._config.onTransitionEnd
_this._config.onTransitionEnd()
_this.setTransitioning false
_el.trigger Event.HIDDEN
_el.removeClass(_this._config.collapsingClass).addClass(_this._config.collapseClass).attr 'aria-expanded', false
return
if !Util.supportsTransitionEnd()
complete()
return
if _el.height() == 0 or _el.css('display') == 'none' then complete() else _el.height(0).one(Util.TRANSITION_END, complete)
transitionEndEmulator TRANSITION_DURATION
return
}
{
key: '_doubleTapToGo'
value: (element) ->
if element.hasClass('doubleTapToGo')
element.removeClass 'doubleTapToGo'
return true
if element.parent().children('ul').length
$(@_element).find('.doubleTapToGo').removeClass 'doubleTapToGo'
element.addClass 'doubleTapToGo'
return false
return
}
{
key: 'setTransitioning'
value: (isTransitioning) ->
@_transitioning = isTransitioning
return
}
{
key: 'dispose'
value: ->
$.removeData @_element, DATA_KEY
$(@_element).find('li').has('ul').children('a').off 'click'
@_transitioning = null
@_config = null
@_element = null
return
}
{
key: '_getConfig'
value: (config) ->
config = $.extend({}, Default, config)
config
}
], [ {
key: '_jQueryInterface'
value: (config) ->
@each ->
$this = $(this)
data = $this.data(DATA_KEY)
_config = $.extend({}, Default, $this.data(), (if typeof config == 'undefined' then 'undefined' else _typeof(config)) == 'object' and config)
if !data and /dispose/.test(config)
@dispose()
if !data
data = new MetisMenu(this, _config)
$this.data DATA_KEY, data
if typeof config == 'string'
if data[config] == undefined
throw new Error('No method named "' + config + '"')
data[config]()
return
} ]
MetisMenu
$.fn[NAME] = MetisMenu._jQueryInterface
$.fn[NAME].Constructor = MetisMenu
$.fn[NAME].noConflict = ->
$.fn[NAME] = JQUERY_NO_CONFLICT
MetisMenu._jQueryInterface
MetisMenu
)(jQuery)
return |
[
{
"context": "ree_base'] =\n\tglyphName: 'three'\n\tcharacterName: 'DIGIT THREE'\n\tcontours:\n\t\t0:\n\t\t\tskeleton: true\n\t\t\tclosed: fal",
"end": 79,
"score": 0.7594682574272156,
"start": 68,
"tag": "NAME",
"value": "DIGIT THREE"
}
] | src/glyphs/components/three_base.coffee | byte-foundry/antique.ptf | 0 | exports.glyphs['three_base'] =
glyphName: 'three'
characterName: 'DIGIT THREE'
contours:
0:
skeleton: true
closed: false
nodes:
0:
x: spacingLeft + (14/54) * thickness
y: contours[0].nodes[1].y - Math.min( 33, ( 33 / 700 ) * capHeight )
typeOut: 'line'
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 0 + 'deg'
distr: 0.25
})
1:
x: contours[0].nodes[0].x
y: Math.min(
capHeight - 98 + (4),
contours[0].nodes[2].y - ( 50 / 54 ) * thickness - ( Math.sin( 4 / 180 * Math.PI ) * ( 0.75 * ( 58 / 54 ) * thickness ) ) - 10
)
dirOut: 90 + 'deg'
type: 'smooth'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: 4 / 180 * Math.PI
distr: 0.25
})
2:
x: contours[0].nodes[1].expandedTo[0].x + ( contours[0].nodes[3].expandedTo[0].x - contours[0].nodes[1].expandedTo[0].x ) * ( 90 / 181 )
y: capHeight + overshoot
dirOut: 0 + 'deg'
type: 'smooth'
expand: Object({
width: ( 50 / 54 ) * thickness * contrast
angle: - 90 + 'deg'
distr: 0
})
3:
x: Math.max(
contours[0].nodes[1].expandedTo[0].x + 100 * width + 96 - (14),
contours[0].nodes[1].expandedTo[1].x + 0.75 * ( 58 / 54 ) * thickness + 10
)
# y: contours[0].nodes[1].y - ( 21 / 700 ) * capHeight
y: contours[0].nodes[1].y
dirIn: 90 + 'deg'
typeOut: 'line'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: 173 + 'deg'
distr: 0.25
})
4:
x: contours[0].nodes[3].x
y: Math.max(
contours[0].nodes[5].expandedTo[1].y + 70,
contours[0].nodes[5].expandedTo[0].y + 10
)
dirOut: - 90 + 'deg'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 170 + 'deg'
distr: 0.25
})
5:
x: contours[0].nodes[2].x
y: contours[1].nodes[0].expandedTo[0].y
dirIn: 0 + 'deg'
expand: Object({
width: Math.min(
( 36 / 54 ) * thickness * contrast * contrastExtremity,
contours[1].nodes[0].expand.width
)
angle: 90 + 'deg'
distr: 1
})
1:
skeleton: true
closed: false
nodes:
0:
x: Math.max(
contours[0].nodes[5].x - 52,
contours[0].nodes[0].x
)
y: contours[1].nodes[6].y + ( contours[0].nodes[0].y - contours[1].nodes[6].y ) * ( 239 / 447 ) * crossbar
typeOut: 'line'
expand: Object({
width: Math.min(
( 50 / 54 ) * thickness * contrast * contrastExtremity,
Math.max(
contours[0].nodes[0].y - contours[1].nodes[6].y - 50,
4
)
)
angle: - 90 + 'deg'
distr: 0.5
})
1:
x: contours[0].nodes[5].x
y: contours[1].nodes[0].expandedTo[0].y
dirOut: 0 + 'deg'
expand: Object({
width: Math.min(
( 50 / 54 ) * thickness * contrast * contrastExtremity,
Math.max(
contours[0].nodes[0].y - contours[1].nodes[6].y - 50,
4
)
)
angle: - 90 + 'deg'
distr: 0
})
2:
x: contours[0].nodes[3].x
# y: contours[1].nodes[1].expandedTo[1].y - ( 55 / 700 ) * capHeight
y: contours[1].nodes[1].expandedTo[1].y - 55
dirIn: 90 + 'deg'
typeOut: 'line'
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 175 + 'deg'
distr: 0.25
})
3:
x: contours[1].nodes[2].x
y: contours[1].nodes[5].y
dirOut: - 90 + 'deg'
type: 'smooth'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 171 + 'deg'
distr: 0.25
})
4:
x: contours[1].nodes[6].expandedTo[0].x + ( contours[1].nodes[3].expandedTo[0].x - contours[1].nodes[6].expandedTo[0].x ) * ( 97 / 194)
y: - overshoot
dirOut: 180 + 'deg'
type: 'smooth'
expand: Object({
width: ( 50 / 54 ) * thickness * contrast
angle: 90 + 'deg'
distr: 0
})
5:
x: contours[0].nodes[0].x
y: Math.min(
contours[0].nodes[1].y - 20,
contours[1].nodes[4].y + ( 50 / 54 ) * thickness + 56
)
typeOut: 'line'
dirIn: - 90 + 'deg'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 7 + 'deg'
distr: 0.25
})
6:
x: contours[0].nodes[0].x
y: contours[1].nodes[5].y + Math.min( 31, ( 31 / 700 ) * capHeight )
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 0 + 'deg'
distr: 0.25
})
components:
0:
base: ['serif-curve-inside-auto', 'none']
id: 'topleft'
parentAnchors:
0:
baseWidth: contours[0].nodes[1].expandedTo[0]
baseHeight: contours[0].nodes[1].expandedTo[0].point
noneAnchor: contours[0].nodes[1].expandedTo[0].point
opposite: contours[0].nodes[1].expandedTo[1].point
curveEnd: contours[0].nodes[2].expandedTo[0]
rotationAngle: -15
left: true
# down: true
rotationCenter: contours[0].nodes[1].expandedTo[0].point
parentParameters:
serifWidth: Math.min(
serifWidth,
contours[0].nodes[2].expandedTo[0].y - contours[0].nodes[1].expandedTo[0].y + overshoot
)
1:
base: ['serif-curve-inside-auto', 'none']
id: 'bottom'
parentAnchors:
0:
baseWidth: contours[1].nodes[5].expandedTo[0]
baseHeight: contours[1].nodes[5].expandedTo[0].point
noneAnchor: contours[1].nodes[5].expandedTo[0].point
opposite: contours[1].nodes[5].expandedTo[1].point
curveEnd: contours[1].nodes[4].expandedTo[0]
rotationAngle: -15
left: true
down: true
inverseOrder: true
rotationCenter: contours[1].nodes[5].expandedTo[0].point
parentParameters:
serifWidth: Math.min(
serifWidth,
contours[1].nodes[5].expandedTo[0].y - contours[1].nodes[4].expandedTo[0].y + overshoot
)
| 216642 | exports.glyphs['three_base'] =
glyphName: 'three'
characterName: '<NAME>'
contours:
0:
skeleton: true
closed: false
nodes:
0:
x: spacingLeft + (14/54) * thickness
y: contours[0].nodes[1].y - Math.min( 33, ( 33 / 700 ) * capHeight )
typeOut: 'line'
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 0 + 'deg'
distr: 0.25
})
1:
x: contours[0].nodes[0].x
y: Math.min(
capHeight - 98 + (4),
contours[0].nodes[2].y - ( 50 / 54 ) * thickness - ( Math.sin( 4 / 180 * Math.PI ) * ( 0.75 * ( 58 / 54 ) * thickness ) ) - 10
)
dirOut: 90 + 'deg'
type: 'smooth'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: 4 / 180 * Math.PI
distr: 0.25
})
2:
x: contours[0].nodes[1].expandedTo[0].x + ( contours[0].nodes[3].expandedTo[0].x - contours[0].nodes[1].expandedTo[0].x ) * ( 90 / 181 )
y: capHeight + overshoot
dirOut: 0 + 'deg'
type: 'smooth'
expand: Object({
width: ( 50 / 54 ) * thickness * contrast
angle: - 90 + 'deg'
distr: 0
})
3:
x: Math.max(
contours[0].nodes[1].expandedTo[0].x + 100 * width + 96 - (14),
contours[0].nodes[1].expandedTo[1].x + 0.75 * ( 58 / 54 ) * thickness + 10
)
# y: contours[0].nodes[1].y - ( 21 / 700 ) * capHeight
y: contours[0].nodes[1].y
dirIn: 90 + 'deg'
typeOut: 'line'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: 173 + 'deg'
distr: 0.25
})
4:
x: contours[0].nodes[3].x
y: Math.max(
contours[0].nodes[5].expandedTo[1].y + 70,
contours[0].nodes[5].expandedTo[0].y + 10
)
dirOut: - 90 + 'deg'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 170 + 'deg'
distr: 0.25
})
5:
x: contours[0].nodes[2].x
y: contours[1].nodes[0].expandedTo[0].y
dirIn: 0 + 'deg'
expand: Object({
width: Math.min(
( 36 / 54 ) * thickness * contrast * contrastExtremity,
contours[1].nodes[0].expand.width
)
angle: 90 + 'deg'
distr: 1
})
1:
skeleton: true
closed: false
nodes:
0:
x: Math.max(
contours[0].nodes[5].x - 52,
contours[0].nodes[0].x
)
y: contours[1].nodes[6].y + ( contours[0].nodes[0].y - contours[1].nodes[6].y ) * ( 239 / 447 ) * crossbar
typeOut: 'line'
expand: Object({
width: Math.min(
( 50 / 54 ) * thickness * contrast * contrastExtremity,
Math.max(
contours[0].nodes[0].y - contours[1].nodes[6].y - 50,
4
)
)
angle: - 90 + 'deg'
distr: 0.5
})
1:
x: contours[0].nodes[5].x
y: contours[1].nodes[0].expandedTo[0].y
dirOut: 0 + 'deg'
expand: Object({
width: Math.min(
( 50 / 54 ) * thickness * contrast * contrastExtremity,
Math.max(
contours[0].nodes[0].y - contours[1].nodes[6].y - 50,
4
)
)
angle: - 90 + 'deg'
distr: 0
})
2:
x: contours[0].nodes[3].x
# y: contours[1].nodes[1].expandedTo[1].y - ( 55 / 700 ) * capHeight
y: contours[1].nodes[1].expandedTo[1].y - 55
dirIn: 90 + 'deg'
typeOut: 'line'
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 175 + 'deg'
distr: 0.25
})
3:
x: contours[1].nodes[2].x
y: contours[1].nodes[5].y
dirOut: - 90 + 'deg'
type: 'smooth'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 171 + 'deg'
distr: 0.25
})
4:
x: contours[1].nodes[6].expandedTo[0].x + ( contours[1].nodes[3].expandedTo[0].x - contours[1].nodes[6].expandedTo[0].x ) * ( 97 / 194)
y: - overshoot
dirOut: 180 + 'deg'
type: 'smooth'
expand: Object({
width: ( 50 / 54 ) * thickness * contrast
angle: 90 + 'deg'
distr: 0
})
5:
x: contours[0].nodes[0].x
y: Math.min(
contours[0].nodes[1].y - 20,
contours[1].nodes[4].y + ( 50 / 54 ) * thickness + 56
)
typeOut: 'line'
dirIn: - 90 + 'deg'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 7 + 'deg'
distr: 0.25
})
6:
x: contours[0].nodes[0].x
y: contours[1].nodes[5].y + Math.min( 31, ( 31 / 700 ) * capHeight )
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 0 + 'deg'
distr: 0.25
})
components:
0:
base: ['serif-curve-inside-auto', 'none']
id: 'topleft'
parentAnchors:
0:
baseWidth: contours[0].nodes[1].expandedTo[0]
baseHeight: contours[0].nodes[1].expandedTo[0].point
noneAnchor: contours[0].nodes[1].expandedTo[0].point
opposite: contours[0].nodes[1].expandedTo[1].point
curveEnd: contours[0].nodes[2].expandedTo[0]
rotationAngle: -15
left: true
# down: true
rotationCenter: contours[0].nodes[1].expandedTo[0].point
parentParameters:
serifWidth: Math.min(
serifWidth,
contours[0].nodes[2].expandedTo[0].y - contours[0].nodes[1].expandedTo[0].y + overshoot
)
1:
base: ['serif-curve-inside-auto', 'none']
id: 'bottom'
parentAnchors:
0:
baseWidth: contours[1].nodes[5].expandedTo[0]
baseHeight: contours[1].nodes[5].expandedTo[0].point
noneAnchor: contours[1].nodes[5].expandedTo[0].point
opposite: contours[1].nodes[5].expandedTo[1].point
curveEnd: contours[1].nodes[4].expandedTo[0]
rotationAngle: -15
left: true
down: true
inverseOrder: true
rotationCenter: contours[1].nodes[5].expandedTo[0].point
parentParameters:
serifWidth: Math.min(
serifWidth,
contours[1].nodes[5].expandedTo[0].y - contours[1].nodes[4].expandedTo[0].y + overshoot
)
| true | exports.glyphs['three_base'] =
glyphName: 'three'
characterName: 'PI:NAME:<NAME>END_PI'
contours:
0:
skeleton: true
closed: false
nodes:
0:
x: spacingLeft + (14/54) * thickness
y: contours[0].nodes[1].y - Math.min( 33, ( 33 / 700 ) * capHeight )
typeOut: 'line'
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 0 + 'deg'
distr: 0.25
})
1:
x: contours[0].nodes[0].x
y: Math.min(
capHeight - 98 + (4),
contours[0].nodes[2].y - ( 50 / 54 ) * thickness - ( Math.sin( 4 / 180 * Math.PI ) * ( 0.75 * ( 58 / 54 ) * thickness ) ) - 10
)
dirOut: 90 + 'deg'
type: 'smooth'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: 4 / 180 * Math.PI
distr: 0.25
})
2:
x: contours[0].nodes[1].expandedTo[0].x + ( contours[0].nodes[3].expandedTo[0].x - contours[0].nodes[1].expandedTo[0].x ) * ( 90 / 181 )
y: capHeight + overshoot
dirOut: 0 + 'deg'
type: 'smooth'
expand: Object({
width: ( 50 / 54 ) * thickness * contrast
angle: - 90 + 'deg'
distr: 0
})
3:
x: Math.max(
contours[0].nodes[1].expandedTo[0].x + 100 * width + 96 - (14),
contours[0].nodes[1].expandedTo[1].x + 0.75 * ( 58 / 54 ) * thickness + 10
)
# y: contours[0].nodes[1].y - ( 21 / 700 ) * capHeight
y: contours[0].nodes[1].y
dirIn: 90 + 'deg'
typeOut: 'line'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: 173 + 'deg'
distr: 0.25
})
4:
x: contours[0].nodes[3].x
y: Math.max(
contours[0].nodes[5].expandedTo[1].y + 70,
contours[0].nodes[5].expandedTo[0].y + 10
)
dirOut: - 90 + 'deg'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 170 + 'deg'
distr: 0.25
})
5:
x: contours[0].nodes[2].x
y: contours[1].nodes[0].expandedTo[0].y
dirIn: 0 + 'deg'
expand: Object({
width: Math.min(
( 36 / 54 ) * thickness * contrast * contrastExtremity,
contours[1].nodes[0].expand.width
)
angle: 90 + 'deg'
distr: 1
})
1:
skeleton: true
closed: false
nodes:
0:
x: Math.max(
contours[0].nodes[5].x - 52,
contours[0].nodes[0].x
)
y: contours[1].nodes[6].y + ( contours[0].nodes[0].y - contours[1].nodes[6].y ) * ( 239 / 447 ) * crossbar
typeOut: 'line'
expand: Object({
width: Math.min(
( 50 / 54 ) * thickness * contrast * contrastExtremity,
Math.max(
contours[0].nodes[0].y - contours[1].nodes[6].y - 50,
4
)
)
angle: - 90 + 'deg'
distr: 0.5
})
1:
x: contours[0].nodes[5].x
y: contours[1].nodes[0].expandedTo[0].y
dirOut: 0 + 'deg'
expand: Object({
width: Math.min(
( 50 / 54 ) * thickness * contrast * contrastExtremity,
Math.max(
contours[0].nodes[0].y - contours[1].nodes[6].y - 50,
4
)
)
angle: - 90 + 'deg'
distr: 0
})
2:
x: contours[0].nodes[3].x
# y: contours[1].nodes[1].expandedTo[1].y - ( 55 / 700 ) * capHeight
y: contours[1].nodes[1].expandedTo[1].y - 55
dirIn: 90 + 'deg'
typeOut: 'line'
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 175 + 'deg'
distr: 0.25
})
3:
x: contours[1].nodes[2].x
y: contours[1].nodes[5].y
dirOut: - 90 + 'deg'
type: 'smooth'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 171 + 'deg'
distr: 0.25
})
4:
x: contours[1].nodes[6].expandedTo[0].x + ( contours[1].nodes[3].expandedTo[0].x - contours[1].nodes[6].expandedTo[0].x ) * ( 97 / 194)
y: - overshoot
dirOut: 180 + 'deg'
type: 'smooth'
expand: Object({
width: ( 50 / 54 ) * thickness * contrast
angle: 90 + 'deg'
distr: 0
})
5:
x: contours[0].nodes[0].x
y: Math.min(
contours[0].nodes[1].y - 20,
contours[1].nodes[4].y + ( 50 / 54 ) * thickness + 56
)
typeOut: 'line'
dirIn: - 90 + 'deg'
expand: Object({
width: ( 58 / 54 ) * thickness
angle: - 7 + 'deg'
distr: 0.25
})
6:
x: contours[0].nodes[0].x
y: contours[1].nodes[5].y + Math.min( 31, ( 31 / 700 ) * capHeight )
expand: Object({
width: ( 57 / 54 ) * thickness
angle: 0 + 'deg'
distr: 0.25
})
components:
0:
base: ['serif-curve-inside-auto', 'none']
id: 'topleft'
parentAnchors:
0:
baseWidth: contours[0].nodes[1].expandedTo[0]
baseHeight: contours[0].nodes[1].expandedTo[0].point
noneAnchor: contours[0].nodes[1].expandedTo[0].point
opposite: contours[0].nodes[1].expandedTo[1].point
curveEnd: contours[0].nodes[2].expandedTo[0]
rotationAngle: -15
left: true
# down: true
rotationCenter: contours[0].nodes[1].expandedTo[0].point
parentParameters:
serifWidth: Math.min(
serifWidth,
contours[0].nodes[2].expandedTo[0].y - contours[0].nodes[1].expandedTo[0].y + overshoot
)
1:
base: ['serif-curve-inside-auto', 'none']
id: 'bottom'
parentAnchors:
0:
baseWidth: contours[1].nodes[5].expandedTo[0]
baseHeight: contours[1].nodes[5].expandedTo[0].point
noneAnchor: contours[1].nodes[5].expandedTo[0].point
opposite: contours[1].nodes[5].expandedTo[1].point
curveEnd: contours[1].nodes[4].expandedTo[0]
rotationAngle: -15
left: true
down: true
inverseOrder: true
rotationCenter: contours[1].nodes[5].expandedTo[0].point
parentParameters:
serifWidth: Math.min(
serifWidth,
contours[1].nodes[5].expandedTo[0].y - contours[1].nodes[4].expandedTo[0].y + overshoot
)
|
[
{
"context": "0.20\t1.70\n \"\"\"\n }\n\n {\n name: \"Sudoku\"\n code: \"\"\"\n #include <iostream",
"end": 4855,
"score": 0.9967656135559082,
"start": 4849,
"tag": "NAME",
"value": "Sudoku"
},
{
"context": " input: \"12 90\"\n }\n\n {\n name: \"Hanoi towers\"\n code: \"\"\"\n #include <iostream",
"end": 9178,
"score": 0.9996069073677063,
"start": 9166,
"tag": "NAME",
"value": "Hanoi towers"
},
{
"context": "\"\"\n input: \"3\"\n }\n\n {\n name: \"Rhombus\"\n code: \"\"\"\n #include <iostream",
"end": 9757,
"score": 0.9986212849617004,
"start": 9750,
"tag": "NAME",
"value": "Rhombus"
},
{
"context": "e 'compile', 'run' or 'debug'\"\n name: 'js_demo'\n height: 200\n prompt: '> '",
"end": 15679,
"score": 0.9383794665336609,
"start": 15672,
"tag": "USERNAME",
"value": "js_demo"
}
] | client/main/main.ng.coffee | albertsgrc/cmm-frontend | 0 | import '/client/app.ng.coffee'
EXAMPLES = [
{
name: "Default"
code: """
#include <iostream>
using namespace std;
int main() {
}
"""
}
{
name: "MatrixMul"
code: """
#include <iostream>
using namespace std;
double** read_matrix(int* n, int* m) {
double **M;
cout << "Enter the first dimension: ";
bool correct = cin >> *n;
while (not correct) { cout << "Invalid first dimension" << endl; correct = cin >> *n; }
cout << endl;
cout << "Enter the second dimension: ";
correct = cin >> *m;
while (not correct) { cout << "Invalid second dimension" << endl; correct = cin >> *m; }
cout << endl;
M = new double* [*n];
for (int i = 0; i < *n; ++i) M[i] = new double[*m];
cout << "Reserved " << (*n)*(*m) << " elements" << endl;
cout << "Enter the matrix:" << endl;
for (int i = 0; i < *n; ++i)
for (int j = 0; j < *m; ++j)
cin >> M[i][j];
return M;
}
void write_matrix(double **M, int n, int m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << M[i][j] << ' ';
}
cout << endl;
}
}
double** matrix_mul(double **M1, int n1, int m1, double **M2, int n2, int m2) {
if (m1 != n2) {
cout << "Cannot multiply matrices with sizes " << n1 << "x" << m1 << " and " << n2 << "x" << m2 << endl;
return nullptr;
}
else {
double** R = new double*[n1];
for (int i = 0; i < n1; ++i) R[i] = new double[m2];
for (int i = 0; i < n1; ++i)
for (int j = 0; j < m2; ++j)
for (int k = 0; k < n2; ++k)
R[i][j] += M1[i][k]*M2[k][j];
return R;
}
}
void free_matrix(double **M, int n) {
for (int i = 0; i < n; ++i) delete[] M[i];
delete[] M;
}
int main() {
int n1, m1, n2, m2;
double **M1, **M2;
cout << "First matrix:" << endl;
M1 = read_matrix(&n1, &m1);
cout << "Second matrix:" << endl;
M2 = read_matrix(&n2, &m2);
double **R = matrix_mul(M1, n1, m1, M2, n2, m2);
if (R != nullptr) {
write_matrix(R, n1, m2);
free_matrix(R, n1);
}
free_matrix(M1, n1);
free_matrix(M2, n2);
}
"""
input: """
10 10
0.985972 0.41644 0.00917712 0.960001 0.738504 0.178032 0.279277 0.871901 0.937947 0.368076
0.796421 0.501716 0.352193 0.914611 0.305051 0.170487 0.426052 0.388529 0.821443 0.341463
0.866829 0.0475431 0.0520645 0.225011 0.521641 0.962696 0.27995 0.955066 0.789707 0.732368
0.316189 0.877086 0.972151 0.753573 0.687137 0.96446 0.337021 0.68242 0.217289 0.813299
0.949761 0.314933 0.604641 0.42739 0.543298 0.947111 0.0547473 0.432424 0.499621 0.630333
0.230609 0.486681 0.739983 0.352329 0.974505 0.524403 0.107063 0.0682698 0.363578 0.149505
0.0419426 0.994638 0.89545 0.65836 0.390982 0.462052 0.740027 0.974471 0.234875 0.374738
0.820769 0.119097 0.884086 0.648969 0.303171 0.797565 0.223649 0.576949 0.751251 0.130427
0.618224 0.113461 0.25556 0.614178 0.901178 0.0406404 0.732617 0.808629 0.0322353 0.515182
0.435284 0.125175 0.393207 0.580732 0.663967 0.636366 0.402737 0.59888 0.797121 0.979881
10 10
-0.02 0.16 -0.46 -1.19 2.11 -0.26 0.52 -0.41 0.31 -0.34
0.16 0.46 0.07 -0.42 1.01 0.29 0.88 -1.16 -0.53 -0.52
0.61 -1.81 -2.38 -2.34 2.99 -0.38 1.85 0.29 -0.22 1.62
-0.09 1.24 0.82 3.33 -3.39 -0.29 -2.40 1.12 0.40 -0.99
0.28 -0.39 0.16 0.03 -0.38 0.95 -0.31 -0.18 0.33 -0.05
-1.51 2.00 2.91 3.21 -3.75 0.63 -2.33 0.73 0.23 -1.98
-2.35 2.79 2.24 0.80 -2.43 0.75 -0.80 -0.01 0.93 -1.17
1.51 -2.20 -0.94 -1.00 1.20 -0.77 1.31 0.28 -0.22 0.65
0.32 -0.14 -0.26 -1.47 0.49 0.39 0.87 -0.10 -0.79 1.06
0.37 -0.86 -1.47 -1.09 2.30 -0.80 0.88 -0.88 -0.20 1.70
"""
}
{
name: "Sudoku"
code: """
#include <iostream>
using namespace std;
int const SIZE = 9;
const int SUBSIZE = SIZE/3;
int S[9][9];
bool MR[9][9], MC[9][9], MQ[9][9], SET[9][9];
bool found;
int quad(const int i, const int j) {
return (i/SUBSIZE)*SUBSIZE + j/SUBSIZE;
}
bool canPutNum(int num, int i, int j) {
return not MC[j][num-1] and not MQ[quad(i, j)][num-1]
and not MR[i][num-1];
}
void putNum(int num, int i, int j) {
S[i][j] = num;
MR[i][num-1] = MC[j][num-1] = MQ[quad(i, j)][num-1] = true;
}
void removeNum(int num, int i, int j) {
MR[i][num-1] = MC[j][num-1] = MQ[quad(i, j)][num-1] = false;
}
void backtrack(int i, int j) {
if (not found) {
if (i < SIZE) {
if (not SET[i][j]) {
for (int num = 1; num <= SIZE; ++num) {
if (canPutNum(num, i, j)) {
putNum(num, i, j);
if (j + 1 == SIZE) backtrack(i + 1, 0);
else backtrack(i, j + 1);
if (not found) removeNum(num, i, j);
} } }
else {
if (j + 1 == SIZE) backtrack(i + 1, 0);
else backtrack(i, j + 1);
} }
else found = true;
} }
void initialize() {
found = false;
for (int i = 0; i < SIZE; ++i)
for (int j = 0; j < SIZE; ++j)
*(*(MR + i) + j) = (*(MC + i))[j] = MQ[i][j] = SET[i][j] = false;
}
void read() {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
char c; cin >> c;
if (c != '.') {
putNum(c - '0', i, j);
SET[i][j] = true;
} } } }
void print() {
cout << endl;
for (int i = 0; i < SIZE; ++i) {
cout << S[i][0];
for (int j = 1; j < SIZE; ++j) cout << ' ' << S[i][j];
cout << endl;
} }
void solve() {
backtrack(0, 0);
}
int main() {
int n; cin >> n; cout << n << endl;
for (int i = 0; i < n; ++i) {
initialize();
read();
solve();
print();
} }
"""
input: """
2
. . . . . 2 3 . 7
. . . . . 6 4 5 .
1 . . 9 3 . . . .
. . . . 6 1 8 . .
. 4 8 . . . 5 6 .
. . 6 4 2 . . . .
. . . . 7 5 . . 8
. 2 9 1 . . . . .
4 . 5 6 . . . . .
7 . . . . 2 . . 4
1 . . . . . 7 6 .
2 . . . 8 . 3 . 9
. . . 6 5 . 8 2 .
. . . . 2 . . . .
. 2 6 . 9 1 . . .
8 . 7 . 1 . . . 5
. 5 9 . . . . . 3
3 . . 5 . . . . 8
"""
}
{
name: "GCD"
code: """
// P67723_en: Greatest common divisor
// Pre: two strictly positive natural numbers a and b
// Post: the greatest common divisor of a and b
#include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int a0 = a; //we need to keep the value of the original a and b
int b0 = b;
while ( b != 0) {
int r = a%b; //remainder
a = b;
b = r;
}
cout << "The gcd of " << a0 << " and " << b0 << " is " << a << "." << endl;
}
"""
input: "12 90"
}
{
name: "Hanoi towers"
code: """
#include <iostream>
using namespace std;
void hanoi(int n, char from, char to, char aux) {
if (n > 0) {
hanoi(n - 1, from, aux, to);
cout << from << " => " << to << endl;
hanoi(n - 1, aux, to, from);
}
}
int main() {
int ndiscos;
cin >> ndiscos;
hanoi(ndiscos, 'A', 'C', 'B');
}
"""
input: "3"
}
{
name: "Rhombus"
code: """
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 1; i <= x; ++i) {
for (int j = 0; j < x + i - 1; ++j) {
if (j < x - i) cout << ' ';
else cout << '*';
}
cout << endl;
}
for (int i = 1; i < x; ++i) {
for (int j = 0; j < 2*x - i - 1; ++j) {
if (j >= i) cout << '*';
else cout << ' ';
}
cout << endl;
}
}
"""
input: "10"
}
]
STATUS = {
WAITING_INPUT: {
icon: 'input'
tooltip: "Waiting for input"
color: "white"
text: "Waiting for input"
}
RUNNING: {
icon: 'directions_run'
tooltip: "Running"
color: "white"
text: "Running"
}
PAUSED: {
icon: "pause"
tooltip: "Paused"
color: "white"
text: ""
}
COMPILATION_SUCCESSFUL: {
icon: 'done'
color: 'white'
text: 'Compilation successful'
tooltip: "See AST and instructions tabs on the right"
}
COMPILATION_ERROR: {
icon: 'error'
color: '#F48FB1'
text: 'Compilation error'
tooltip: "See the terminal for errors"
}
EXITED: (status) ->
{
icon: if status is 0 then 'done' else 'error'
color: if status is 0 then 'white' else '#F48FB1'
text: "Exited with status <b>#{status}</b>"
tooltip: if status is 0 then "Execution finished correctly" else "Execution finished abnormaly"
}
KILLED: {
icon: "stop"
color: 'white'
text: 'Killed'
tooltip: "You killed the program"
}
}
MainCtrl = ($scope, $state, $window, $mdMedia, $rootScope, $mdToast, $timeout, $sce, $mdDialog) ->
for status, value of STATUS
if value.text?
value.text = $sce.trustAsHtml(value.text)
#####
# SCOPE VARIABLES INITIALIZATION
#####
initialExample = 0
$scope.selectedIndex = 0 # For the tabs
$scope.speed = 0.4;
$scope.astString = ""
$scope.instructionsString = ""
$scope.compilerHelpString = ""
$scope.fixedInput = EXAMPLES[initialExample].input ? ""
$scope.compiled = no
$scope.compileError = no
$scope.running = no
$scope.debugging = no
$scope.runningStatus = no
$scope.variables = {}
$scope.$mdMedia = $mdMedia
$scope.$watch('runningStatus', _.debounce(( (newv, oldv) ->
icon = $('.status i')
times = if newv is oldv then 2 else 3
icon.delay(100).fadeTo(100,0.5).delay(100).fadeTo(100,1) for time in [0...times]
), 50))
#####
# RESPONSIVE
#####
$rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
if toState.name isnt "terminal"
$("#terminal").appendTo(".terminalOuter")
$.terminal.active()?.scroll_to_bottom()
)
$rootScope.$on('$viewContentLoaded', (event, toState, toParams, fromState, fromParams) ->
if $state.current.name is "terminal"
$("#terminal").appendTo("#terminalTab")
$.terminal.active()?.scroll_to_bottom()
)
$scope.$watch((-> $mdMedia('gt-sm')), (big) ->
if big
$state.go('fixed-input')
if $scope.tabs.some((e) -> e.title is 'Terminal')
$scope.tabs.shift()
$("#terminal").appendTo(".terminalOuter")
else unless $scope.tabs.some((e) -> e.title is 'Terminal')
$state.go('terminal')
$scope.tabs.unshift { isTerminal: yes, icon: 'tv', title: 'Terminal', state: 'terminal', showCondition: -> yes }
)
#####
# EDITOR SETUP
#####
editor = ace.edit("editor")
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/c_cpp")
editor.$blockScrolling = Infinity
editor.setValue(EXAMPLES[initialExample].code, -1)
aceRange = ace.require('ace/range').Range;
getBreakpoints = -> Object.keys(editor.session.getBreakpoints(undefined, 0)).map((x) -> parseInt(x) + 1)
editor.on("guttermousedown", (e) ->
target = e.domEvent.target
if target.className.indexOf("ace_gutter-cell") == -1
return
if !editor.isFocused()
editor.focus()
if e.clientX > 25 + target.getBoundingClientRect().left
return
{ row } = e.getDocumentPosition()
breakpoints = e.editor.session.getBreakpoints(row, 0)
if row not of breakpoints
e.editor.session.setBreakpoint(row)
#range = new aceRange(row, 0, row, 1);
#markedLines[row] = e.editor.session.addMarker(range, "warning", "fullLine", true);
worker.postMessage({ command: "addBreakpoint", breakpoint: row + 1 })
else
e.editor.session.clearBreakpoint(row)
#editor.getSession().removeMarker markedLines[row]
#delete markedLines[row]
worker.postMessage({ command: "removeBreakpoint", breakpoint: row + 1 })
e.stop()
)
#####
# TERMINAL SETUP
#####
jQuery ($) ->
$('#terminal').terminal ((command) ->
if command in ["compile", "c"]
$scope.compile(yes)
else if command in ["run", "r"]
$scope.run(yes)
else if command in ["debug", "d"]
$scope.debug(yes)
else
this.error("Invalid command #{command}. Type 'compile', 'run' or 'debug'")
),
greetings: "This is the C-- terminal. Type 'compile', 'run' or 'debug'"
name: 'js_demo'
height: 200
prompt: '> '
completion: ['compile', 'run', 'debug', 'c', 'r', 'd']
scrollOnEcho: yes
keymap: {
"CTRL+D": -> worker.postMessage({ command: "endOfInput" })
"CTRL+Z": ->
$scope.kill()
$scope.$apply()
"CTRL+C": ->
$scope.kill()
$scope.$apply()
}
#####
# WORKER SETUP
#####
worker = null
output = null
currentLine = null
listen = {}
terminal = -> $.terminal.active()
echo = (msg) ->
terminal().echo(if msg.length is 0 then "\0" else msg)
buffer = (fn) ->
timeout = null
buff = ""
({ string }) ->
buff += string
clearTimeout(timeout)
timeout = setTimeout((-> fn({ string: buff }); buff = ""))
listen.output = buffer(({ string }) ->
term = terminal()
lines = string.split('\n')
if lines.length is 1
term.set_prompt(output = term.get_prompt() + lines[0])
else
echo((output ? "") + lines[0])
for line in lines[1...-1]
echo(line)
term.set_prompt(output = lines[lines.length - 1]))
listen.compilationError = ({ message, description }) ->
$scope.compileError = yes
$scope.compiled = yes
$scope.compilerHelpString = description ? ""
$scope.runningStatus = STATUS.COMPILATION_ERROR
if $scope.compilerHelpString.length > 0
$state.go('compilation-help')
$timeout(->$scope.selectedIndex = 1)
term = terminal()
term.error message
listen.startRunning = ->
#console.log "startRunning"
$scope.running = yes
$scope.runningStatus = STATUS.RUNNING
unless $mdMedia('gt-sm')
$timeout((->$state.go('terminal'); $scope.selectedIndex = 0))
$.terminal.active().push((command) ->
output = null
this.set_prompt("")
worker.postMessage({ command: "input", input: command })
,
name: 'runEnvironment'
prompt: ''
)
listen.startDebugging = ->
$scope.debugging = yes
listen.startRunning()
listen.currentLine = ({ line }) ->
editor.getSession().removeMarker currentLine if currentLine?
row = line - 1
range = new aceRange(row, 0, row, 1);
currentLine = editor.getSession().addMarker(range, "current-line", "fullLine", true)
listen.compilationSuccessful = ({ ast, instructions, goingToRun }) ->
if $scope.compileError
$state.go('instructions')
$timeout(-> $scope.selectedIndex = 2)
$scope.compiled = yes
$scope.compileError = no
$scope.astString = ast
$scope.instructionsString = instructions
unless goingToRun
$scope.runningStatus = STATUS.COMPILATION_SUCCESSFUL
listen.executionFinish = ({ status }) ->
# TODO: Show status somehow
if $scope.debugging and $state.current.name is "variables"
$state.go('fixed-input')
$scope.selectedIndex = 0
# Output can arrive after executionFinish signal, so we must wait for the call stack to clear
setTimeout(->
term = terminal()
term.pop()
term.set_prompt((if output? then output else "") + "> ")
)
$scope.running = $scope.debugging = no
$scope.waitingForInput = no
if status?
$scope.runningStatus = STATUS.EXITED(status)
$scope.runningStatus.text = $sce.trustAsHtml($scope.runningStatus.text)
else
$scope.runningStatus = STATUS.KILLED
output = null
editor.getSession().removeMarker currentLine if currentLine?
currentLine = null
listen.resumeRunning = ->
#console.log "resume"
if $scope.debugging
$timeout((-> # Prevents continuous flashing when using step over/step
if $scope.runningStatus is STATUS.RUNNING
$state.go('fixed-input'); $scope.selectedIndex = 0
), 100)
$scope.runningStatus = STATUS.RUNNING
listen.waitingForInput = ->
$scope.runningStatus = STATUS.WAITING_INPUT
$.terminal.active().focus()
listen.paused = ({ variables }) ->
$scope.variables = variables
$scope.runningStatus = STATUS.PAUSED
$state.go('variables')
$timeout(->$scope.selectedIndex = 3)
listen.variableSet = ({ id, value, repr }) ->
$scope.variables[id].value = value
$scope.variables[id].repr = repr
$scope.variables[id].edit = no
listen.invalidVariableValue = ({ id, value }) ->
showToast "Invalid value '#{value}' for variable with type #{$scope.variables[id].type}"
do resetWorker = ->
worker = new Worker("/worker.js")
worker.onmessage = (e) ->
{ data: { event, data }} = e
unless listen[event]?
throw "Invalid event #{event}"
else
listen[event](data)
$scope.$apply()
for breakpoint in getBreakpoints()
worker.postMessage({ command: "addBreakpoint", breakpoint })
#####
# ACTIONS
#####
$scope.selectExample = (example) ->
editor.setValue(example.code, -1)
$scope.fixedInput = example.input ? ""
$scope.debug = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "debug")
output = null
worker.postMessage({ command: "debug", code: editor.getValue(), input: $scope.fixedInput })
null
$scope.run = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "run")
output = null
worker.postMessage({ command: "run", code: editor.getValue(), input: $scope.fixedInput })
null
$scope.continue = -> worker.postMessage({ command: "continue" })
$scope.kill = ->
listen.executionFinish({ status: null })
worker.terminate()
resetWorker()
$scope.compile = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "compile")
worker.postMessage({ command: "compile", code: editor.getValue() })
$scope.stepOver = -> worker.postMessage({ command: "stepOver" })
$scope.stepInto = -> worker.postMessage({ command: "stepInto" })
$scope.stepOut = -> worker.postMessage({ command: "stepOut" })
$scope.stepInstruction = -> worker.postMessage({ command: "stepInstruction" })
showToast = (text) ->
toast = $mdToast.simple()
.textContent(text)
.position('top right')
.hideDelay(3000);
$mdToast.show toast
$scope.tryToEdit = (variable, name) ->
if variable.const
showToast "Cannot set value for #{name}: it's declared const"
else if variable.isArray
showToast "Changing array values is not supported yet"
else
variable.edit = yes
variable.editValue =
if variable.isChar # Null char values can mess up (no way to tell whether there's something)
''
else
variable.value
$scope.confirmVariableEdit = (variable, name) ->
{ editValue: value } = variable
worker.postMessage({ command: "setVariable", id: name, value })
$scope.cancelVariableEdit = (variable) ->
variable.editValue = null
variable.edit = no
$scope.showHelp = ->
$scope.showAbout = (ev) ->
$mdDialog.show({
templateUrl: 'client/about/about.html'
controller: ['$scope', '$mdDialog', ($scope, $mdDialog) -> $scope.close = -> $mdDialog.cancel()]
parent: angular.element(document.body)
targetEvent: ev
clickOutsideToClose: yes
}
)
#####
# CONTENT
#####
$scope.examples = EXAMPLES
$scope.tabs = [
{
icon: 'input'
title: 'Fixed input'
state: 'fixed-input'
showCondition: -> yes
}
#{
# icon: 'bug_report'
# title: 'Variables'
# state: 'variables'
# showCondition: -> $scope.debugging
#}
{
icon: 'build'
title: 'Compilation Help'
state: 'compilation-help'
showCondition: -> $scope.compiled and $scope.compileError and $scope.compilerHelpString.length > 0
}
{
icon: 'code'
title: 'AST'
state: 'ast'
showCondition: -> $scope.compiled and not $scope.compileError
}
{
icon: 'format_list_numbered'
title: 'Instructions'
state: 'instructions'
showCondition: -> $scope.compiled and not $scope.compileError
}
{
icon: "bug_report"
title: 'Variables'
state: 'variables'
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
]
$scope.buttons = [
{
text: "Compile"
icon: "build"
tooltip: "Compiles the program"
color: '#7986CB'
action: $scope.compile
showCondition: -> not $scope.running
}
{
text: "Run"
icon: "play_arrow"
tooltip: "Compiles and runs the program"
color: '#009688'
action: $scope.run
showCondition: -> not $scope.running
}
{
text: "Kill"
icon: "stop"
tooltip: "Kills the program"
color: "#EF5350"
action: $scope.kill
showCondition: -> $scope.running
}
{
text: "Debug"
icon: "bug_report"
tooltip: "Compiles and starts debugging"
color: '#EF6C00'
action: $scope.debug
showCondition: -> not $scope.running
}
{
text: "Continue"
icon: "play_arrow"
tooltip: "Continues debugging the program"
color: '#009688'
action: $scope.continue
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step over"
icon: "vertical_align_bottom"
tooltip: "Runs the program until the next line of code"
color: '#689F38'
action: $scope.stepOver
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step into"
icon: "subdirectory_arrow_right"
tooltip: "Enters the function call or steps over"
color: '#558B2F'
action: $scope.stepInto
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step out"
icon: "reply"
tooltip: "Runs the program until the current function returns"
color: '#33691E'
action: $scope.stepOut
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step"
icon: "keyboard_arrow_down"
tooltip: "Runs the program until the next instruction"
color: "#827717"
action: $scope.stepInstruction
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
]
app.controller('MainCtrl', ['$scope', '$state', '$window', '$mdMedia', '$rootScope', '$mdToast', '$timeout', '$sce', '$mdDialog', MainCtrl])
| 110384 | import '/client/app.ng.coffee'
EXAMPLES = [
{
name: "Default"
code: """
#include <iostream>
using namespace std;
int main() {
}
"""
}
{
name: "MatrixMul"
code: """
#include <iostream>
using namespace std;
double** read_matrix(int* n, int* m) {
double **M;
cout << "Enter the first dimension: ";
bool correct = cin >> *n;
while (not correct) { cout << "Invalid first dimension" << endl; correct = cin >> *n; }
cout << endl;
cout << "Enter the second dimension: ";
correct = cin >> *m;
while (not correct) { cout << "Invalid second dimension" << endl; correct = cin >> *m; }
cout << endl;
M = new double* [*n];
for (int i = 0; i < *n; ++i) M[i] = new double[*m];
cout << "Reserved " << (*n)*(*m) << " elements" << endl;
cout << "Enter the matrix:" << endl;
for (int i = 0; i < *n; ++i)
for (int j = 0; j < *m; ++j)
cin >> M[i][j];
return M;
}
void write_matrix(double **M, int n, int m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << M[i][j] << ' ';
}
cout << endl;
}
}
double** matrix_mul(double **M1, int n1, int m1, double **M2, int n2, int m2) {
if (m1 != n2) {
cout << "Cannot multiply matrices with sizes " << n1 << "x" << m1 << " and " << n2 << "x" << m2 << endl;
return nullptr;
}
else {
double** R = new double*[n1];
for (int i = 0; i < n1; ++i) R[i] = new double[m2];
for (int i = 0; i < n1; ++i)
for (int j = 0; j < m2; ++j)
for (int k = 0; k < n2; ++k)
R[i][j] += M1[i][k]*M2[k][j];
return R;
}
}
void free_matrix(double **M, int n) {
for (int i = 0; i < n; ++i) delete[] M[i];
delete[] M;
}
int main() {
int n1, m1, n2, m2;
double **M1, **M2;
cout << "First matrix:" << endl;
M1 = read_matrix(&n1, &m1);
cout << "Second matrix:" << endl;
M2 = read_matrix(&n2, &m2);
double **R = matrix_mul(M1, n1, m1, M2, n2, m2);
if (R != nullptr) {
write_matrix(R, n1, m2);
free_matrix(R, n1);
}
free_matrix(M1, n1);
free_matrix(M2, n2);
}
"""
input: """
10 10
0.985972 0.41644 0.00917712 0.960001 0.738504 0.178032 0.279277 0.871901 0.937947 0.368076
0.796421 0.501716 0.352193 0.914611 0.305051 0.170487 0.426052 0.388529 0.821443 0.341463
0.866829 0.0475431 0.0520645 0.225011 0.521641 0.962696 0.27995 0.955066 0.789707 0.732368
0.316189 0.877086 0.972151 0.753573 0.687137 0.96446 0.337021 0.68242 0.217289 0.813299
0.949761 0.314933 0.604641 0.42739 0.543298 0.947111 0.0547473 0.432424 0.499621 0.630333
0.230609 0.486681 0.739983 0.352329 0.974505 0.524403 0.107063 0.0682698 0.363578 0.149505
0.0419426 0.994638 0.89545 0.65836 0.390982 0.462052 0.740027 0.974471 0.234875 0.374738
0.820769 0.119097 0.884086 0.648969 0.303171 0.797565 0.223649 0.576949 0.751251 0.130427
0.618224 0.113461 0.25556 0.614178 0.901178 0.0406404 0.732617 0.808629 0.0322353 0.515182
0.435284 0.125175 0.393207 0.580732 0.663967 0.636366 0.402737 0.59888 0.797121 0.979881
10 10
-0.02 0.16 -0.46 -1.19 2.11 -0.26 0.52 -0.41 0.31 -0.34
0.16 0.46 0.07 -0.42 1.01 0.29 0.88 -1.16 -0.53 -0.52
0.61 -1.81 -2.38 -2.34 2.99 -0.38 1.85 0.29 -0.22 1.62
-0.09 1.24 0.82 3.33 -3.39 -0.29 -2.40 1.12 0.40 -0.99
0.28 -0.39 0.16 0.03 -0.38 0.95 -0.31 -0.18 0.33 -0.05
-1.51 2.00 2.91 3.21 -3.75 0.63 -2.33 0.73 0.23 -1.98
-2.35 2.79 2.24 0.80 -2.43 0.75 -0.80 -0.01 0.93 -1.17
1.51 -2.20 -0.94 -1.00 1.20 -0.77 1.31 0.28 -0.22 0.65
0.32 -0.14 -0.26 -1.47 0.49 0.39 0.87 -0.10 -0.79 1.06
0.37 -0.86 -1.47 -1.09 2.30 -0.80 0.88 -0.88 -0.20 1.70
"""
}
{
name: "<NAME>"
code: """
#include <iostream>
using namespace std;
int const SIZE = 9;
const int SUBSIZE = SIZE/3;
int S[9][9];
bool MR[9][9], MC[9][9], MQ[9][9], SET[9][9];
bool found;
int quad(const int i, const int j) {
return (i/SUBSIZE)*SUBSIZE + j/SUBSIZE;
}
bool canPutNum(int num, int i, int j) {
return not MC[j][num-1] and not MQ[quad(i, j)][num-1]
and not MR[i][num-1];
}
void putNum(int num, int i, int j) {
S[i][j] = num;
MR[i][num-1] = MC[j][num-1] = MQ[quad(i, j)][num-1] = true;
}
void removeNum(int num, int i, int j) {
MR[i][num-1] = MC[j][num-1] = MQ[quad(i, j)][num-1] = false;
}
void backtrack(int i, int j) {
if (not found) {
if (i < SIZE) {
if (not SET[i][j]) {
for (int num = 1; num <= SIZE; ++num) {
if (canPutNum(num, i, j)) {
putNum(num, i, j);
if (j + 1 == SIZE) backtrack(i + 1, 0);
else backtrack(i, j + 1);
if (not found) removeNum(num, i, j);
} } }
else {
if (j + 1 == SIZE) backtrack(i + 1, 0);
else backtrack(i, j + 1);
} }
else found = true;
} }
void initialize() {
found = false;
for (int i = 0; i < SIZE; ++i)
for (int j = 0; j < SIZE; ++j)
*(*(MR + i) + j) = (*(MC + i))[j] = MQ[i][j] = SET[i][j] = false;
}
void read() {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
char c; cin >> c;
if (c != '.') {
putNum(c - '0', i, j);
SET[i][j] = true;
} } } }
void print() {
cout << endl;
for (int i = 0; i < SIZE; ++i) {
cout << S[i][0];
for (int j = 1; j < SIZE; ++j) cout << ' ' << S[i][j];
cout << endl;
} }
void solve() {
backtrack(0, 0);
}
int main() {
int n; cin >> n; cout << n << endl;
for (int i = 0; i < n; ++i) {
initialize();
read();
solve();
print();
} }
"""
input: """
2
. . . . . 2 3 . 7
. . . . . 6 4 5 .
1 . . 9 3 . . . .
. . . . 6 1 8 . .
. 4 8 . . . 5 6 .
. . 6 4 2 . . . .
. . . . 7 5 . . 8
. 2 9 1 . . . . .
4 . 5 6 . . . . .
7 . . . . 2 . . 4
1 . . . . . 7 6 .
2 . . . 8 . 3 . 9
. . . 6 5 . 8 2 .
. . . . 2 . . . .
. 2 6 . 9 1 . . .
8 . 7 . 1 . . . 5
. 5 9 . . . . . 3
3 . . 5 . . . . 8
"""
}
{
name: "GCD"
code: """
// P67723_en: Greatest common divisor
// Pre: two strictly positive natural numbers a and b
// Post: the greatest common divisor of a and b
#include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int a0 = a; //we need to keep the value of the original a and b
int b0 = b;
while ( b != 0) {
int r = a%b; //remainder
a = b;
b = r;
}
cout << "The gcd of " << a0 << " and " << b0 << " is " << a << "." << endl;
}
"""
input: "12 90"
}
{
name: "<NAME>"
code: """
#include <iostream>
using namespace std;
void hanoi(int n, char from, char to, char aux) {
if (n > 0) {
hanoi(n - 1, from, aux, to);
cout << from << " => " << to << endl;
hanoi(n - 1, aux, to, from);
}
}
int main() {
int ndiscos;
cin >> ndiscos;
hanoi(ndiscos, 'A', 'C', 'B');
}
"""
input: "3"
}
{
name: "<NAME>"
code: """
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 1; i <= x; ++i) {
for (int j = 0; j < x + i - 1; ++j) {
if (j < x - i) cout << ' ';
else cout << '*';
}
cout << endl;
}
for (int i = 1; i < x; ++i) {
for (int j = 0; j < 2*x - i - 1; ++j) {
if (j >= i) cout << '*';
else cout << ' ';
}
cout << endl;
}
}
"""
input: "10"
}
]
STATUS = {
WAITING_INPUT: {
icon: 'input'
tooltip: "Waiting for input"
color: "white"
text: "Waiting for input"
}
RUNNING: {
icon: 'directions_run'
tooltip: "Running"
color: "white"
text: "Running"
}
PAUSED: {
icon: "pause"
tooltip: "Paused"
color: "white"
text: ""
}
COMPILATION_SUCCESSFUL: {
icon: 'done'
color: 'white'
text: 'Compilation successful'
tooltip: "See AST and instructions tabs on the right"
}
COMPILATION_ERROR: {
icon: 'error'
color: '#F48FB1'
text: 'Compilation error'
tooltip: "See the terminal for errors"
}
EXITED: (status) ->
{
icon: if status is 0 then 'done' else 'error'
color: if status is 0 then 'white' else '#F48FB1'
text: "Exited with status <b>#{status}</b>"
tooltip: if status is 0 then "Execution finished correctly" else "Execution finished abnormaly"
}
KILLED: {
icon: "stop"
color: 'white'
text: 'Killed'
tooltip: "You killed the program"
}
}
MainCtrl = ($scope, $state, $window, $mdMedia, $rootScope, $mdToast, $timeout, $sce, $mdDialog) ->
for status, value of STATUS
if value.text?
value.text = $sce.trustAsHtml(value.text)
#####
# SCOPE VARIABLES INITIALIZATION
#####
initialExample = 0
$scope.selectedIndex = 0 # For the tabs
$scope.speed = 0.4;
$scope.astString = ""
$scope.instructionsString = ""
$scope.compilerHelpString = ""
$scope.fixedInput = EXAMPLES[initialExample].input ? ""
$scope.compiled = no
$scope.compileError = no
$scope.running = no
$scope.debugging = no
$scope.runningStatus = no
$scope.variables = {}
$scope.$mdMedia = $mdMedia
$scope.$watch('runningStatus', _.debounce(( (newv, oldv) ->
icon = $('.status i')
times = if newv is oldv then 2 else 3
icon.delay(100).fadeTo(100,0.5).delay(100).fadeTo(100,1) for time in [0...times]
), 50))
#####
# RESPONSIVE
#####
$rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
if toState.name isnt "terminal"
$("#terminal").appendTo(".terminalOuter")
$.terminal.active()?.scroll_to_bottom()
)
$rootScope.$on('$viewContentLoaded', (event, toState, toParams, fromState, fromParams) ->
if $state.current.name is "terminal"
$("#terminal").appendTo("#terminalTab")
$.terminal.active()?.scroll_to_bottom()
)
$scope.$watch((-> $mdMedia('gt-sm')), (big) ->
if big
$state.go('fixed-input')
if $scope.tabs.some((e) -> e.title is 'Terminal')
$scope.tabs.shift()
$("#terminal").appendTo(".terminalOuter")
else unless $scope.tabs.some((e) -> e.title is 'Terminal')
$state.go('terminal')
$scope.tabs.unshift { isTerminal: yes, icon: 'tv', title: 'Terminal', state: 'terminal', showCondition: -> yes }
)
#####
# EDITOR SETUP
#####
editor = ace.edit("editor")
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/c_cpp")
editor.$blockScrolling = Infinity
editor.setValue(EXAMPLES[initialExample].code, -1)
aceRange = ace.require('ace/range').Range;
getBreakpoints = -> Object.keys(editor.session.getBreakpoints(undefined, 0)).map((x) -> parseInt(x) + 1)
editor.on("guttermousedown", (e) ->
target = e.domEvent.target
if target.className.indexOf("ace_gutter-cell") == -1
return
if !editor.isFocused()
editor.focus()
if e.clientX > 25 + target.getBoundingClientRect().left
return
{ row } = e.getDocumentPosition()
breakpoints = e.editor.session.getBreakpoints(row, 0)
if row not of breakpoints
e.editor.session.setBreakpoint(row)
#range = new aceRange(row, 0, row, 1);
#markedLines[row] = e.editor.session.addMarker(range, "warning", "fullLine", true);
worker.postMessage({ command: "addBreakpoint", breakpoint: row + 1 })
else
e.editor.session.clearBreakpoint(row)
#editor.getSession().removeMarker markedLines[row]
#delete markedLines[row]
worker.postMessage({ command: "removeBreakpoint", breakpoint: row + 1 })
e.stop()
)
#####
# TERMINAL SETUP
#####
jQuery ($) ->
$('#terminal').terminal ((command) ->
if command in ["compile", "c"]
$scope.compile(yes)
else if command in ["run", "r"]
$scope.run(yes)
else if command in ["debug", "d"]
$scope.debug(yes)
else
this.error("Invalid command #{command}. Type 'compile', 'run' or 'debug'")
),
greetings: "This is the C-- terminal. Type 'compile', 'run' or 'debug'"
name: 'js_demo'
height: 200
prompt: '> '
completion: ['compile', 'run', 'debug', 'c', 'r', 'd']
scrollOnEcho: yes
keymap: {
"CTRL+D": -> worker.postMessage({ command: "endOfInput" })
"CTRL+Z": ->
$scope.kill()
$scope.$apply()
"CTRL+C": ->
$scope.kill()
$scope.$apply()
}
#####
# WORKER SETUP
#####
worker = null
output = null
currentLine = null
listen = {}
terminal = -> $.terminal.active()
echo = (msg) ->
terminal().echo(if msg.length is 0 then "\0" else msg)
buffer = (fn) ->
timeout = null
buff = ""
({ string }) ->
buff += string
clearTimeout(timeout)
timeout = setTimeout((-> fn({ string: buff }); buff = ""))
listen.output = buffer(({ string }) ->
term = terminal()
lines = string.split('\n')
if lines.length is 1
term.set_prompt(output = term.get_prompt() + lines[0])
else
echo((output ? "") + lines[0])
for line in lines[1...-1]
echo(line)
term.set_prompt(output = lines[lines.length - 1]))
listen.compilationError = ({ message, description }) ->
$scope.compileError = yes
$scope.compiled = yes
$scope.compilerHelpString = description ? ""
$scope.runningStatus = STATUS.COMPILATION_ERROR
if $scope.compilerHelpString.length > 0
$state.go('compilation-help')
$timeout(->$scope.selectedIndex = 1)
term = terminal()
term.error message
listen.startRunning = ->
#console.log "startRunning"
$scope.running = yes
$scope.runningStatus = STATUS.RUNNING
unless $mdMedia('gt-sm')
$timeout((->$state.go('terminal'); $scope.selectedIndex = 0))
$.terminal.active().push((command) ->
output = null
this.set_prompt("")
worker.postMessage({ command: "input", input: command })
,
name: 'runEnvironment'
prompt: ''
)
listen.startDebugging = ->
$scope.debugging = yes
listen.startRunning()
listen.currentLine = ({ line }) ->
editor.getSession().removeMarker currentLine if currentLine?
row = line - 1
range = new aceRange(row, 0, row, 1);
currentLine = editor.getSession().addMarker(range, "current-line", "fullLine", true)
listen.compilationSuccessful = ({ ast, instructions, goingToRun }) ->
if $scope.compileError
$state.go('instructions')
$timeout(-> $scope.selectedIndex = 2)
$scope.compiled = yes
$scope.compileError = no
$scope.astString = ast
$scope.instructionsString = instructions
unless goingToRun
$scope.runningStatus = STATUS.COMPILATION_SUCCESSFUL
listen.executionFinish = ({ status }) ->
# TODO: Show status somehow
if $scope.debugging and $state.current.name is "variables"
$state.go('fixed-input')
$scope.selectedIndex = 0
# Output can arrive after executionFinish signal, so we must wait for the call stack to clear
setTimeout(->
term = terminal()
term.pop()
term.set_prompt((if output? then output else "") + "> ")
)
$scope.running = $scope.debugging = no
$scope.waitingForInput = no
if status?
$scope.runningStatus = STATUS.EXITED(status)
$scope.runningStatus.text = $sce.trustAsHtml($scope.runningStatus.text)
else
$scope.runningStatus = STATUS.KILLED
output = null
editor.getSession().removeMarker currentLine if currentLine?
currentLine = null
listen.resumeRunning = ->
#console.log "resume"
if $scope.debugging
$timeout((-> # Prevents continuous flashing when using step over/step
if $scope.runningStatus is STATUS.RUNNING
$state.go('fixed-input'); $scope.selectedIndex = 0
), 100)
$scope.runningStatus = STATUS.RUNNING
listen.waitingForInput = ->
$scope.runningStatus = STATUS.WAITING_INPUT
$.terminal.active().focus()
listen.paused = ({ variables }) ->
$scope.variables = variables
$scope.runningStatus = STATUS.PAUSED
$state.go('variables')
$timeout(->$scope.selectedIndex = 3)
listen.variableSet = ({ id, value, repr }) ->
$scope.variables[id].value = value
$scope.variables[id].repr = repr
$scope.variables[id].edit = no
listen.invalidVariableValue = ({ id, value }) ->
showToast "Invalid value '#{value}' for variable with type #{$scope.variables[id].type}"
do resetWorker = ->
worker = new Worker("/worker.js")
worker.onmessage = (e) ->
{ data: { event, data }} = e
unless listen[event]?
throw "Invalid event #{event}"
else
listen[event](data)
$scope.$apply()
for breakpoint in getBreakpoints()
worker.postMessage({ command: "addBreakpoint", breakpoint })
#####
# ACTIONS
#####
$scope.selectExample = (example) ->
editor.setValue(example.code, -1)
$scope.fixedInput = example.input ? ""
$scope.debug = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "debug")
output = null
worker.postMessage({ command: "debug", code: editor.getValue(), input: $scope.fixedInput })
null
$scope.run = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "run")
output = null
worker.postMessage({ command: "run", code: editor.getValue(), input: $scope.fixedInput })
null
$scope.continue = -> worker.postMessage({ command: "continue" })
$scope.kill = ->
listen.executionFinish({ status: null })
worker.terminate()
resetWorker()
$scope.compile = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "compile")
worker.postMessage({ command: "compile", code: editor.getValue() })
$scope.stepOver = -> worker.postMessage({ command: "stepOver" })
$scope.stepInto = -> worker.postMessage({ command: "stepInto" })
$scope.stepOut = -> worker.postMessage({ command: "stepOut" })
$scope.stepInstruction = -> worker.postMessage({ command: "stepInstruction" })
showToast = (text) ->
toast = $mdToast.simple()
.textContent(text)
.position('top right')
.hideDelay(3000);
$mdToast.show toast
$scope.tryToEdit = (variable, name) ->
if variable.const
showToast "Cannot set value for #{name}: it's declared const"
else if variable.isArray
showToast "Changing array values is not supported yet"
else
variable.edit = yes
variable.editValue =
if variable.isChar # Null char values can mess up (no way to tell whether there's something)
''
else
variable.value
$scope.confirmVariableEdit = (variable, name) ->
{ editValue: value } = variable
worker.postMessage({ command: "setVariable", id: name, value })
$scope.cancelVariableEdit = (variable) ->
variable.editValue = null
variable.edit = no
$scope.showHelp = ->
$scope.showAbout = (ev) ->
$mdDialog.show({
templateUrl: 'client/about/about.html'
controller: ['$scope', '$mdDialog', ($scope, $mdDialog) -> $scope.close = -> $mdDialog.cancel()]
parent: angular.element(document.body)
targetEvent: ev
clickOutsideToClose: yes
}
)
#####
# CONTENT
#####
$scope.examples = EXAMPLES
$scope.tabs = [
{
icon: 'input'
title: 'Fixed input'
state: 'fixed-input'
showCondition: -> yes
}
#{
# icon: 'bug_report'
# title: 'Variables'
# state: 'variables'
# showCondition: -> $scope.debugging
#}
{
icon: 'build'
title: 'Compilation Help'
state: 'compilation-help'
showCondition: -> $scope.compiled and $scope.compileError and $scope.compilerHelpString.length > 0
}
{
icon: 'code'
title: 'AST'
state: 'ast'
showCondition: -> $scope.compiled and not $scope.compileError
}
{
icon: 'format_list_numbered'
title: 'Instructions'
state: 'instructions'
showCondition: -> $scope.compiled and not $scope.compileError
}
{
icon: "bug_report"
title: 'Variables'
state: 'variables'
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
]
$scope.buttons = [
{
text: "Compile"
icon: "build"
tooltip: "Compiles the program"
color: '#7986CB'
action: $scope.compile
showCondition: -> not $scope.running
}
{
text: "Run"
icon: "play_arrow"
tooltip: "Compiles and runs the program"
color: '#009688'
action: $scope.run
showCondition: -> not $scope.running
}
{
text: "Kill"
icon: "stop"
tooltip: "Kills the program"
color: "#EF5350"
action: $scope.kill
showCondition: -> $scope.running
}
{
text: "Debug"
icon: "bug_report"
tooltip: "Compiles and starts debugging"
color: '#EF6C00'
action: $scope.debug
showCondition: -> not $scope.running
}
{
text: "Continue"
icon: "play_arrow"
tooltip: "Continues debugging the program"
color: '#009688'
action: $scope.continue
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step over"
icon: "vertical_align_bottom"
tooltip: "Runs the program until the next line of code"
color: '#689F38'
action: $scope.stepOver
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step into"
icon: "subdirectory_arrow_right"
tooltip: "Enters the function call or steps over"
color: '#558B2F'
action: $scope.stepInto
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step out"
icon: "reply"
tooltip: "Runs the program until the current function returns"
color: '#33691E'
action: $scope.stepOut
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step"
icon: "keyboard_arrow_down"
tooltip: "Runs the program until the next instruction"
color: "#827717"
action: $scope.stepInstruction
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
]
app.controller('MainCtrl', ['$scope', '$state', '$window', '$mdMedia', '$rootScope', '$mdToast', '$timeout', '$sce', '$mdDialog', MainCtrl])
| true | import '/client/app.ng.coffee'
EXAMPLES = [
{
name: "Default"
code: """
#include <iostream>
using namespace std;
int main() {
}
"""
}
{
name: "MatrixMul"
code: """
#include <iostream>
using namespace std;
double** read_matrix(int* n, int* m) {
double **M;
cout << "Enter the first dimension: ";
bool correct = cin >> *n;
while (not correct) { cout << "Invalid first dimension" << endl; correct = cin >> *n; }
cout << endl;
cout << "Enter the second dimension: ";
correct = cin >> *m;
while (not correct) { cout << "Invalid second dimension" << endl; correct = cin >> *m; }
cout << endl;
M = new double* [*n];
for (int i = 0; i < *n; ++i) M[i] = new double[*m];
cout << "Reserved " << (*n)*(*m) << " elements" << endl;
cout << "Enter the matrix:" << endl;
for (int i = 0; i < *n; ++i)
for (int j = 0; j < *m; ++j)
cin >> M[i][j];
return M;
}
void write_matrix(double **M, int n, int m) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cout << M[i][j] << ' ';
}
cout << endl;
}
}
double** matrix_mul(double **M1, int n1, int m1, double **M2, int n2, int m2) {
if (m1 != n2) {
cout << "Cannot multiply matrices with sizes " << n1 << "x" << m1 << " and " << n2 << "x" << m2 << endl;
return nullptr;
}
else {
double** R = new double*[n1];
for (int i = 0; i < n1; ++i) R[i] = new double[m2];
for (int i = 0; i < n1; ++i)
for (int j = 0; j < m2; ++j)
for (int k = 0; k < n2; ++k)
R[i][j] += M1[i][k]*M2[k][j];
return R;
}
}
void free_matrix(double **M, int n) {
for (int i = 0; i < n; ++i) delete[] M[i];
delete[] M;
}
int main() {
int n1, m1, n2, m2;
double **M1, **M2;
cout << "First matrix:" << endl;
M1 = read_matrix(&n1, &m1);
cout << "Second matrix:" << endl;
M2 = read_matrix(&n2, &m2);
double **R = matrix_mul(M1, n1, m1, M2, n2, m2);
if (R != nullptr) {
write_matrix(R, n1, m2);
free_matrix(R, n1);
}
free_matrix(M1, n1);
free_matrix(M2, n2);
}
"""
input: """
10 10
0.985972 0.41644 0.00917712 0.960001 0.738504 0.178032 0.279277 0.871901 0.937947 0.368076
0.796421 0.501716 0.352193 0.914611 0.305051 0.170487 0.426052 0.388529 0.821443 0.341463
0.866829 0.0475431 0.0520645 0.225011 0.521641 0.962696 0.27995 0.955066 0.789707 0.732368
0.316189 0.877086 0.972151 0.753573 0.687137 0.96446 0.337021 0.68242 0.217289 0.813299
0.949761 0.314933 0.604641 0.42739 0.543298 0.947111 0.0547473 0.432424 0.499621 0.630333
0.230609 0.486681 0.739983 0.352329 0.974505 0.524403 0.107063 0.0682698 0.363578 0.149505
0.0419426 0.994638 0.89545 0.65836 0.390982 0.462052 0.740027 0.974471 0.234875 0.374738
0.820769 0.119097 0.884086 0.648969 0.303171 0.797565 0.223649 0.576949 0.751251 0.130427
0.618224 0.113461 0.25556 0.614178 0.901178 0.0406404 0.732617 0.808629 0.0322353 0.515182
0.435284 0.125175 0.393207 0.580732 0.663967 0.636366 0.402737 0.59888 0.797121 0.979881
10 10
-0.02 0.16 -0.46 -1.19 2.11 -0.26 0.52 -0.41 0.31 -0.34
0.16 0.46 0.07 -0.42 1.01 0.29 0.88 -1.16 -0.53 -0.52
0.61 -1.81 -2.38 -2.34 2.99 -0.38 1.85 0.29 -0.22 1.62
-0.09 1.24 0.82 3.33 -3.39 -0.29 -2.40 1.12 0.40 -0.99
0.28 -0.39 0.16 0.03 -0.38 0.95 -0.31 -0.18 0.33 -0.05
-1.51 2.00 2.91 3.21 -3.75 0.63 -2.33 0.73 0.23 -1.98
-2.35 2.79 2.24 0.80 -2.43 0.75 -0.80 -0.01 0.93 -1.17
1.51 -2.20 -0.94 -1.00 1.20 -0.77 1.31 0.28 -0.22 0.65
0.32 -0.14 -0.26 -1.47 0.49 0.39 0.87 -0.10 -0.79 1.06
0.37 -0.86 -1.47 -1.09 2.30 -0.80 0.88 -0.88 -0.20 1.70
"""
}
{
name: "PI:NAME:<NAME>END_PI"
code: """
#include <iostream>
using namespace std;
int const SIZE = 9;
const int SUBSIZE = SIZE/3;
int S[9][9];
bool MR[9][9], MC[9][9], MQ[9][9], SET[9][9];
bool found;
int quad(const int i, const int j) {
return (i/SUBSIZE)*SUBSIZE + j/SUBSIZE;
}
bool canPutNum(int num, int i, int j) {
return not MC[j][num-1] and not MQ[quad(i, j)][num-1]
and not MR[i][num-1];
}
void putNum(int num, int i, int j) {
S[i][j] = num;
MR[i][num-1] = MC[j][num-1] = MQ[quad(i, j)][num-1] = true;
}
void removeNum(int num, int i, int j) {
MR[i][num-1] = MC[j][num-1] = MQ[quad(i, j)][num-1] = false;
}
void backtrack(int i, int j) {
if (not found) {
if (i < SIZE) {
if (not SET[i][j]) {
for (int num = 1; num <= SIZE; ++num) {
if (canPutNum(num, i, j)) {
putNum(num, i, j);
if (j + 1 == SIZE) backtrack(i + 1, 0);
else backtrack(i, j + 1);
if (not found) removeNum(num, i, j);
} } }
else {
if (j + 1 == SIZE) backtrack(i + 1, 0);
else backtrack(i, j + 1);
} }
else found = true;
} }
void initialize() {
found = false;
for (int i = 0; i < SIZE; ++i)
for (int j = 0; j < SIZE; ++j)
*(*(MR + i) + j) = (*(MC + i))[j] = MQ[i][j] = SET[i][j] = false;
}
void read() {
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
char c; cin >> c;
if (c != '.') {
putNum(c - '0', i, j);
SET[i][j] = true;
} } } }
void print() {
cout << endl;
for (int i = 0; i < SIZE; ++i) {
cout << S[i][0];
for (int j = 1; j < SIZE; ++j) cout << ' ' << S[i][j];
cout << endl;
} }
void solve() {
backtrack(0, 0);
}
int main() {
int n; cin >> n; cout << n << endl;
for (int i = 0; i < n; ++i) {
initialize();
read();
solve();
print();
} }
"""
input: """
2
. . . . . 2 3 . 7
. . . . . 6 4 5 .
1 . . 9 3 . . . .
. . . . 6 1 8 . .
. 4 8 . . . 5 6 .
. . 6 4 2 . . . .
. . . . 7 5 . . 8
. 2 9 1 . . . . .
4 . 5 6 . . . . .
7 . . . . 2 . . 4
1 . . . . . 7 6 .
2 . . . 8 . 3 . 9
. . . 6 5 . 8 2 .
. . . . 2 . . . .
. 2 6 . 9 1 . . .
8 . 7 . 1 . . . 5
. 5 9 . . . . . 3
3 . . 5 . . . . 8
"""
}
{
name: "GCD"
code: """
// P67723_en: Greatest common divisor
// Pre: two strictly positive natural numbers a and b
// Post: the greatest common divisor of a and b
#include<iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int a0 = a; //we need to keep the value of the original a and b
int b0 = b;
while ( b != 0) {
int r = a%b; //remainder
a = b;
b = r;
}
cout << "The gcd of " << a0 << " and " << b0 << " is " << a << "." << endl;
}
"""
input: "12 90"
}
{
name: "PI:NAME:<NAME>END_PI"
code: """
#include <iostream>
using namespace std;
void hanoi(int n, char from, char to, char aux) {
if (n > 0) {
hanoi(n - 1, from, aux, to);
cout << from << " => " << to << endl;
hanoi(n - 1, aux, to, from);
}
}
int main() {
int ndiscos;
cin >> ndiscos;
hanoi(ndiscos, 'A', 'C', 'B');
}
"""
input: "3"
}
{
name: "PI:NAME:<NAME>END_PI"
code: """
#include <iostream>
using namespace std;
int main() {
int x;
cin >> x;
for (int i = 1; i <= x; ++i) {
for (int j = 0; j < x + i - 1; ++j) {
if (j < x - i) cout << ' ';
else cout << '*';
}
cout << endl;
}
for (int i = 1; i < x; ++i) {
for (int j = 0; j < 2*x - i - 1; ++j) {
if (j >= i) cout << '*';
else cout << ' ';
}
cout << endl;
}
}
"""
input: "10"
}
]
STATUS = {
WAITING_INPUT: {
icon: 'input'
tooltip: "Waiting for input"
color: "white"
text: "Waiting for input"
}
RUNNING: {
icon: 'directions_run'
tooltip: "Running"
color: "white"
text: "Running"
}
PAUSED: {
icon: "pause"
tooltip: "Paused"
color: "white"
text: ""
}
COMPILATION_SUCCESSFUL: {
icon: 'done'
color: 'white'
text: 'Compilation successful'
tooltip: "See AST and instructions tabs on the right"
}
COMPILATION_ERROR: {
icon: 'error'
color: '#F48FB1'
text: 'Compilation error'
tooltip: "See the terminal for errors"
}
EXITED: (status) ->
{
icon: if status is 0 then 'done' else 'error'
color: if status is 0 then 'white' else '#F48FB1'
text: "Exited with status <b>#{status}</b>"
tooltip: if status is 0 then "Execution finished correctly" else "Execution finished abnormaly"
}
KILLED: {
icon: "stop"
color: 'white'
text: 'Killed'
tooltip: "You killed the program"
}
}
MainCtrl = ($scope, $state, $window, $mdMedia, $rootScope, $mdToast, $timeout, $sce, $mdDialog) ->
for status, value of STATUS
if value.text?
value.text = $sce.trustAsHtml(value.text)
#####
# SCOPE VARIABLES INITIALIZATION
#####
initialExample = 0
$scope.selectedIndex = 0 # For the tabs
$scope.speed = 0.4;
$scope.astString = ""
$scope.instructionsString = ""
$scope.compilerHelpString = ""
$scope.fixedInput = EXAMPLES[initialExample].input ? ""
$scope.compiled = no
$scope.compileError = no
$scope.running = no
$scope.debugging = no
$scope.runningStatus = no
$scope.variables = {}
$scope.$mdMedia = $mdMedia
$scope.$watch('runningStatus', _.debounce(( (newv, oldv) ->
icon = $('.status i')
times = if newv is oldv then 2 else 3
icon.delay(100).fadeTo(100,0.5).delay(100).fadeTo(100,1) for time in [0...times]
), 50))
#####
# RESPONSIVE
#####
$rootScope.$on('$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
if toState.name isnt "terminal"
$("#terminal").appendTo(".terminalOuter")
$.terminal.active()?.scroll_to_bottom()
)
$rootScope.$on('$viewContentLoaded', (event, toState, toParams, fromState, fromParams) ->
if $state.current.name is "terminal"
$("#terminal").appendTo("#terminalTab")
$.terminal.active()?.scroll_to_bottom()
)
$scope.$watch((-> $mdMedia('gt-sm')), (big) ->
if big
$state.go('fixed-input')
if $scope.tabs.some((e) -> e.title is 'Terminal')
$scope.tabs.shift()
$("#terminal").appendTo(".terminalOuter")
else unless $scope.tabs.some((e) -> e.title is 'Terminal')
$state.go('terminal')
$scope.tabs.unshift { isTerminal: yes, icon: 'tv', title: 'Terminal', state: 'terminal', showCondition: -> yes }
)
#####
# EDITOR SETUP
#####
editor = ace.edit("editor")
editor.setTheme("ace/theme/twilight");
editor.getSession().setMode("ace/mode/c_cpp")
editor.$blockScrolling = Infinity
editor.setValue(EXAMPLES[initialExample].code, -1)
aceRange = ace.require('ace/range').Range;
getBreakpoints = -> Object.keys(editor.session.getBreakpoints(undefined, 0)).map((x) -> parseInt(x) + 1)
editor.on("guttermousedown", (e) ->
target = e.domEvent.target
if target.className.indexOf("ace_gutter-cell") == -1
return
if !editor.isFocused()
editor.focus()
if e.clientX > 25 + target.getBoundingClientRect().left
return
{ row } = e.getDocumentPosition()
breakpoints = e.editor.session.getBreakpoints(row, 0)
if row not of breakpoints
e.editor.session.setBreakpoint(row)
#range = new aceRange(row, 0, row, 1);
#markedLines[row] = e.editor.session.addMarker(range, "warning", "fullLine", true);
worker.postMessage({ command: "addBreakpoint", breakpoint: row + 1 })
else
e.editor.session.clearBreakpoint(row)
#editor.getSession().removeMarker markedLines[row]
#delete markedLines[row]
worker.postMessage({ command: "removeBreakpoint", breakpoint: row + 1 })
e.stop()
)
#####
# TERMINAL SETUP
#####
jQuery ($) ->
$('#terminal').terminal ((command) ->
if command in ["compile", "c"]
$scope.compile(yes)
else if command in ["run", "r"]
$scope.run(yes)
else if command in ["debug", "d"]
$scope.debug(yes)
else
this.error("Invalid command #{command}. Type 'compile', 'run' or 'debug'")
),
greetings: "This is the C-- terminal. Type 'compile', 'run' or 'debug'"
name: 'js_demo'
height: 200
prompt: '> '
completion: ['compile', 'run', 'debug', 'c', 'r', 'd']
scrollOnEcho: yes
keymap: {
"CTRL+D": -> worker.postMessage({ command: "endOfInput" })
"CTRL+Z": ->
$scope.kill()
$scope.$apply()
"CTRL+C": ->
$scope.kill()
$scope.$apply()
}
#####
# WORKER SETUP
#####
worker = null
output = null
currentLine = null
listen = {}
terminal = -> $.terminal.active()
echo = (msg) ->
terminal().echo(if msg.length is 0 then "\0" else msg)
buffer = (fn) ->
timeout = null
buff = ""
({ string }) ->
buff += string
clearTimeout(timeout)
timeout = setTimeout((-> fn({ string: buff }); buff = ""))
listen.output = buffer(({ string }) ->
term = terminal()
lines = string.split('\n')
if lines.length is 1
term.set_prompt(output = term.get_prompt() + lines[0])
else
echo((output ? "") + lines[0])
for line in lines[1...-1]
echo(line)
term.set_prompt(output = lines[lines.length - 1]))
listen.compilationError = ({ message, description }) ->
$scope.compileError = yes
$scope.compiled = yes
$scope.compilerHelpString = description ? ""
$scope.runningStatus = STATUS.COMPILATION_ERROR
if $scope.compilerHelpString.length > 0
$state.go('compilation-help')
$timeout(->$scope.selectedIndex = 1)
term = terminal()
term.error message
listen.startRunning = ->
#console.log "startRunning"
$scope.running = yes
$scope.runningStatus = STATUS.RUNNING
unless $mdMedia('gt-sm')
$timeout((->$state.go('terminal'); $scope.selectedIndex = 0))
$.terminal.active().push((command) ->
output = null
this.set_prompt("")
worker.postMessage({ command: "input", input: command })
,
name: 'runEnvironment'
prompt: ''
)
listen.startDebugging = ->
$scope.debugging = yes
listen.startRunning()
listen.currentLine = ({ line }) ->
editor.getSession().removeMarker currentLine if currentLine?
row = line - 1
range = new aceRange(row, 0, row, 1);
currentLine = editor.getSession().addMarker(range, "current-line", "fullLine", true)
listen.compilationSuccessful = ({ ast, instructions, goingToRun }) ->
if $scope.compileError
$state.go('instructions')
$timeout(-> $scope.selectedIndex = 2)
$scope.compiled = yes
$scope.compileError = no
$scope.astString = ast
$scope.instructionsString = instructions
unless goingToRun
$scope.runningStatus = STATUS.COMPILATION_SUCCESSFUL
listen.executionFinish = ({ status }) ->
# TODO: Show status somehow
if $scope.debugging and $state.current.name is "variables"
$state.go('fixed-input')
$scope.selectedIndex = 0
# Output can arrive after executionFinish signal, so we must wait for the call stack to clear
setTimeout(->
term = terminal()
term.pop()
term.set_prompt((if output? then output else "") + "> ")
)
$scope.running = $scope.debugging = no
$scope.waitingForInput = no
if status?
$scope.runningStatus = STATUS.EXITED(status)
$scope.runningStatus.text = $sce.trustAsHtml($scope.runningStatus.text)
else
$scope.runningStatus = STATUS.KILLED
output = null
editor.getSession().removeMarker currentLine if currentLine?
currentLine = null
listen.resumeRunning = ->
#console.log "resume"
if $scope.debugging
$timeout((-> # Prevents continuous flashing when using step over/step
if $scope.runningStatus is STATUS.RUNNING
$state.go('fixed-input'); $scope.selectedIndex = 0
), 100)
$scope.runningStatus = STATUS.RUNNING
listen.waitingForInput = ->
$scope.runningStatus = STATUS.WAITING_INPUT
$.terminal.active().focus()
listen.paused = ({ variables }) ->
$scope.variables = variables
$scope.runningStatus = STATUS.PAUSED
$state.go('variables')
$timeout(->$scope.selectedIndex = 3)
listen.variableSet = ({ id, value, repr }) ->
$scope.variables[id].value = value
$scope.variables[id].repr = repr
$scope.variables[id].edit = no
listen.invalidVariableValue = ({ id, value }) ->
showToast "Invalid value '#{value}' for variable with type #{$scope.variables[id].type}"
do resetWorker = ->
worker = new Worker("/worker.js")
worker.onmessage = (e) ->
{ data: { event, data }} = e
unless listen[event]?
throw "Invalid event #{event}"
else
listen[event](data)
$scope.$apply()
for breakpoint in getBreakpoints()
worker.postMessage({ command: "addBreakpoint", breakpoint })
#####
# ACTIONS
#####
$scope.selectExample = (example) ->
editor.setValue(example.code, -1)
$scope.fixedInput = example.input ? ""
$scope.debug = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "debug")
output = null
worker.postMessage({ command: "debug", code: editor.getValue(), input: $scope.fixedInput })
null
$scope.run = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "run")
output = null
worker.postMessage({ command: "run", code: editor.getValue(), input: $scope.fixedInput })
null
$scope.continue = -> worker.postMessage({ command: "continue" })
$scope.kill = ->
listen.executionFinish({ status: null })
worker.terminate()
resetWorker()
$scope.compile = (fromTerminal) ->
unless fromTerminal
term = $.terminal.active()
term.echo(term.get_prompt() + "compile")
worker.postMessage({ command: "compile", code: editor.getValue() })
$scope.stepOver = -> worker.postMessage({ command: "stepOver" })
$scope.stepInto = -> worker.postMessage({ command: "stepInto" })
$scope.stepOut = -> worker.postMessage({ command: "stepOut" })
$scope.stepInstruction = -> worker.postMessage({ command: "stepInstruction" })
showToast = (text) ->
toast = $mdToast.simple()
.textContent(text)
.position('top right')
.hideDelay(3000);
$mdToast.show toast
$scope.tryToEdit = (variable, name) ->
if variable.const
showToast "Cannot set value for #{name}: it's declared const"
else if variable.isArray
showToast "Changing array values is not supported yet"
else
variable.edit = yes
variable.editValue =
if variable.isChar # Null char values can mess up (no way to tell whether there's something)
''
else
variable.value
$scope.confirmVariableEdit = (variable, name) ->
{ editValue: value } = variable
worker.postMessage({ command: "setVariable", id: name, value })
$scope.cancelVariableEdit = (variable) ->
variable.editValue = null
variable.edit = no
$scope.showHelp = ->
$scope.showAbout = (ev) ->
$mdDialog.show({
templateUrl: 'client/about/about.html'
controller: ['$scope', '$mdDialog', ($scope, $mdDialog) -> $scope.close = -> $mdDialog.cancel()]
parent: angular.element(document.body)
targetEvent: ev
clickOutsideToClose: yes
}
)
#####
# CONTENT
#####
$scope.examples = EXAMPLES
$scope.tabs = [
{
icon: 'input'
title: 'Fixed input'
state: 'fixed-input'
showCondition: -> yes
}
#{
# icon: 'bug_report'
# title: 'Variables'
# state: 'variables'
# showCondition: -> $scope.debugging
#}
{
icon: 'build'
title: 'Compilation Help'
state: 'compilation-help'
showCondition: -> $scope.compiled and $scope.compileError and $scope.compilerHelpString.length > 0
}
{
icon: 'code'
title: 'AST'
state: 'ast'
showCondition: -> $scope.compiled and not $scope.compileError
}
{
icon: 'format_list_numbered'
title: 'Instructions'
state: 'instructions'
showCondition: -> $scope.compiled and not $scope.compileError
}
{
icon: "bug_report"
title: 'Variables'
state: 'variables'
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
]
$scope.buttons = [
{
text: "Compile"
icon: "build"
tooltip: "Compiles the program"
color: '#7986CB'
action: $scope.compile
showCondition: -> not $scope.running
}
{
text: "Run"
icon: "play_arrow"
tooltip: "Compiles and runs the program"
color: '#009688'
action: $scope.run
showCondition: -> not $scope.running
}
{
text: "Kill"
icon: "stop"
tooltip: "Kills the program"
color: "#EF5350"
action: $scope.kill
showCondition: -> $scope.running
}
{
text: "Debug"
icon: "bug_report"
tooltip: "Compiles and starts debugging"
color: '#EF6C00'
action: $scope.debug
showCondition: -> not $scope.running
}
{
text: "Continue"
icon: "play_arrow"
tooltip: "Continues debugging the program"
color: '#009688'
action: $scope.continue
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step over"
icon: "vertical_align_bottom"
tooltip: "Runs the program until the next line of code"
color: '#689F38'
action: $scope.stepOver
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step into"
icon: "subdirectory_arrow_right"
tooltip: "Enters the function call or steps over"
color: '#558B2F'
action: $scope.stepInto
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step out"
icon: "reply"
tooltip: "Runs the program until the current function returns"
color: '#33691E'
action: $scope.stepOut
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
{
text: "Step"
icon: "keyboard_arrow_down"
tooltip: "Runs the program until the next instruction"
color: "#827717"
action: $scope.stepInstruction
showCondition: -> $scope.debugging and $scope.runningStatus is STATUS.PAUSED
}
]
app.controller('MainCtrl', ['$scope', '$state', '$window', '$mdMedia', '$rootScope', '$mdToast', '$timeout', '$sce', '$mdDialog', MainCtrl])
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9984803795814514,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-zlib-dictionary.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.
# test compression/decompression with dictionary
#
# We'll use clean-new inflate stream each time
# and .reset() old dirty deflate one
#
run = (num) ->
inflate = zlib.createInflate(dictionary: spdyDict)
if num is 2
deflate.reset()
deflate.removeAllListeners "data"
# Put data into deflate stream
deflate.on "data", (chunk) ->
inflate.write chunk
return
# Get data from inflate stream
output = []
inflate.on "data", (chunk) ->
output.push chunk
return
inflate.on "end", ->
called++
assert.equal output.join(""), input
run num + 1 if num < 2
return
deflate.write input
deflate.flush ->
inflate.end()
return
return
common = require("../common.js")
assert = require("assert")
zlib = require("zlib")
path = require("path")
spdyDict = new Buffer([
"optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-"
"languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi"
"f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser"
"-agent10010120020120220320420520630030130230330430530630740040140240340440"
"5406407408409410411412413414415416417500501502503504505accept-rangesageeta"
"glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic"
"ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran"
"sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati"
"oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo"
"ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe"
"pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic"
"ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1"
".1statusversionurl\u0000"
].join(""))
deflate = zlib.createDeflate(dictionary: spdyDict)
input = [
"HTTP/1.1 200 Ok"
"Server: node.js"
"Content-Length: 0"
""
].join("\r\n")
called = 0
run 1
process.on "exit", ->
assert.equal called, 2
return
| 34427 | # 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.
# test compression/decompression with dictionary
#
# We'll use clean-new inflate stream each time
# and .reset() old dirty deflate one
#
run = (num) ->
inflate = zlib.createInflate(dictionary: spdyDict)
if num is 2
deflate.reset()
deflate.removeAllListeners "data"
# Put data into deflate stream
deflate.on "data", (chunk) ->
inflate.write chunk
return
# Get data from inflate stream
output = []
inflate.on "data", (chunk) ->
output.push chunk
return
inflate.on "end", ->
called++
assert.equal output.join(""), input
run num + 1 if num < 2
return
deflate.write input
deflate.flush ->
inflate.end()
return
return
common = require("../common.js")
assert = require("assert")
zlib = require("zlib")
path = require("path")
spdyDict = new Buffer([
"optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-"
"languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi"
"f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser"
"-agent10010120020120220320420520630030130230330430530630740040140240340440"
"5406407408409410411412413414415416417500501502503504505accept-rangesageeta"
"glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic"
"ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran"
"sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati"
"oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo"
"ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe"
"pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic"
"ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1"
".1statusversionurl\u0000"
].join(""))
deflate = zlib.createDeflate(dictionary: spdyDict)
input = [
"HTTP/1.1 200 Ok"
"Server: node.js"
"Content-Length: 0"
""
].join("\r\n")
called = 0
run 1
process.on "exit", ->
assert.equal called, 2
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.
# test compression/decompression with dictionary
#
# We'll use clean-new inflate stream each time
# and .reset() old dirty deflate one
#
run = (num) ->
inflate = zlib.createInflate(dictionary: spdyDict)
if num is 2
deflate.reset()
deflate.removeAllListeners "data"
# Put data into deflate stream
deflate.on "data", (chunk) ->
inflate.write chunk
return
# Get data from inflate stream
output = []
inflate.on "data", (chunk) ->
output.push chunk
return
inflate.on "end", ->
called++
assert.equal output.join(""), input
run num + 1 if num < 2
return
deflate.write input
deflate.flush ->
inflate.end()
return
return
common = require("../common.js")
assert = require("assert")
zlib = require("zlib")
path = require("path")
spdyDict = new Buffer([
"optionsgetheadpostputdeletetraceacceptaccept-charsetaccept-encodingaccept-"
"languageauthorizationexpectfromhostif-modified-sinceif-matchif-none-matchi"
"f-rangeif-unmodifiedsincemax-forwardsproxy-authorizationrangerefererteuser"
"-agent10010120020120220320420520630030130230330430530630740040140240340440"
"5406407408409410411412413414415416417500501502503504505accept-rangesageeta"
"glocationproxy-authenticatepublicretry-afterservervarywarningwww-authentic"
"ateallowcontent-basecontent-encodingcache-controlconnectiondatetrailertran"
"sfer-encodingupgradeviawarningcontent-languagecontent-lengthcontent-locati"
"oncontent-md5content-rangecontent-typeetagexpireslast-modifiedset-cookieMo"
"ndayTuesdayWednesdayThursdayFridaySaturdaySundayJanFebMarAprMayJunJulAugSe"
"pOctNovDecchunkedtext/htmlimage/pngimage/jpgimage/gifapplication/xmlapplic"
"ation/xhtmltext/plainpublicmax-agecharset=iso-8859-1utf-8gzipdeflateHTTP/1"
".1statusversionurl\u0000"
].join(""))
deflate = zlib.createDeflate(dictionary: spdyDict)
input = [
"HTTP/1.1 200 Ok"
"Server: node.js"
"Content-Length: 0"
""
].join("\r\n")
called = 0
run 1
process.on "exit", ->
assert.equal called, 2
return
|
[
{
"context": "is file is part of the ChinesePuzzle package.\n\n(c) Mathieu Ledru\n\nFor the full copyright and license information, ",
"end": 70,
"score": 0.9998593330383301,
"start": 57,
"tag": "NAME",
"value": "Mathieu Ledru"
}
] | Common/Bin/Data/coffee/Game/CardPlay.coffee | matyo91/ChinesePuzzle | 1 | ###
This file is part of the ChinesePuzzle package.
(c) Mathieu Ledru
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
###
cpz.CardPlayColor =
Spade: 1
Club: 2
Heart: 3
Diamond: 4
cpz.CardPlayRank =
Ace: 1
Two: 2
Three: 3
Four: 4
Five: 5
Six: 6
Seven: 7
Eight: 8
Nine: 9
Ten: 10
Jack: 11
Queen: 12
King: 13
cpz.CardPlay = cpz.Card.extend(
_faceSprite: null
_backSprite: null
_color: null
_rank: null
_isLocked: false
_isFaceUp: false
onExit: ->
cc.SafeRelease @_faceSprite
cc.SafeRelease @_backSprite
@_super()
initWithConf: (conf) ->
return false unless @initWithTexture cc.textureNull(), 16
@setConf conf
true
initWithConfAndColorAndRank: (conf, color, rank) ->
return false unless @initWithConf conf
@_color = color
@_rank = rank
true
encode: ->
color: @_color
rank: @_rank
decode: (data) ->
@_color = data['color']
@_rank = data['rank']
@
isNextToCardPlay: (cardPlay) ->
cardPlay and @_color is cardPlay._color and @_rank is cardPlay._rank + 1
setConf: (conf) ->
unless @_faceSprite
@_faceSprite = cc.SpriteBatchNode.create cc.textureNull()
@_faceSprite.retain()
unless @_backSprite
@_backSprite = cc.SpriteBatchNode.create cc.textureNull()
@_backSprite.retain()
conf.getNodeThemePath 'card_' + cpz.CardPlay.matchColor(@_color) + cpz.CardPlay.matchRank(@_rank), @_faceSprite
conf.getNodeThemePath 'cardplaybg', @_backSprite
@setIsFaceUp @getIsFaceUp(), true
getColor: -> @_color
getRank: -> @_rank
getIsLocked: -> @_isLocked
setIsLocked: (@_isLocked) -> @
getIsFaceUp: -> @_isFaceUp
setIsFaceUp: (isFaceUp, force) ->
if @_isFaceUp isnt isFaceUp or force
@_isFaceUp = isFaceUp
if @_isFaceUp
@setSpriteBatchNode(@_faceSprite)
else
@setSpriteBatchNode(@_backSprite)
@
)
cpz.CardPlay.createWithConfAndColorAndRank = (conf, color, rank) ->
obj = new cpz.CardPlay()
return obj if obj and obj.initWithConfAndColorAndRank(conf, color, rank)
null
cpz.CardPlay.decode = (conf, data) ->
obj = new cpz.CardPlay()
obj.decode(data)
return obj if obj and obj.initWithConf(conf)
null
cpz.CardPlay.matchColor = (color) ->
if typeof color is 'string'
switch color
when 'S' then cpz.CardPlayColor.Spade
when 'C' then cpz.CardPlayColor.Club
when 'H' then cpz.CardPlayColor.Heart
when 'D' then cpz.CardPlayColor.Diamond
else cpz.CardPlayColor.Spade
else
switch color
when cpz.CardPlayColor.Spade then 'S'
when cpz.CardPlayColor.Club then 'C'
when cpz.CardPlayColor.Heart then 'H'
when cpz.CardPlayColor.Diamond then 'D'
else 'D'
cpz.CardPlay.matchRank = (rank) ->
if typeof rank is 'string'
switch rank
when 'A' then cpz.CardPlayRank.Ace
when '2' then cpz.CardPlayRank.Two
when '3' then cpz.CardPlayRank.Three
when '4' then cpz.CardPlayRank.Four
when '5' then cpz.CardPlayRank.Five
when '6' then cpz.CardPlayRank.Six
when '7' then cpz.CardPlayRank.Seven
when '8' then cpz.CardPlayRank.Eight
when '9' then cpz.CardPlayRank.Nine
when '10' then cpz.CardPlayRank.Ten
when 'J' then cpz.CardPlayRank.Jack
when 'Q' then cpz.CardPlayRank.Queen
when 'K' then cpz.CardPlayRank.King
else cpz.CardPlayRank.Ace
else
switch rank
when cpz.CardPlayRank.Ace then 'A'
when cpz.CardPlayRank.Two then '2'
when cpz.CardPlayRank.Three then '3'
when cpz.CardPlayRank.Four then '4'
when cpz.CardPlayRank.Five then '5'
when cpz.CardPlayRank.Six then '6'
when cpz.CardPlayRank.Seven then '7'
when cpz.CardPlayRank.Eight then '8'
when cpz.CardPlayRank.Nine then '9'
when cpz.CardPlayRank.Ten then '10'
when cpz.CardPlayRank.Jack then 'J'
when cpz.CardPlayRank.Queen then 'Q'
when cpz.CardPlayRank.King then 'K'
else 'A'
| 106231 | ###
This file is part of the ChinesePuzzle package.
(c) <NAME>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
###
cpz.CardPlayColor =
Spade: 1
Club: 2
Heart: 3
Diamond: 4
cpz.CardPlayRank =
Ace: 1
Two: 2
Three: 3
Four: 4
Five: 5
Six: 6
Seven: 7
Eight: 8
Nine: 9
Ten: 10
Jack: 11
Queen: 12
King: 13
cpz.CardPlay = cpz.Card.extend(
_faceSprite: null
_backSprite: null
_color: null
_rank: null
_isLocked: false
_isFaceUp: false
onExit: ->
cc.SafeRelease @_faceSprite
cc.SafeRelease @_backSprite
@_super()
initWithConf: (conf) ->
return false unless @initWithTexture cc.textureNull(), 16
@setConf conf
true
initWithConfAndColorAndRank: (conf, color, rank) ->
return false unless @initWithConf conf
@_color = color
@_rank = rank
true
encode: ->
color: @_color
rank: @_rank
decode: (data) ->
@_color = data['color']
@_rank = data['rank']
@
isNextToCardPlay: (cardPlay) ->
cardPlay and @_color is cardPlay._color and @_rank is cardPlay._rank + 1
setConf: (conf) ->
unless @_faceSprite
@_faceSprite = cc.SpriteBatchNode.create cc.textureNull()
@_faceSprite.retain()
unless @_backSprite
@_backSprite = cc.SpriteBatchNode.create cc.textureNull()
@_backSprite.retain()
conf.getNodeThemePath 'card_' + cpz.CardPlay.matchColor(@_color) + cpz.CardPlay.matchRank(@_rank), @_faceSprite
conf.getNodeThemePath 'cardplaybg', @_backSprite
@setIsFaceUp @getIsFaceUp(), true
getColor: -> @_color
getRank: -> @_rank
getIsLocked: -> @_isLocked
setIsLocked: (@_isLocked) -> @
getIsFaceUp: -> @_isFaceUp
setIsFaceUp: (isFaceUp, force) ->
if @_isFaceUp isnt isFaceUp or force
@_isFaceUp = isFaceUp
if @_isFaceUp
@setSpriteBatchNode(@_faceSprite)
else
@setSpriteBatchNode(@_backSprite)
@
)
cpz.CardPlay.createWithConfAndColorAndRank = (conf, color, rank) ->
obj = new cpz.CardPlay()
return obj if obj and obj.initWithConfAndColorAndRank(conf, color, rank)
null
cpz.CardPlay.decode = (conf, data) ->
obj = new cpz.CardPlay()
obj.decode(data)
return obj if obj and obj.initWithConf(conf)
null
cpz.CardPlay.matchColor = (color) ->
if typeof color is 'string'
switch color
when 'S' then cpz.CardPlayColor.Spade
when 'C' then cpz.CardPlayColor.Club
when 'H' then cpz.CardPlayColor.Heart
when 'D' then cpz.CardPlayColor.Diamond
else cpz.CardPlayColor.Spade
else
switch color
when cpz.CardPlayColor.Spade then 'S'
when cpz.CardPlayColor.Club then 'C'
when cpz.CardPlayColor.Heart then 'H'
when cpz.CardPlayColor.Diamond then 'D'
else 'D'
cpz.CardPlay.matchRank = (rank) ->
if typeof rank is 'string'
switch rank
when 'A' then cpz.CardPlayRank.Ace
when '2' then cpz.CardPlayRank.Two
when '3' then cpz.CardPlayRank.Three
when '4' then cpz.CardPlayRank.Four
when '5' then cpz.CardPlayRank.Five
when '6' then cpz.CardPlayRank.Six
when '7' then cpz.CardPlayRank.Seven
when '8' then cpz.CardPlayRank.Eight
when '9' then cpz.CardPlayRank.Nine
when '10' then cpz.CardPlayRank.Ten
when 'J' then cpz.CardPlayRank.Jack
when 'Q' then cpz.CardPlayRank.Queen
when 'K' then cpz.CardPlayRank.King
else cpz.CardPlayRank.Ace
else
switch rank
when cpz.CardPlayRank.Ace then 'A'
when cpz.CardPlayRank.Two then '2'
when cpz.CardPlayRank.Three then '3'
when cpz.CardPlayRank.Four then '4'
when cpz.CardPlayRank.Five then '5'
when cpz.CardPlayRank.Six then '6'
when cpz.CardPlayRank.Seven then '7'
when cpz.CardPlayRank.Eight then '8'
when cpz.CardPlayRank.Nine then '9'
when cpz.CardPlayRank.Ten then '10'
when cpz.CardPlayRank.Jack then 'J'
when cpz.CardPlayRank.Queen then 'Q'
when cpz.CardPlayRank.King then 'K'
else 'A'
| true | ###
This file is part of the ChinesePuzzle package.
(c) PI:NAME:<NAME>END_PI
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
###
cpz.CardPlayColor =
Spade: 1
Club: 2
Heart: 3
Diamond: 4
cpz.CardPlayRank =
Ace: 1
Two: 2
Three: 3
Four: 4
Five: 5
Six: 6
Seven: 7
Eight: 8
Nine: 9
Ten: 10
Jack: 11
Queen: 12
King: 13
cpz.CardPlay = cpz.Card.extend(
_faceSprite: null
_backSprite: null
_color: null
_rank: null
_isLocked: false
_isFaceUp: false
onExit: ->
cc.SafeRelease @_faceSprite
cc.SafeRelease @_backSprite
@_super()
initWithConf: (conf) ->
return false unless @initWithTexture cc.textureNull(), 16
@setConf conf
true
initWithConfAndColorAndRank: (conf, color, rank) ->
return false unless @initWithConf conf
@_color = color
@_rank = rank
true
encode: ->
color: @_color
rank: @_rank
decode: (data) ->
@_color = data['color']
@_rank = data['rank']
@
isNextToCardPlay: (cardPlay) ->
cardPlay and @_color is cardPlay._color and @_rank is cardPlay._rank + 1
setConf: (conf) ->
unless @_faceSprite
@_faceSprite = cc.SpriteBatchNode.create cc.textureNull()
@_faceSprite.retain()
unless @_backSprite
@_backSprite = cc.SpriteBatchNode.create cc.textureNull()
@_backSprite.retain()
conf.getNodeThemePath 'card_' + cpz.CardPlay.matchColor(@_color) + cpz.CardPlay.matchRank(@_rank), @_faceSprite
conf.getNodeThemePath 'cardplaybg', @_backSprite
@setIsFaceUp @getIsFaceUp(), true
getColor: -> @_color
getRank: -> @_rank
getIsLocked: -> @_isLocked
setIsLocked: (@_isLocked) -> @
getIsFaceUp: -> @_isFaceUp
setIsFaceUp: (isFaceUp, force) ->
if @_isFaceUp isnt isFaceUp or force
@_isFaceUp = isFaceUp
if @_isFaceUp
@setSpriteBatchNode(@_faceSprite)
else
@setSpriteBatchNode(@_backSprite)
@
)
cpz.CardPlay.createWithConfAndColorAndRank = (conf, color, rank) ->
obj = new cpz.CardPlay()
return obj if obj and obj.initWithConfAndColorAndRank(conf, color, rank)
null
cpz.CardPlay.decode = (conf, data) ->
obj = new cpz.CardPlay()
obj.decode(data)
return obj if obj and obj.initWithConf(conf)
null
cpz.CardPlay.matchColor = (color) ->
if typeof color is 'string'
switch color
when 'S' then cpz.CardPlayColor.Spade
when 'C' then cpz.CardPlayColor.Club
when 'H' then cpz.CardPlayColor.Heart
when 'D' then cpz.CardPlayColor.Diamond
else cpz.CardPlayColor.Spade
else
switch color
when cpz.CardPlayColor.Spade then 'S'
when cpz.CardPlayColor.Club then 'C'
when cpz.CardPlayColor.Heart then 'H'
when cpz.CardPlayColor.Diamond then 'D'
else 'D'
cpz.CardPlay.matchRank = (rank) ->
if typeof rank is 'string'
switch rank
when 'A' then cpz.CardPlayRank.Ace
when '2' then cpz.CardPlayRank.Two
when '3' then cpz.CardPlayRank.Three
when '4' then cpz.CardPlayRank.Four
when '5' then cpz.CardPlayRank.Five
when '6' then cpz.CardPlayRank.Six
when '7' then cpz.CardPlayRank.Seven
when '8' then cpz.CardPlayRank.Eight
when '9' then cpz.CardPlayRank.Nine
when '10' then cpz.CardPlayRank.Ten
when 'J' then cpz.CardPlayRank.Jack
when 'Q' then cpz.CardPlayRank.Queen
when 'K' then cpz.CardPlayRank.King
else cpz.CardPlayRank.Ace
else
switch rank
when cpz.CardPlayRank.Ace then 'A'
when cpz.CardPlayRank.Two then '2'
when cpz.CardPlayRank.Three then '3'
when cpz.CardPlayRank.Four then '4'
when cpz.CardPlayRank.Five then '5'
when cpz.CardPlayRank.Six then '6'
when cpz.CardPlayRank.Seven then '7'
when cpz.CardPlayRank.Eight then '8'
when cpz.CardPlayRank.Nine then '9'
when cpz.CardPlayRank.Ten then '10'
when cpz.CardPlayRank.Jack then 'J'
when cpz.CardPlayRank.Queen then 'Q'
when cpz.CardPlayRank.King then 'K'
else 'A'
|
[
{
"context": ".allTheThings v0.7.2 - 12 September, 2012\n\n (c) Amsul Naeem, 2012 - http://amsul.ca\n Licensed under MIT (\"",
"end": 1488,
"score": 0.9998992085456848,
"start": 1477,
"tag": "NAME",
"value": "Amsul Naeem"
},
{
"context": "flavour) license.\n Hosted on http://github.com/amsul/Load.allTheThings\n\n This library creates a Loa",
"end": 1600,
"score": 0.9475982189178467,
"start": 1595,
"tag": "USERNAME",
"value": "amsul"
},
{
"context": " For more documentation, check http://github.com/amsul/Load.allTheThings\n\n\n * Note: Load.fonts is req",
"end": 1907,
"score": 0.9996609687805176,
"start": 1902,
"tag": "USERNAME",
"value": "amsul"
},
{
"context": "onts is required to load fonts (http://github.com/amsul/Load.fonts)\n###\n\n###jshint debug: true, browser: ",
"end": 2001,
"score": 0.9996418952941895,
"start": 1996,
"tag": "USERNAME",
"value": "amsul"
},
{
"context": " throw 'Load.fonts (http://github.com/amsul/Load.fonts) is required for Load.allTheThings to ",
"end": 4392,
"score": 0.9996137619018555,
"start": 4387,
"tag": "USERNAME",
"value": "amsul"
}
] | Load.allTheThings.coffee | amsul/Load.allTheThings | 6 | ###
__ __ ___ ___ ______ __ ______ __
/\ \ /\ \ /\_ \ /\_ \/\__ _\/\ \ /\__ _\/\ \ __
\ \ \ ___ __ \_\ \ __ \//\ \ \//\ \/_/\ \/\ \ \___ __\/_/\ \/\ \ \___ /\_\ ___ __ ____
\ \ \ __ / __`\ /'__`\ /'_` \ /'__`\ \ \ \ \ \ \ \ \ \ \ \ _ `\ /'__`\ \ \ \ \ \ _ `\/\ \ /' _ `\ /'_ `\ /',__\
\ \ \L\ \/\ \L\ \/\ \L\.\_/\ \L\ \ __/\ \L\.\_ \_\ \_ \_\ \_\ \ \ \ \ \ \ \/\ __/ \ \ \ \ \ \ \ \ \ \/\ \/\ \/\ \L\ \/\__, `\
\ \____/\ \____/\ \__/.\_\ \___,_\/\_\ \__/.\_\/\____\/\____\\ \_\ \ \_\ \_\ \____\ \ \_\ \ \_\ \_\ \_\ \_\ \_\ \____ \/\____/
\/___/ \/___/ \/__/\/_/\/__,_ /\/_/\/__/\/_/\/____/\/____/ \/_/ \/_/\/_/\/____/ \/_/ \/_/\/_/\/_/\/_/\/_/\/___L\ \/___/
/\____/
\_/__/
==================================================================================================================================
----------------------------------------------------------------------------------------------------------------------------------
###
###!
Load.allTheThings v0.7.2 - 12 September, 2012
(c) Amsul Naeem, 2012 - http://amsul.ca
Licensed under MIT ("expat" flavour) license.
Hosted on http://github.com/amsul/Load.allTheThings
This library creates a Load object which can be used to
preload things before they are needed on your page. It can
load images, fonts, stylesheets, scripts, and html.
To invoke the loader, use Load.allTheThings()
For more documentation, check http://github.com/amsul/Load.allTheThings
* Note: Load.fonts is required to load fonts (http://github.com/amsul/Load.fonts)
###
###jshint debug: true, browser: true, devel: true, curly: false, forin: false, nonew: true, plusplus: false###
class Load
## create a global reach
window.Load = Load
## for private methods
self = {}
## for querying the dom
dom =
get: ( selector ) ->
if selector and typeof selector is 'string'
if selector.match /^#/ then return document.getElementById selector.replace /^#/, ''
else if selector.match /^\./ then return document.getElementsByClassName selector.replace /^\./, ''
else return document.querySelectorAll selector
return null
###
Load all the things!
======================================================================== ###
Load.allTheThings = ( options ) ->
## begin loading things based on options
self.beginLoading( options )
return Load
#allTheThings
###
When loading begins, do some things
======================================================================== ###
self.beginLoading = ( options ) ->
## keep a private counts of things
self.PROGRESS = 0
self.THINGS = 0
self.THINGS_LOADED = 0
## in case no options are passed
options = options || {}
## store the options
Load.options = options
## default options
self.defaults =
thingsToLoad: [ 'images', 'fonts', 'css', 'js', 'html', 'data' ]
within: null
progressId: null
progressBarId: null
thingsId: null
thingsLoadedId: null
cleanUp: false
onError: ( thing ) -> return Load
onLoad: ( thing ) -> return Load
onComplete: -> return Load
## check the options and merge with the defaults
for own key, value of self.defaults
Load.options[ key ] = options[ key ] || value
## check if fonts are being requested
if Load.options.thingsToLoad.indexOf 'fonts' isnt -1
## check if Load.fonts has been attached
if not window.Font or not window.Font::isLoadDotFonts
throw 'Load.fonts (http://github.com/amsul/Load.fonts) is required for Load.allTheThings to work with fonts.'
## store the elements that will need UI updates
Load.elemProgress = dom.get '#' + Load.options.progressId
Load.elemProgressBar = dom.get '#' + Load.options.progressBarId
Load.elemThings = dom.get '#' + Load.options.thingsId
Load.elemThingsLoaded = dom.get '#' + Load.options.thingsLoadedId
# put in all the initial counts
Load.elemThingsLoaded.innerHTML = self.THINGS_LOADED if Load.elemThingsLoaded
Load.elemProgress.innerHTML = self.PROGRESS if Load.elemProgress
## figure out the context
context = ( ->
selector = dom.get Load.options.within
return selector || document
)()
## collect all the required things within the context
self.loadAllThingsWithin context if context
## update the UI with the final count of things
Load.elemThings.innerHTML = self.THINGS if Load.elemThings
Load.elemProgressBar.style.width = 0 + '%' if Load.elemProgressBar
return self
#beginLoading
###
Add things to a collection to be loaded
======================================================================== ###
self.loadAllThingsWithin = ( context ) ->
## collection for context nodes
collectionOfNodes = []
## collection of all the things found
collectionOfThings = []
## check if the context is a nodelist
if context.constructor.name is 'NodeList'
## push all the context elements into a collection
collectionOfNodes.push node for node in context
## if it's not a nodelist, just pass into collection
else collectionOfNodes.push context
## go through the type of things to load, and find them
thingsToLoad = Load.options.thingsToLoad
thingsToLoad = if typeof thingsToLoad is 'string' then [ thingsToLoad ] else thingsToLoad
self.findThings collectionOfNodes, collectionOfThings, type for type in thingsToLoad
## update the count of things
self.THINGS += collectionOfThings.length
return self
#loadAllThingsWithin
###
Find things to load in a collection
======================================================================== ###
self.findThings = ( collectionNodes, collectionThings, type ) ->
## filter things with `data-src` out of a list of things
filterThenLoad = ( things, type ) ->
## go through the things and filter out ones with `data-src`
for thing in things
## if there is a `data-src`
if thing.dataset and thing.dataset.src
## begin loading the thing
self.load thing, type
## put the thing in the collection
collectionThings.push thing
return self
## create a selector based on type
selector = ( ->
switch type
when 'images' then 'img'
when 'fonts' then 'font'
when 'css' then 'link'
when 'js' then 'script'
when 'html' then 'section'
when 'data' then 'code'
else throw 'Thing type \'' + type + '\' is unknown'
)()
## get things of this type within the collection
for node in collectionNodes
## find the things of this type in this node
things = node.querySelectorAll selector
## if there are matching things
filterThenLoad things, type if things.length
return self
#findThings
###
Load things based on type of things
======================================================================== ###
self.load = ( thing, type ) ->
## if type is fonts
if type is 'fonts'
font = new Font()
## add the handlers based on type
self.addHandlers font, type
## set the font family and start to load
font.fontFamily = thing.dataset.family
font.src = thing.dataset.src
## for things other than fonts
else
request = thing.dataset.src
## add the handlers based on type
self.addHandlers thing, type
if type is 'css' then thing.href = request
else thing.src = request
## do cleanup on the thing element
self.doCleanUp thing, type
return self
#load
###
Do a clean up of the thing data-src
======================================================================== ###
self.doCleanUp = ( thing, type ) ->
## remove the data binding
thing.removeAttribute 'data-src'
## only for data and fonts
if type is 'data' or type is 'fonts'
## if a total clean up is required, remove thing from the dom
if Load.options.cleanUp then thing.outerHTML = ''
## otherwise hide the thing
else thing.style.display = 'none'
return self
#doCleanup
###
Update the progress as things load
======================================================================== ###
self.thingLoaded = ( thing, type, request ) ->
## update the counts
self.THINGS_LOADED += 1
self.PROGRESS = self.THINGS_LOADED / self.THINGS * 100
## update the UI
Load.elemProgress.innerHTML = self.PROGRESS if Load.elemProgress
Load.elemProgressBar.style.width = self.PROGRESS + '%' if Load.elemProgressBar
Load.elemThingsLoaded.innerHTML = self.THINGS_LOADED if Load.elemThingsLoaded
## do final stuff depending on type
if type is 'html'
thing.innerHTML = request.responseText
else if type is 'data'
self.addToCache thing, type, request.responseText
## do stuff when this thing is loaded
Load.options.onLoad thing, type
## do stuff when all the things are loaded
self.loadComplete() if self.THINGS_LOADED is self.THINGS
return self
#thingLoaded
###
Update the progress as things load
======================================================================== ###
self.loadComplete = ->
## invoke the oncomplete option
Load.options.onComplete()
return self
###
Bind and unbind some events
======================================================================== ###
self.bind = ( thing, listener, handler ) ->
thing.addEventListener listener, handler, false
return self
self.unbind = ( thing, listener, handler ) ->
thing.removeEventListener listener, handler
return self
###
Add and remove handlers
======================================================================== ###
self.addHandlers = ( thing, type ) ->
if type is 'images' or type is 'css' or type is 'js'
self.commonHandlers thing, type
else if type is 'fonts'
## event handlers
onLoad = ->
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onError = ->
self.removeHandlers thing, type
Load.options.onError thing, type
return
thing.onload = onLoad
thing.onerror = onError
else if type is 'html' or type is 'data'
## create a doc request
request = new XMLHttpRequest()
request.onload = (e) ->
self.
removeHandlers(request, type).
thingLoaded( thing, type, request )
return
request.onreadystatechange = (e) ->
if request.readyState is 4 and request.status is 200
self.
removeHandlers( request, type ).
thingLoaded( thing, type, request )
return
request.onerror = ->
self.removeHandlers request, type
return
request.open 'GET', thing.dataset.src, true
request.send()
else
console.log( 'no add handler', thing, type )
return self
#addHandlers
self.removeHandlers = ( thing, type ) ->
if type is 'images' or type is 'css' or type is 'js'
self.
unbind( thing, 'load', thing.onLoad ).
unbind( thing, 'readyStateChange', thing.onReadyStateChange ).
unbind( thing, 'error', thing.onError )
else if type is 'fonts'
thing.onload = ->
thing.onerror = ->
else if type is 'html' or type is 'data'
thing.onload = ->
thing.onreadystatechange = ->
thing.onerror = ->
else
console.log( 'no remove handler', thing, type )
return self
#removeHandlers
self.commonHandlers = ( thing, type ) ->
onLoad = ( e ) ->
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onReadyStateChange = ( e ) ->
if thing.readyState is 'complete'
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onError = ( e ) ->
self.removeHandlers thing, type
Load.options.onError thing, type
return
self.
bind( thing, 'load', onLoad ).
bind( thing, 'readyStateChange', onReadyStateChange ).
bind( thing, 'error', onError )
return self
#commonHandlers
###
Add a thing to the cache
======================================================================== ###
self.addToCache = ( thing, type, content ) ->
self.cache = self.cache || {}
if type is 'data'
## parse it as json
item = JSON.parse content
if thing.dataset and thing.dataset.name
self.cache[ thing.dataset.name ] = item
else
throw 'No name given to this type \'' + type + '\''
return self
#addToCache
###
Get a thing from cache
======================================================================== ###
Load.getCached = ( name ) ->
cachedThing = self.cache[ name ]
if cachedThing then return cachedThing
| 49849 | ###
__ __ ___ ___ ______ __ ______ __
/\ \ /\ \ /\_ \ /\_ \/\__ _\/\ \ /\__ _\/\ \ __
\ \ \ ___ __ \_\ \ __ \//\ \ \//\ \/_/\ \/\ \ \___ __\/_/\ \/\ \ \___ /\_\ ___ __ ____
\ \ \ __ / __`\ /'__`\ /'_` \ /'__`\ \ \ \ \ \ \ \ \ \ \ \ _ `\ /'__`\ \ \ \ \ \ _ `\/\ \ /' _ `\ /'_ `\ /',__\
\ \ \L\ \/\ \L\ \/\ \L\.\_/\ \L\ \ __/\ \L\.\_ \_\ \_ \_\ \_\ \ \ \ \ \ \ \/\ __/ \ \ \ \ \ \ \ \ \ \/\ \/\ \/\ \L\ \/\__, `\
\ \____/\ \____/\ \__/.\_\ \___,_\/\_\ \__/.\_\/\____\/\____\\ \_\ \ \_\ \_\ \____\ \ \_\ \ \_\ \_\ \_\ \_\ \_\ \____ \/\____/
\/___/ \/___/ \/__/\/_/\/__,_ /\/_/\/__/\/_/\/____/\/____/ \/_/ \/_/\/_/\/____/ \/_/ \/_/\/_/\/_/\/_/\/_/\/___L\ \/___/
/\____/
\_/__/
==================================================================================================================================
----------------------------------------------------------------------------------------------------------------------------------
###
###!
Load.allTheThings v0.7.2 - 12 September, 2012
(c) <NAME>, 2012 - http://amsul.ca
Licensed under MIT ("expat" flavour) license.
Hosted on http://github.com/amsul/Load.allTheThings
This library creates a Load object which can be used to
preload things before they are needed on your page. It can
load images, fonts, stylesheets, scripts, and html.
To invoke the loader, use Load.allTheThings()
For more documentation, check http://github.com/amsul/Load.allTheThings
* Note: Load.fonts is required to load fonts (http://github.com/amsul/Load.fonts)
###
###jshint debug: true, browser: true, devel: true, curly: false, forin: false, nonew: true, plusplus: false###
class Load
## create a global reach
window.Load = Load
## for private methods
self = {}
## for querying the dom
dom =
get: ( selector ) ->
if selector and typeof selector is 'string'
if selector.match /^#/ then return document.getElementById selector.replace /^#/, ''
else if selector.match /^\./ then return document.getElementsByClassName selector.replace /^\./, ''
else return document.querySelectorAll selector
return null
###
Load all the things!
======================================================================== ###
Load.allTheThings = ( options ) ->
## begin loading things based on options
self.beginLoading( options )
return Load
#allTheThings
###
When loading begins, do some things
======================================================================== ###
self.beginLoading = ( options ) ->
## keep a private counts of things
self.PROGRESS = 0
self.THINGS = 0
self.THINGS_LOADED = 0
## in case no options are passed
options = options || {}
## store the options
Load.options = options
## default options
self.defaults =
thingsToLoad: [ 'images', 'fonts', 'css', 'js', 'html', 'data' ]
within: null
progressId: null
progressBarId: null
thingsId: null
thingsLoadedId: null
cleanUp: false
onError: ( thing ) -> return Load
onLoad: ( thing ) -> return Load
onComplete: -> return Load
## check the options and merge with the defaults
for own key, value of self.defaults
Load.options[ key ] = options[ key ] || value
## check if fonts are being requested
if Load.options.thingsToLoad.indexOf 'fonts' isnt -1
## check if Load.fonts has been attached
if not window.Font or not window.Font::isLoadDotFonts
throw 'Load.fonts (http://github.com/amsul/Load.fonts) is required for Load.allTheThings to work with fonts.'
## store the elements that will need UI updates
Load.elemProgress = dom.get '#' + Load.options.progressId
Load.elemProgressBar = dom.get '#' + Load.options.progressBarId
Load.elemThings = dom.get '#' + Load.options.thingsId
Load.elemThingsLoaded = dom.get '#' + Load.options.thingsLoadedId
# put in all the initial counts
Load.elemThingsLoaded.innerHTML = self.THINGS_LOADED if Load.elemThingsLoaded
Load.elemProgress.innerHTML = self.PROGRESS if Load.elemProgress
## figure out the context
context = ( ->
selector = dom.get Load.options.within
return selector || document
)()
## collect all the required things within the context
self.loadAllThingsWithin context if context
## update the UI with the final count of things
Load.elemThings.innerHTML = self.THINGS if Load.elemThings
Load.elemProgressBar.style.width = 0 + '%' if Load.elemProgressBar
return self
#beginLoading
###
Add things to a collection to be loaded
======================================================================== ###
self.loadAllThingsWithin = ( context ) ->
## collection for context nodes
collectionOfNodes = []
## collection of all the things found
collectionOfThings = []
## check if the context is a nodelist
if context.constructor.name is 'NodeList'
## push all the context elements into a collection
collectionOfNodes.push node for node in context
## if it's not a nodelist, just pass into collection
else collectionOfNodes.push context
## go through the type of things to load, and find them
thingsToLoad = Load.options.thingsToLoad
thingsToLoad = if typeof thingsToLoad is 'string' then [ thingsToLoad ] else thingsToLoad
self.findThings collectionOfNodes, collectionOfThings, type for type in thingsToLoad
## update the count of things
self.THINGS += collectionOfThings.length
return self
#loadAllThingsWithin
###
Find things to load in a collection
======================================================================== ###
self.findThings = ( collectionNodes, collectionThings, type ) ->
## filter things with `data-src` out of a list of things
filterThenLoad = ( things, type ) ->
## go through the things and filter out ones with `data-src`
for thing in things
## if there is a `data-src`
if thing.dataset and thing.dataset.src
## begin loading the thing
self.load thing, type
## put the thing in the collection
collectionThings.push thing
return self
## create a selector based on type
selector = ( ->
switch type
when 'images' then 'img'
when 'fonts' then 'font'
when 'css' then 'link'
when 'js' then 'script'
when 'html' then 'section'
when 'data' then 'code'
else throw 'Thing type \'' + type + '\' is unknown'
)()
## get things of this type within the collection
for node in collectionNodes
## find the things of this type in this node
things = node.querySelectorAll selector
## if there are matching things
filterThenLoad things, type if things.length
return self
#findThings
###
Load things based on type of things
======================================================================== ###
self.load = ( thing, type ) ->
## if type is fonts
if type is 'fonts'
font = new Font()
## add the handlers based on type
self.addHandlers font, type
## set the font family and start to load
font.fontFamily = thing.dataset.family
font.src = thing.dataset.src
## for things other than fonts
else
request = thing.dataset.src
## add the handlers based on type
self.addHandlers thing, type
if type is 'css' then thing.href = request
else thing.src = request
## do cleanup on the thing element
self.doCleanUp thing, type
return self
#load
###
Do a clean up of the thing data-src
======================================================================== ###
self.doCleanUp = ( thing, type ) ->
## remove the data binding
thing.removeAttribute 'data-src'
## only for data and fonts
if type is 'data' or type is 'fonts'
## if a total clean up is required, remove thing from the dom
if Load.options.cleanUp then thing.outerHTML = ''
## otherwise hide the thing
else thing.style.display = 'none'
return self
#doCleanup
###
Update the progress as things load
======================================================================== ###
self.thingLoaded = ( thing, type, request ) ->
## update the counts
self.THINGS_LOADED += 1
self.PROGRESS = self.THINGS_LOADED / self.THINGS * 100
## update the UI
Load.elemProgress.innerHTML = self.PROGRESS if Load.elemProgress
Load.elemProgressBar.style.width = self.PROGRESS + '%' if Load.elemProgressBar
Load.elemThingsLoaded.innerHTML = self.THINGS_LOADED if Load.elemThingsLoaded
## do final stuff depending on type
if type is 'html'
thing.innerHTML = request.responseText
else if type is 'data'
self.addToCache thing, type, request.responseText
## do stuff when this thing is loaded
Load.options.onLoad thing, type
## do stuff when all the things are loaded
self.loadComplete() if self.THINGS_LOADED is self.THINGS
return self
#thingLoaded
###
Update the progress as things load
======================================================================== ###
self.loadComplete = ->
## invoke the oncomplete option
Load.options.onComplete()
return self
###
Bind and unbind some events
======================================================================== ###
self.bind = ( thing, listener, handler ) ->
thing.addEventListener listener, handler, false
return self
self.unbind = ( thing, listener, handler ) ->
thing.removeEventListener listener, handler
return self
###
Add and remove handlers
======================================================================== ###
self.addHandlers = ( thing, type ) ->
if type is 'images' or type is 'css' or type is 'js'
self.commonHandlers thing, type
else if type is 'fonts'
## event handlers
onLoad = ->
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onError = ->
self.removeHandlers thing, type
Load.options.onError thing, type
return
thing.onload = onLoad
thing.onerror = onError
else if type is 'html' or type is 'data'
## create a doc request
request = new XMLHttpRequest()
request.onload = (e) ->
self.
removeHandlers(request, type).
thingLoaded( thing, type, request )
return
request.onreadystatechange = (e) ->
if request.readyState is 4 and request.status is 200
self.
removeHandlers( request, type ).
thingLoaded( thing, type, request )
return
request.onerror = ->
self.removeHandlers request, type
return
request.open 'GET', thing.dataset.src, true
request.send()
else
console.log( 'no add handler', thing, type )
return self
#addHandlers
self.removeHandlers = ( thing, type ) ->
if type is 'images' or type is 'css' or type is 'js'
self.
unbind( thing, 'load', thing.onLoad ).
unbind( thing, 'readyStateChange', thing.onReadyStateChange ).
unbind( thing, 'error', thing.onError )
else if type is 'fonts'
thing.onload = ->
thing.onerror = ->
else if type is 'html' or type is 'data'
thing.onload = ->
thing.onreadystatechange = ->
thing.onerror = ->
else
console.log( 'no remove handler', thing, type )
return self
#removeHandlers
self.commonHandlers = ( thing, type ) ->
onLoad = ( e ) ->
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onReadyStateChange = ( e ) ->
if thing.readyState is 'complete'
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onError = ( e ) ->
self.removeHandlers thing, type
Load.options.onError thing, type
return
self.
bind( thing, 'load', onLoad ).
bind( thing, 'readyStateChange', onReadyStateChange ).
bind( thing, 'error', onError )
return self
#commonHandlers
###
Add a thing to the cache
======================================================================== ###
self.addToCache = ( thing, type, content ) ->
self.cache = self.cache || {}
if type is 'data'
## parse it as json
item = JSON.parse content
if thing.dataset and thing.dataset.name
self.cache[ thing.dataset.name ] = item
else
throw 'No name given to this type \'' + type + '\''
return self
#addToCache
###
Get a thing from cache
======================================================================== ###
Load.getCached = ( name ) ->
cachedThing = self.cache[ name ]
if cachedThing then return cachedThing
| true | ###
__ __ ___ ___ ______ __ ______ __
/\ \ /\ \ /\_ \ /\_ \/\__ _\/\ \ /\__ _\/\ \ __
\ \ \ ___ __ \_\ \ __ \//\ \ \//\ \/_/\ \/\ \ \___ __\/_/\ \/\ \ \___ /\_\ ___ __ ____
\ \ \ __ / __`\ /'__`\ /'_` \ /'__`\ \ \ \ \ \ \ \ \ \ \ \ _ `\ /'__`\ \ \ \ \ \ _ `\/\ \ /' _ `\ /'_ `\ /',__\
\ \ \L\ \/\ \L\ \/\ \L\.\_/\ \L\ \ __/\ \L\.\_ \_\ \_ \_\ \_\ \ \ \ \ \ \ \/\ __/ \ \ \ \ \ \ \ \ \ \/\ \/\ \/\ \L\ \/\__, `\
\ \____/\ \____/\ \__/.\_\ \___,_\/\_\ \__/.\_\/\____\/\____\\ \_\ \ \_\ \_\ \____\ \ \_\ \ \_\ \_\ \_\ \_\ \_\ \____ \/\____/
\/___/ \/___/ \/__/\/_/\/__,_ /\/_/\/__/\/_/\/____/\/____/ \/_/ \/_/\/_/\/____/ \/_/ \/_/\/_/\/_/\/_/\/_/\/___L\ \/___/
/\____/
\_/__/
==================================================================================================================================
----------------------------------------------------------------------------------------------------------------------------------
###
###!
Load.allTheThings v0.7.2 - 12 September, 2012
(c) PI:NAME:<NAME>END_PI, 2012 - http://amsul.ca
Licensed under MIT ("expat" flavour) license.
Hosted on http://github.com/amsul/Load.allTheThings
This library creates a Load object which can be used to
preload things before they are needed on your page. It can
load images, fonts, stylesheets, scripts, and html.
To invoke the loader, use Load.allTheThings()
For more documentation, check http://github.com/amsul/Load.allTheThings
* Note: Load.fonts is required to load fonts (http://github.com/amsul/Load.fonts)
###
###jshint debug: true, browser: true, devel: true, curly: false, forin: false, nonew: true, plusplus: false###
class Load
## create a global reach
window.Load = Load
## for private methods
self = {}
## for querying the dom
dom =
get: ( selector ) ->
if selector and typeof selector is 'string'
if selector.match /^#/ then return document.getElementById selector.replace /^#/, ''
else if selector.match /^\./ then return document.getElementsByClassName selector.replace /^\./, ''
else return document.querySelectorAll selector
return null
###
Load all the things!
======================================================================== ###
Load.allTheThings = ( options ) ->
## begin loading things based on options
self.beginLoading( options )
return Load
#allTheThings
###
When loading begins, do some things
======================================================================== ###
self.beginLoading = ( options ) ->
## keep a private counts of things
self.PROGRESS = 0
self.THINGS = 0
self.THINGS_LOADED = 0
## in case no options are passed
options = options || {}
## store the options
Load.options = options
## default options
self.defaults =
thingsToLoad: [ 'images', 'fonts', 'css', 'js', 'html', 'data' ]
within: null
progressId: null
progressBarId: null
thingsId: null
thingsLoadedId: null
cleanUp: false
onError: ( thing ) -> return Load
onLoad: ( thing ) -> return Load
onComplete: -> return Load
## check the options and merge with the defaults
for own key, value of self.defaults
Load.options[ key ] = options[ key ] || value
## check if fonts are being requested
if Load.options.thingsToLoad.indexOf 'fonts' isnt -1
## check if Load.fonts has been attached
if not window.Font or not window.Font::isLoadDotFonts
throw 'Load.fonts (http://github.com/amsul/Load.fonts) is required for Load.allTheThings to work with fonts.'
## store the elements that will need UI updates
Load.elemProgress = dom.get '#' + Load.options.progressId
Load.elemProgressBar = dom.get '#' + Load.options.progressBarId
Load.elemThings = dom.get '#' + Load.options.thingsId
Load.elemThingsLoaded = dom.get '#' + Load.options.thingsLoadedId
# put in all the initial counts
Load.elemThingsLoaded.innerHTML = self.THINGS_LOADED if Load.elemThingsLoaded
Load.elemProgress.innerHTML = self.PROGRESS if Load.elemProgress
## figure out the context
context = ( ->
selector = dom.get Load.options.within
return selector || document
)()
## collect all the required things within the context
self.loadAllThingsWithin context if context
## update the UI with the final count of things
Load.elemThings.innerHTML = self.THINGS if Load.elemThings
Load.elemProgressBar.style.width = 0 + '%' if Load.elemProgressBar
return self
#beginLoading
###
Add things to a collection to be loaded
======================================================================== ###
self.loadAllThingsWithin = ( context ) ->
## collection for context nodes
collectionOfNodes = []
## collection of all the things found
collectionOfThings = []
## check if the context is a nodelist
if context.constructor.name is 'NodeList'
## push all the context elements into a collection
collectionOfNodes.push node for node in context
## if it's not a nodelist, just pass into collection
else collectionOfNodes.push context
## go through the type of things to load, and find them
thingsToLoad = Load.options.thingsToLoad
thingsToLoad = if typeof thingsToLoad is 'string' then [ thingsToLoad ] else thingsToLoad
self.findThings collectionOfNodes, collectionOfThings, type for type in thingsToLoad
## update the count of things
self.THINGS += collectionOfThings.length
return self
#loadAllThingsWithin
###
Find things to load in a collection
======================================================================== ###
self.findThings = ( collectionNodes, collectionThings, type ) ->
## filter things with `data-src` out of a list of things
filterThenLoad = ( things, type ) ->
## go through the things and filter out ones with `data-src`
for thing in things
## if there is a `data-src`
if thing.dataset and thing.dataset.src
## begin loading the thing
self.load thing, type
## put the thing in the collection
collectionThings.push thing
return self
## create a selector based on type
selector = ( ->
switch type
when 'images' then 'img'
when 'fonts' then 'font'
when 'css' then 'link'
when 'js' then 'script'
when 'html' then 'section'
when 'data' then 'code'
else throw 'Thing type \'' + type + '\' is unknown'
)()
## get things of this type within the collection
for node in collectionNodes
## find the things of this type in this node
things = node.querySelectorAll selector
## if there are matching things
filterThenLoad things, type if things.length
return self
#findThings
###
Load things based on type of things
======================================================================== ###
self.load = ( thing, type ) ->
## if type is fonts
if type is 'fonts'
font = new Font()
## add the handlers based on type
self.addHandlers font, type
## set the font family and start to load
font.fontFamily = thing.dataset.family
font.src = thing.dataset.src
## for things other than fonts
else
request = thing.dataset.src
## add the handlers based on type
self.addHandlers thing, type
if type is 'css' then thing.href = request
else thing.src = request
## do cleanup on the thing element
self.doCleanUp thing, type
return self
#load
###
Do a clean up of the thing data-src
======================================================================== ###
self.doCleanUp = ( thing, type ) ->
## remove the data binding
thing.removeAttribute 'data-src'
## only for data and fonts
if type is 'data' or type is 'fonts'
## if a total clean up is required, remove thing from the dom
if Load.options.cleanUp then thing.outerHTML = ''
## otherwise hide the thing
else thing.style.display = 'none'
return self
#doCleanup
###
Update the progress as things load
======================================================================== ###
self.thingLoaded = ( thing, type, request ) ->
## update the counts
self.THINGS_LOADED += 1
self.PROGRESS = self.THINGS_LOADED / self.THINGS * 100
## update the UI
Load.elemProgress.innerHTML = self.PROGRESS if Load.elemProgress
Load.elemProgressBar.style.width = self.PROGRESS + '%' if Load.elemProgressBar
Load.elemThingsLoaded.innerHTML = self.THINGS_LOADED if Load.elemThingsLoaded
## do final stuff depending on type
if type is 'html'
thing.innerHTML = request.responseText
else if type is 'data'
self.addToCache thing, type, request.responseText
## do stuff when this thing is loaded
Load.options.onLoad thing, type
## do stuff when all the things are loaded
self.loadComplete() if self.THINGS_LOADED is self.THINGS
return self
#thingLoaded
###
Update the progress as things load
======================================================================== ###
self.loadComplete = ->
## invoke the oncomplete option
Load.options.onComplete()
return self
###
Bind and unbind some events
======================================================================== ###
self.bind = ( thing, listener, handler ) ->
thing.addEventListener listener, handler, false
return self
self.unbind = ( thing, listener, handler ) ->
thing.removeEventListener listener, handler
return self
###
Add and remove handlers
======================================================================== ###
self.addHandlers = ( thing, type ) ->
if type is 'images' or type is 'css' or type is 'js'
self.commonHandlers thing, type
else if type is 'fonts'
## event handlers
onLoad = ->
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onError = ->
self.removeHandlers thing, type
Load.options.onError thing, type
return
thing.onload = onLoad
thing.onerror = onError
else if type is 'html' or type is 'data'
## create a doc request
request = new XMLHttpRequest()
request.onload = (e) ->
self.
removeHandlers(request, type).
thingLoaded( thing, type, request )
return
request.onreadystatechange = (e) ->
if request.readyState is 4 and request.status is 200
self.
removeHandlers( request, type ).
thingLoaded( thing, type, request )
return
request.onerror = ->
self.removeHandlers request, type
return
request.open 'GET', thing.dataset.src, true
request.send()
else
console.log( 'no add handler', thing, type )
return self
#addHandlers
self.removeHandlers = ( thing, type ) ->
if type is 'images' or type is 'css' or type is 'js'
self.
unbind( thing, 'load', thing.onLoad ).
unbind( thing, 'readyStateChange', thing.onReadyStateChange ).
unbind( thing, 'error', thing.onError )
else if type is 'fonts'
thing.onload = ->
thing.onerror = ->
else if type is 'html' or type is 'data'
thing.onload = ->
thing.onreadystatechange = ->
thing.onerror = ->
else
console.log( 'no remove handler', thing, type )
return self
#removeHandlers
self.commonHandlers = ( thing, type ) ->
onLoad = ( e ) ->
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onReadyStateChange = ( e ) ->
if thing.readyState is 'complete'
self.
removeHandlers( thing, type ).
thingLoaded( thing, type )
return
onError = ( e ) ->
self.removeHandlers thing, type
Load.options.onError thing, type
return
self.
bind( thing, 'load', onLoad ).
bind( thing, 'readyStateChange', onReadyStateChange ).
bind( thing, 'error', onError )
return self
#commonHandlers
###
Add a thing to the cache
======================================================================== ###
self.addToCache = ( thing, type, content ) ->
self.cache = self.cache || {}
if type is 'data'
## parse it as json
item = JSON.parse content
if thing.dataset and thing.dataset.name
self.cache[ thing.dataset.name ] = item
else
throw 'No name given to this type \'' + type + '\''
return self
#addToCache
###
Get a thing from cache
======================================================================== ###
Load.getCached = ( name ) ->
cachedThing = self.cache[ name ]
if cachedThing then return cachedThing
|
[
{
"context": "ript\n# (c) 2013-2017 Flowhub UG\n# (c) 2013 Henri Bergius, Nemein\n# NoFlo may be freely distributed und",
"end": 111,
"score": 0.9998459815979004,
"start": 98,
"tag": "NAME",
"value": "Henri Bergius"
},
{
"context": "2013-2017 Flowhub UG\n# (c) 2013 Henri Bergius, Nemein\n# NoFlo may be freely distributed under the M",
"end": 119,
"score": 0.9984235763549805,
"start": 113,
"tag": "NAME",
"value": "Nemein"
}
] | src/lib/ComponentLoader.coffee | rrothenb/noflo | 0 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2017 Flowhub UG
# (c) 2013 Henri Bergius, Nemein
# NoFlo may be freely distributed under the MIT license
fbpGraph = require 'fbp-graph'
{EventEmitter} = require 'events'
registerLoader = require './loader/register'
platform = require './Platform'
# ## The NoFlo Component Loader
#
# The Component Loader is responsible for discovering components
# available in the running system, as well as for instantiating
# them.
#
# Internally the loader uses a registered, platform-specific
# loader. NoFlo ships with a loader for Node.js that discovers
# components from the current project's `components/` and
# `graphs/` folders, as well as those folders of any installed
# NPM dependencies. For browsers and embedded devices it is
# possible to generate a statically configured component
# loader using the [noflo-component-loader](https://github.com/noflo/noflo-component-loader) webpack plugin.
class ComponentLoader extends EventEmitter
constructor: (baseDir, options = {}) ->
super()
@baseDir = baseDir
@options = options
@components = null
@libraryIcons = {}
@processing = false
@ready = false
@setMaxListeners 0
# Get the library prefix for a given module name. This
# is mostly used for generating valid names for namespaced
# NPM modules, as well as for convenience renaming all
# `noflo-` prefixed modules with just their base name.
#
# Examples:
#
# * `my-project` becomes `my-project`
# * `@foo/my-project` becomes `my-project`
# * `noflo-core` becomes `core`
getModulePrefix: (name) ->
return '' unless name
return '' if name is 'noflo'
name = name.replace /\@[a-z\-]+\//, '' if name[0] is '@'
name.replace /^noflo-/, ''
# Get the list of all available components
listComponents: (callback) ->
if @processing
@once 'ready', =>
callback null, @components
return
return callback null, @components if @components
@ready = false
@processing = true
@components = {}
registerLoader.register @, (err) =>
if err
return callback err
throw err
@processing = false
@ready = true
@emit 'ready', true
callback null, @components
return
# Load an instance of a specific component. If the
# registered component is a JSON or FBP graph, it will
# be loaded as an instance of the NoFlo subgraph
# component.
load: (name, callback, metadata) ->
unless @ready
@listComponents (err) =>
return callback err if err
@load name, callback, metadata
return
if name?.constructor?.name is 'Component'
component = name
name = 'anonymous'
else
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
break
unless component
# Failure to load
callback new Error "Component #{name} not available with base #{@baseDir}"
return
if @isGraph component
@loadGraph name, component, callback, metadata
return
@createComponent name, component, metadata, (err, instance) =>
return callback err if err
if not instance
callback new Error "Component #{name} could not be loaded."
return
instance.baseDir = @baseDir if name is 'Graph'
instance.componentName = name if typeof name is 'string'
if instance.isLegacy()
platform.deprecated "Component #{name} uses legacy NoFlo APIs. Please port to Process API"
@setIcon name, instance
callback null, instance
# Creates an instance of a component.
createComponent: (name, component, metadata, callback) ->
implementation = component
unless implementation
return callback new Error "Component #{name} not available"
# If a string was specified, attempt to `require` it.
if typeof implementation is 'string'
if typeof registerLoader.dynamicLoad is 'function'
registerLoader.dynamicLoad name, implementation, metadata, callback
return
return callback Error "Dynamic loading of #{implementation} for component #{name} not available on this platform."
if implementation?.constructor?.name is 'Component'
instance = implementation
# Attempt to create the component instance using the `getComponent` method.
else if typeof implementation.getComponent is 'function'
try
instance = implementation.getComponent metadata
catch e
return callback e
# Attempt to create a component using a factory function.
else if typeof implementation is 'function'
try
instance = implementation metadata
catch e
return callback e
else
callback new Error "Invalid type #{typeof(implementation)} for component #{name}."
return
callback null, instance
# Check if a given filesystem path is actually a graph
isGraph: (cPath) ->
# Live graph instance
return true if typeof cPath is 'object' and cPath instanceof fbpGraph.Graph
# Graph JSON definition
return true if typeof cPath is 'object' and cPath.processes and cPath.connections
return false unless typeof cPath is 'string'
# Graph file path
cPath.indexOf('.fbp') isnt -1 or cPath.indexOf('.json') isnt -1
# Load a graph as a NoFlo subgraph component instance
loadGraph: (name, component, callback, metadata) ->
@createComponent name, @components['Graph'], metadata, (err, graph) =>
return callback err if err
graph.loader = @
graph.baseDir = @baseDir
graph.inPorts.remove 'graph'
graph.setGraph component, (err) =>
return callback err if err
@setIcon name, graph
callback null, graph
return
return
# Set icon for the component instance. If the instance
# has an icon set, then this is a no-op. Otherwise we
# determine an icon based on the module it is coming
# from, or use a fallback icon separately for subgraphs
# and elementary components.
setIcon: (name, instance) ->
# See if component has an icon
return if not instance.getIcon or instance.getIcon()
# See if library has an icon
[library, componentName] = name.split '/'
if componentName and @getLibraryIcon library
instance.setIcon @getLibraryIcon library
return
# See if instance is a subgraph
if instance.isSubgraph()
instance.setIcon 'sitemap'
return
instance.setIcon 'gear'
return
getLibraryIcon: (prefix) ->
if @libraryIcons[prefix]
return @libraryIcons[prefix]
return null
setLibraryIcon: (prefix, icon) ->
@libraryIcons[prefix] = icon
normalizeName: (packageId, name) ->
prefix = @getModulePrefix packageId
fullName = "#{prefix}/#{name}"
fullName = name unless packageId
fullName
# ### Registering components at runtime
#
# In addition to components discovered by the loader,
# it is possible to register components at runtime.
#
# With the `registerComponent` method you can register
# a NoFlo Component constructor or factory method
# as a component available for loading.
registerComponent: (packageId, name, cPath, callback) ->
fullName = @normalizeName packageId, name
@components[fullName] = cPath
do callback if callback
# With the `registerGraph` method you can register new
# graphs as loadable components.
registerGraph: (packageId, name, gPath, callback) ->
@registerComponent packageId, name, gPath, callback
# With `registerLoader` you can register custom component
# loaders. They will be called immediately and can register
# any components or graphs they wish.
registerLoader: (loader, callback) ->
loader @, callback
# With `setSource` you can register a component by providing
# a source code string. Supported languages and techniques
# depend on the runtime environment, for example CoffeeScript
# components can only be registered via `setSource` if
# the environment has a CoffeeScript compiler loaded.
setSource: (packageId, name, source, language, callback) ->
unless registerLoader.setSource
return callback new Error 'setSource not allowed'
unless @ready
@listComponents (err) =>
return callback err if err
@setSource packageId, name, source, language, callback
return
registerLoader.setSource @, packageId, name, source, language, callback
# `getSource` allows fetching the source code of a registered
# component as a string.
getSource: (name, callback) ->
unless registerLoader.getSource
return callback new Error 'getSource not allowed'
unless @ready
@listComponents (err) =>
return callback err if err
@getSource name, callback
return
registerLoader.getSource @, name, callback
clear: ->
@components = null
@ready = false
@processing = false
exports.ComponentLoader = ComponentLoader
| 192107 | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2017 Flowhub UG
# (c) 2013 <NAME>, <NAME>
# NoFlo may be freely distributed under the MIT license
fbpGraph = require 'fbp-graph'
{EventEmitter} = require 'events'
registerLoader = require './loader/register'
platform = require './Platform'
# ## The NoFlo Component Loader
#
# The Component Loader is responsible for discovering components
# available in the running system, as well as for instantiating
# them.
#
# Internally the loader uses a registered, platform-specific
# loader. NoFlo ships with a loader for Node.js that discovers
# components from the current project's `components/` and
# `graphs/` folders, as well as those folders of any installed
# NPM dependencies. For browsers and embedded devices it is
# possible to generate a statically configured component
# loader using the [noflo-component-loader](https://github.com/noflo/noflo-component-loader) webpack plugin.
class ComponentLoader extends EventEmitter
constructor: (baseDir, options = {}) ->
super()
@baseDir = baseDir
@options = options
@components = null
@libraryIcons = {}
@processing = false
@ready = false
@setMaxListeners 0
# Get the library prefix for a given module name. This
# is mostly used for generating valid names for namespaced
# NPM modules, as well as for convenience renaming all
# `noflo-` prefixed modules with just their base name.
#
# Examples:
#
# * `my-project` becomes `my-project`
# * `@foo/my-project` becomes `my-project`
# * `noflo-core` becomes `core`
getModulePrefix: (name) ->
return '' unless name
return '' if name is 'noflo'
name = name.replace /\@[a-z\-]+\//, '' if name[0] is '@'
name.replace /^noflo-/, ''
# Get the list of all available components
listComponents: (callback) ->
if @processing
@once 'ready', =>
callback null, @components
return
return callback null, @components if @components
@ready = false
@processing = true
@components = {}
registerLoader.register @, (err) =>
if err
return callback err
throw err
@processing = false
@ready = true
@emit 'ready', true
callback null, @components
return
# Load an instance of a specific component. If the
# registered component is a JSON or FBP graph, it will
# be loaded as an instance of the NoFlo subgraph
# component.
load: (name, callback, metadata) ->
unless @ready
@listComponents (err) =>
return callback err if err
@load name, callback, metadata
return
if name?.constructor?.name is 'Component'
component = name
name = 'anonymous'
else
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
break
unless component
# Failure to load
callback new Error "Component #{name} not available with base #{@baseDir}"
return
if @isGraph component
@loadGraph name, component, callback, metadata
return
@createComponent name, component, metadata, (err, instance) =>
return callback err if err
if not instance
callback new Error "Component #{name} could not be loaded."
return
instance.baseDir = @baseDir if name is 'Graph'
instance.componentName = name if typeof name is 'string'
if instance.isLegacy()
platform.deprecated "Component #{name} uses legacy NoFlo APIs. Please port to Process API"
@setIcon name, instance
callback null, instance
# Creates an instance of a component.
createComponent: (name, component, metadata, callback) ->
implementation = component
unless implementation
return callback new Error "Component #{name} not available"
# If a string was specified, attempt to `require` it.
if typeof implementation is 'string'
if typeof registerLoader.dynamicLoad is 'function'
registerLoader.dynamicLoad name, implementation, metadata, callback
return
return callback Error "Dynamic loading of #{implementation} for component #{name} not available on this platform."
if implementation?.constructor?.name is 'Component'
instance = implementation
# Attempt to create the component instance using the `getComponent` method.
else if typeof implementation.getComponent is 'function'
try
instance = implementation.getComponent metadata
catch e
return callback e
# Attempt to create a component using a factory function.
else if typeof implementation is 'function'
try
instance = implementation metadata
catch e
return callback e
else
callback new Error "Invalid type #{typeof(implementation)} for component #{name}."
return
callback null, instance
# Check if a given filesystem path is actually a graph
isGraph: (cPath) ->
# Live graph instance
return true if typeof cPath is 'object' and cPath instanceof fbpGraph.Graph
# Graph JSON definition
return true if typeof cPath is 'object' and cPath.processes and cPath.connections
return false unless typeof cPath is 'string'
# Graph file path
cPath.indexOf('.fbp') isnt -1 or cPath.indexOf('.json') isnt -1
# Load a graph as a NoFlo subgraph component instance
loadGraph: (name, component, callback, metadata) ->
@createComponent name, @components['Graph'], metadata, (err, graph) =>
return callback err if err
graph.loader = @
graph.baseDir = @baseDir
graph.inPorts.remove 'graph'
graph.setGraph component, (err) =>
return callback err if err
@setIcon name, graph
callback null, graph
return
return
# Set icon for the component instance. If the instance
# has an icon set, then this is a no-op. Otherwise we
# determine an icon based on the module it is coming
# from, or use a fallback icon separately for subgraphs
# and elementary components.
setIcon: (name, instance) ->
# See if component has an icon
return if not instance.getIcon or instance.getIcon()
# See if library has an icon
[library, componentName] = name.split '/'
if componentName and @getLibraryIcon library
instance.setIcon @getLibraryIcon library
return
# See if instance is a subgraph
if instance.isSubgraph()
instance.setIcon 'sitemap'
return
instance.setIcon 'gear'
return
getLibraryIcon: (prefix) ->
if @libraryIcons[prefix]
return @libraryIcons[prefix]
return null
setLibraryIcon: (prefix, icon) ->
@libraryIcons[prefix] = icon
normalizeName: (packageId, name) ->
prefix = @getModulePrefix packageId
fullName = "#{prefix}/#{name}"
fullName = name unless packageId
fullName
# ### Registering components at runtime
#
# In addition to components discovered by the loader,
# it is possible to register components at runtime.
#
# With the `registerComponent` method you can register
# a NoFlo Component constructor or factory method
# as a component available for loading.
registerComponent: (packageId, name, cPath, callback) ->
fullName = @normalizeName packageId, name
@components[fullName] = cPath
do callback if callback
# With the `registerGraph` method you can register new
# graphs as loadable components.
registerGraph: (packageId, name, gPath, callback) ->
@registerComponent packageId, name, gPath, callback
# With `registerLoader` you can register custom component
# loaders. They will be called immediately and can register
# any components or graphs they wish.
registerLoader: (loader, callback) ->
loader @, callback
# With `setSource` you can register a component by providing
# a source code string. Supported languages and techniques
# depend on the runtime environment, for example CoffeeScript
# components can only be registered via `setSource` if
# the environment has a CoffeeScript compiler loaded.
setSource: (packageId, name, source, language, callback) ->
unless registerLoader.setSource
return callback new Error 'setSource not allowed'
unless @ready
@listComponents (err) =>
return callback err if err
@setSource packageId, name, source, language, callback
return
registerLoader.setSource @, packageId, name, source, language, callback
# `getSource` allows fetching the source code of a registered
# component as a string.
getSource: (name, callback) ->
unless registerLoader.getSource
return callback new Error 'getSource not allowed'
unless @ready
@listComponents (err) =>
return callback err if err
@getSource name, callback
return
registerLoader.getSource @, name, callback
clear: ->
@components = null
@ready = false
@processing = false
exports.ComponentLoader = ComponentLoader
| true | # NoFlo - Flow-Based Programming for JavaScript
# (c) 2013-2017 Flowhub UG
# (c) 2013 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI
# NoFlo may be freely distributed under the MIT license
fbpGraph = require 'fbp-graph'
{EventEmitter} = require 'events'
registerLoader = require './loader/register'
platform = require './Platform'
# ## The NoFlo Component Loader
#
# The Component Loader is responsible for discovering components
# available in the running system, as well as for instantiating
# them.
#
# Internally the loader uses a registered, platform-specific
# loader. NoFlo ships with a loader for Node.js that discovers
# components from the current project's `components/` and
# `graphs/` folders, as well as those folders of any installed
# NPM dependencies. For browsers and embedded devices it is
# possible to generate a statically configured component
# loader using the [noflo-component-loader](https://github.com/noflo/noflo-component-loader) webpack plugin.
class ComponentLoader extends EventEmitter
constructor: (baseDir, options = {}) ->
super()
@baseDir = baseDir
@options = options
@components = null
@libraryIcons = {}
@processing = false
@ready = false
@setMaxListeners 0
# Get the library prefix for a given module name. This
# is mostly used for generating valid names for namespaced
# NPM modules, as well as for convenience renaming all
# `noflo-` prefixed modules with just their base name.
#
# Examples:
#
# * `my-project` becomes `my-project`
# * `@foo/my-project` becomes `my-project`
# * `noflo-core` becomes `core`
getModulePrefix: (name) ->
return '' unless name
return '' if name is 'noflo'
name = name.replace /\@[a-z\-]+\//, '' if name[0] is '@'
name.replace /^noflo-/, ''
# Get the list of all available components
listComponents: (callback) ->
if @processing
@once 'ready', =>
callback null, @components
return
return callback null, @components if @components
@ready = false
@processing = true
@components = {}
registerLoader.register @, (err) =>
if err
return callback err
throw err
@processing = false
@ready = true
@emit 'ready', true
callback null, @components
return
# Load an instance of a specific component. If the
# registered component is a JSON or FBP graph, it will
# be loaded as an instance of the NoFlo subgraph
# component.
load: (name, callback, metadata) ->
unless @ready
@listComponents (err) =>
return callback err if err
@load name, callback, metadata
return
if name?.constructor?.name is 'Component'
component = name
name = 'anonymous'
else
component = @components[name]
unless component
# Try an alias
for componentName of @components
if componentName.split('/')[1] is name
component = @components[componentName]
break
unless component
# Failure to load
callback new Error "Component #{name} not available with base #{@baseDir}"
return
if @isGraph component
@loadGraph name, component, callback, metadata
return
@createComponent name, component, metadata, (err, instance) =>
return callback err if err
if not instance
callback new Error "Component #{name} could not be loaded."
return
instance.baseDir = @baseDir if name is 'Graph'
instance.componentName = name if typeof name is 'string'
if instance.isLegacy()
platform.deprecated "Component #{name} uses legacy NoFlo APIs. Please port to Process API"
@setIcon name, instance
callback null, instance
# Creates an instance of a component.
createComponent: (name, component, metadata, callback) ->
implementation = component
unless implementation
return callback new Error "Component #{name} not available"
# If a string was specified, attempt to `require` it.
if typeof implementation is 'string'
if typeof registerLoader.dynamicLoad is 'function'
registerLoader.dynamicLoad name, implementation, metadata, callback
return
return callback Error "Dynamic loading of #{implementation} for component #{name} not available on this platform."
if implementation?.constructor?.name is 'Component'
instance = implementation
# Attempt to create the component instance using the `getComponent` method.
else if typeof implementation.getComponent is 'function'
try
instance = implementation.getComponent metadata
catch e
return callback e
# Attempt to create a component using a factory function.
else if typeof implementation is 'function'
try
instance = implementation metadata
catch e
return callback e
else
callback new Error "Invalid type #{typeof(implementation)} for component #{name}."
return
callback null, instance
# Check if a given filesystem path is actually a graph
isGraph: (cPath) ->
# Live graph instance
return true if typeof cPath is 'object' and cPath instanceof fbpGraph.Graph
# Graph JSON definition
return true if typeof cPath is 'object' and cPath.processes and cPath.connections
return false unless typeof cPath is 'string'
# Graph file path
cPath.indexOf('.fbp') isnt -1 or cPath.indexOf('.json') isnt -1
# Load a graph as a NoFlo subgraph component instance
loadGraph: (name, component, callback, metadata) ->
@createComponent name, @components['Graph'], metadata, (err, graph) =>
return callback err if err
graph.loader = @
graph.baseDir = @baseDir
graph.inPorts.remove 'graph'
graph.setGraph component, (err) =>
return callback err if err
@setIcon name, graph
callback null, graph
return
return
# Set icon for the component instance. If the instance
# has an icon set, then this is a no-op. Otherwise we
# determine an icon based on the module it is coming
# from, or use a fallback icon separately for subgraphs
# and elementary components.
setIcon: (name, instance) ->
# See if component has an icon
return if not instance.getIcon or instance.getIcon()
# See if library has an icon
[library, componentName] = name.split '/'
if componentName and @getLibraryIcon library
instance.setIcon @getLibraryIcon library
return
# See if instance is a subgraph
if instance.isSubgraph()
instance.setIcon 'sitemap'
return
instance.setIcon 'gear'
return
getLibraryIcon: (prefix) ->
if @libraryIcons[prefix]
return @libraryIcons[prefix]
return null
setLibraryIcon: (prefix, icon) ->
@libraryIcons[prefix] = icon
normalizeName: (packageId, name) ->
prefix = @getModulePrefix packageId
fullName = "#{prefix}/#{name}"
fullName = name unless packageId
fullName
# ### Registering components at runtime
#
# In addition to components discovered by the loader,
# it is possible to register components at runtime.
#
# With the `registerComponent` method you can register
# a NoFlo Component constructor or factory method
# as a component available for loading.
registerComponent: (packageId, name, cPath, callback) ->
fullName = @normalizeName packageId, name
@components[fullName] = cPath
do callback if callback
# With the `registerGraph` method you can register new
# graphs as loadable components.
registerGraph: (packageId, name, gPath, callback) ->
@registerComponent packageId, name, gPath, callback
# With `registerLoader` you can register custom component
# loaders. They will be called immediately and can register
# any components or graphs they wish.
registerLoader: (loader, callback) ->
loader @, callback
# With `setSource` you can register a component by providing
# a source code string. Supported languages and techniques
# depend on the runtime environment, for example CoffeeScript
# components can only be registered via `setSource` if
# the environment has a CoffeeScript compiler loaded.
setSource: (packageId, name, source, language, callback) ->
unless registerLoader.setSource
return callback new Error 'setSource not allowed'
unless @ready
@listComponents (err) =>
return callback err if err
@setSource packageId, name, source, language, callback
return
registerLoader.setSource @, packageId, name, source, language, callback
# `getSource` allows fetching the source code of a registered
# component as a string.
getSource: (name, callback) ->
unless registerLoader.getSource
return callback new Error 'getSource not allowed'
unless @ready
@listComponents (err) =>
return callback err if err
@getSource name, callback
return
registerLoader.getSource @, name, callback
clear: ->
@components = null
@ready = false
@processing = false
exports.ComponentLoader = ComponentLoader
|
[
{
"context": "#\n# BanaJs\n# author : dreampuf(soddyque@gmail.com)\n#\n\nexpress = require('express",
"end": 30,
"score": 0.9994798898696899,
"start": 22,
"tag": "USERNAME",
"value": "dreampuf"
},
{
"context": "#\n# BanaJs\n# author : dreampuf(soddyque@gmail.com)\n#\n\nexpress = require('express')\napp = module.exp",
"end": 49,
"score": 0.9999231696128845,
"start": 31,
"tag": "EMAIL",
"value": "soddyque@gmail.com"
},
{
"context": "'/public')\n\n #app.use express.session\n # key: \"banajs\"\n # secret: \"banajs\"\n\n app.use (req, res, next",
"end": 892,
"score": 0.9684087634086609,
"start": 886,
"tag": "KEY",
"value": "banajs"
},
{
"context": " express.session\n # key: \"banajs\"\n # secret: \"banajs\"\n\n app.use (req, res, next)->\n res.local \"con",
"end": 914,
"score": 0.972693145275116,
"start": 908,
"tag": "KEY",
"value": "banajs"
},
{
"context": "is')(express)\n app.use express.session\n key: \"banajs\"\n secret: \"banajs\"\n store: new RedisStore\n ",
"end": 1454,
"score": 0.972963809967041,
"start": 1448,
"tag": "KEY",
"value": "banajs"
},
{
"context": "se express.session\n key: \"banajs\"\n secret: \"banajs\"\n store: new RedisStore\n cookie:\n path",
"end": 1475,
"score": 0.9751688838005066,
"start": 1469,
"tag": "KEY",
"value": "banajs"
}
] | app.coffee | dreampuf/banajs | 3 | #
# BanaJs
# author : dreampuf(soddyque@gmail.com)
#
express = require('express')
app = module.exports = express.createServer()
coffeekup = require 'coffeekup'
coffeekup.tags = coffeekup.tags.concat ["feed", "subtitle", "id", "updated", "author", "name", "rights", "entry", "content"]
config = require './config'
admin_route = require('./route/admin_route')
blog_route = require('./route/blog_route')
# Configuration
app.configure ()->
app.set 'views', __dirname + '/views'
app.set 'view engine', 'coffee'
app.set 'prodir', __dirname
app.register('.coffee', coffeekup.adapters.express)
#app.use express.compiler src: __dirname + '/public', enable: ['coffeescript']
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.methodOverride()
#app.use app.router
app.use express.static(__dirname + '/public')
#app.use express.session
# key: "banajs"
# secret: "banajs"
app.use (req, res, next)->
res.local "config", config
next()
app.configure 'development', ()->
app.use express.errorHandler({ dumpExceptions: true, showStack: true })
#Session store put into third service for continue develop
MemcachedStore = require('connect-memcached')(express)
app.use express.session
secret: "banajs"
store: new MemcachedStore()
app.configure 'production', ()->
#app.use(express.errorHandler())
RedisStore = require('connect-redis')(express)
app.use express.session
key: "banajs"
secret: "banajs"
store: new RedisStore
cookie:
path: "/"
httpOnly: true
# Routes
admin_route(app)
blog_route(app)
app.listen 8081
console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
| 219131 | #
# BanaJs
# author : dreampuf(<EMAIL>)
#
express = require('express')
app = module.exports = express.createServer()
coffeekup = require 'coffeekup'
coffeekup.tags = coffeekup.tags.concat ["feed", "subtitle", "id", "updated", "author", "name", "rights", "entry", "content"]
config = require './config'
admin_route = require('./route/admin_route')
blog_route = require('./route/blog_route')
# Configuration
app.configure ()->
app.set 'views', __dirname + '/views'
app.set 'view engine', 'coffee'
app.set 'prodir', __dirname
app.register('.coffee', coffeekup.adapters.express)
#app.use express.compiler src: __dirname + '/public', enable: ['coffeescript']
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.methodOverride()
#app.use app.router
app.use express.static(__dirname + '/public')
#app.use express.session
# key: "<KEY>"
# secret: "<KEY>"
app.use (req, res, next)->
res.local "config", config
next()
app.configure 'development', ()->
app.use express.errorHandler({ dumpExceptions: true, showStack: true })
#Session store put into third service for continue develop
MemcachedStore = require('connect-memcached')(express)
app.use express.session
secret: "banajs"
store: new MemcachedStore()
app.configure 'production', ()->
#app.use(express.errorHandler())
RedisStore = require('connect-redis')(express)
app.use express.session
key: "<KEY>"
secret: "<KEY>"
store: new RedisStore
cookie:
path: "/"
httpOnly: true
# Routes
admin_route(app)
blog_route(app)
app.listen 8081
console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
| true | #
# BanaJs
# author : dreampuf(PI:EMAIL:<EMAIL>END_PI)
#
express = require('express')
app = module.exports = express.createServer()
coffeekup = require 'coffeekup'
coffeekup.tags = coffeekup.tags.concat ["feed", "subtitle", "id", "updated", "author", "name", "rights", "entry", "content"]
config = require './config'
admin_route = require('./route/admin_route')
blog_route = require('./route/blog_route')
# Configuration
app.configure ()->
app.set 'views', __dirname + '/views'
app.set 'view engine', 'coffee'
app.set 'prodir', __dirname
app.register('.coffee', coffeekup.adapters.express)
#app.use express.compiler src: __dirname + '/public', enable: ['coffeescript']
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.methodOverride()
#app.use app.router
app.use express.static(__dirname + '/public')
#app.use express.session
# key: "PI:KEY:<KEY>END_PI"
# secret: "PI:KEY:<KEY>END_PI"
app.use (req, res, next)->
res.local "config", config
next()
app.configure 'development', ()->
app.use express.errorHandler({ dumpExceptions: true, showStack: true })
#Session store put into third service for continue develop
MemcachedStore = require('connect-memcached')(express)
app.use express.session
secret: "banajs"
store: new MemcachedStore()
app.configure 'production', ()->
#app.use(express.errorHandler())
RedisStore = require('connect-redis')(express)
app.use express.session
key: "PI:KEY:<KEY>END_PI"
secret: "PI:KEY:<KEY>END_PI"
store: new RedisStore
cookie:
path: "/"
httpOnly: true
# Routes
admin_route(app)
blog_route(app)
app.listen 8081
console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env
|
[
{
"context": "eteor.startup ->\n# MailChimpOptions.apiKey = \"9776d245abf3c7fd5a4d9c583d3f02ad-us8\"\n# MailChimpOptions.listId = \"56815b508d\"\n\nMe",
"end": 89,
"score": 0.9997510313987732,
"start": 53,
"tag": "KEY",
"value": "9776d245abf3c7fd5a4d9c583d3f02ad-us8"
},
{
"context": "Valid(email)\n return\n apiKey = \"9776d245abf3c7fd5a4d9c583d3f02ad-us8\"\n options =\n id : \"56815b508d\"\n ",
"end": 286,
"score": 0.999754786491394,
"start": 250,
"tag": "KEY",
"value": "9776d245abf3c7fd5a4d9c583d3f02ad-us8"
}
] | server/mailing.coffee | funkyeah/twmeteor | 0 | # Meteor.startup ->
# MailChimpOptions.apiKey = "9776d245abf3c7fd5a4d9c583d3f02ad-us8"
# MailChimpOptions.listId = "56815b508d"
Meteor.methods
subscribe: (email) ->
if not emailIsValid(email)
return
apiKey = "9776d245abf3c7fd5a4d9c583d3f02ad-us8"
options =
id : "56815b508d"
email:
email: email
MailChimpAPI = new MailChimp(
apiKey
version: '2.0'
)
MailChimpAPI.call "lists", "subscribe", options, (error,data)->
return
| 170512 | # Meteor.startup ->
# MailChimpOptions.apiKey = "<KEY>"
# MailChimpOptions.listId = "56815b508d"
Meteor.methods
subscribe: (email) ->
if not emailIsValid(email)
return
apiKey = "<KEY>"
options =
id : "56815b508d"
email:
email: email
MailChimpAPI = new MailChimp(
apiKey
version: '2.0'
)
MailChimpAPI.call "lists", "subscribe", options, (error,data)->
return
| true | # Meteor.startup ->
# MailChimpOptions.apiKey = "PI:KEY:<KEY>END_PI"
# MailChimpOptions.listId = "56815b508d"
Meteor.methods
subscribe: (email) ->
if not emailIsValid(email)
return
apiKey = "PI:KEY:<KEY>END_PI"
options =
id : "56815b508d"
email:
email: email
MailChimpAPI = new MailChimp(
apiKey
version: '2.0'
)
MailChimpAPI.call "lists", "subscribe", options, (error,data)->
return
|
[
{
"context": "cheKey = (uri, sort, direction, filter) ->\n \"#{uri}-#{sort}-#{direction}-#{filter}\"\n\n api =\n update: (uri) -",
"end": 331,
"score": 0.762474775314331,
"start": 316,
"tag": "KEY",
"value": "uri}-#{sort}-#{"
},
{
"context": "ection, filter) ->\n \"#{uri}-#{sort}-#{direction}-#{filter}\"\n\n api =\n update: (uri) -> mpd.update(",
"end": 344,
"score": 0.8824479579925537,
"start": 342,
"tag": "KEY",
"value": "#{"
},
{
"context": "lter) ->\n \"#{uri}-#{sort}-#{direction}-#{filter}\"\n\n api =\n update: (uri) -> mpd.update(uri)\n\n ",
"end": 350,
"score": 0.6436068415641785,
"start": 350,
"tag": "KEY",
"value": ""
}
] | frontend/app/components/library/library.coffee | zefer/mothership | 24 | mod = angular.module('mothership.library', [
'mothership.mpd'
])
mod.factory 'library', ($q, mpd) ->
'use strict'
# Cache a single library path, so the controller can paginate without fetching
# the data again.
cache =
key: null
items: null
cacheKey = (uri, sort, direction, filter) ->
"#{uri}-#{sort}-#{direction}-#{filter}"
api =
update: (uri) -> mpd.update(uri)
ls: (uri, sort, direction, filter) ->
deferred = $q.defer()
key = cacheKey(uri, sort, direction, filter)
if key == cache.key && false
# Requesting the same path, return the data from the cache.
deferred.resolve(cache.items)
else
mpd.ls(uri, sort, direction, filter).then (items) ->
deferred.resolve(items)
cache.key = key
cache.items = items
deferred.promise
| 161661 | mod = angular.module('mothership.library', [
'mothership.mpd'
])
mod.factory 'library', ($q, mpd) ->
'use strict'
# Cache a single library path, so the controller can paginate without fetching
# the data again.
cache =
key: null
items: null
cacheKey = (uri, sort, direction, filter) ->
"#{<KEY>direction}-<KEY>filter<KEY>}"
api =
update: (uri) -> mpd.update(uri)
ls: (uri, sort, direction, filter) ->
deferred = $q.defer()
key = cacheKey(uri, sort, direction, filter)
if key == cache.key && false
# Requesting the same path, return the data from the cache.
deferred.resolve(cache.items)
else
mpd.ls(uri, sort, direction, filter).then (items) ->
deferred.resolve(items)
cache.key = key
cache.items = items
deferred.promise
| true | mod = angular.module('mothership.library', [
'mothership.mpd'
])
mod.factory 'library', ($q, mpd) ->
'use strict'
# Cache a single library path, so the controller can paginate without fetching
# the data again.
cache =
key: null
items: null
cacheKey = (uri, sort, direction, filter) ->
"#{PI:KEY:<KEY>END_PIdirection}-PI:KEY:<KEY>END_PIfilterPI:KEY:<KEY>END_PI}"
api =
update: (uri) -> mpd.update(uri)
ls: (uri, sort, direction, filter) ->
deferred = $q.defer()
key = cacheKey(uri, sort, direction, filter)
if key == cache.key && false
# Requesting the same path, return the data from the cache.
deferred.resolve(cache.items)
else
mpd.ls(uri, sort, direction, filter).then (items) ->
deferred.resolve(items)
cache.key = key
cache.items = items
deferred.promise
|
[
{
"context": "for announcing downtime completion\n#\n# Author:\n# Morgan Delagrange\n#\n# URLS:\n# /broadcast/create - Send a message ",
"end": 497,
"score": 0.9998866319656372,
"start": 480,
"tag": "NAME",
"value": "Morgan Delagrange"
}
] | src/scripts/announce.coffee | Reelhouse/hubot-scripts | 9 | # Description:
# Send messages to all chat rooms.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_ANNOUNCE_ROOMS - comma-separated list of rooms
#
# Commands:
# hubot announce "<message>" - Sends a message to all hubot rooms.
# hubot announce downtime for "<service>" starting <timeframe> - Syntactic sugar for announcing downtime commencement
# hubot announce downtime complete for "<service>" - Syntactic sugar for announcing downtime completion
#
# Author:
# Morgan Delagrange
#
# URLS:
# /broadcast/create - Send a message to designated, comma-separated rooms.
module.exports = (robot) ->
if process.env.HUBOT_ANNOUNCE_ROOMS
allRooms = process.env.HUBOT_ANNOUNCE_ROOMS.split(',')
else
allRooms = []
robot.respond /announce "(.*)"/i, (msg) ->
announcement = msg.match[1]
for room in allRooms
robot.messageRoom room, announcement
robot.respond /announce downtime for "(.*)" starting (.*)/i, (msg) ->
user = msg.message.user
service = msg.match[1]
startTime = msg.match[2]
message = ["The '#{service}' service will be going down for maintenance starting #{startTime}.",
"If you have questions about this maintenance, please talk to #{user.name} in the the #{user.room} room. Thank you for your patience."]
for room in allRooms
robot.messageRoom room, message...
msg.reply "Don't forget to pause monitoring for this service."
robot.respond /announce downtime complete for "(.*)"/i, (msg) ->
service = msg.match[1]
for room in allRooms
robot.messageRoom room,
"Maintenance for the '#{service}' service is complete."
msg.reply "Don't forget to resume monitoring for this service."
robot.router.post "/broadcast/create", (req, res) ->
if req.body.rooms
rooms = req.body.rooms.split(',')
else
rooms = allRooms
for room in rooms
robot.messageRoom room, req.body.message
res.end "Message Sent"
| 221222 | # Description:
# Send messages to all chat rooms.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_ANNOUNCE_ROOMS - comma-separated list of rooms
#
# Commands:
# hubot announce "<message>" - Sends a message to all hubot rooms.
# hubot announce downtime for "<service>" starting <timeframe> - Syntactic sugar for announcing downtime commencement
# hubot announce downtime complete for "<service>" - Syntactic sugar for announcing downtime completion
#
# Author:
# <NAME>
#
# URLS:
# /broadcast/create - Send a message to designated, comma-separated rooms.
module.exports = (robot) ->
if process.env.HUBOT_ANNOUNCE_ROOMS
allRooms = process.env.HUBOT_ANNOUNCE_ROOMS.split(',')
else
allRooms = []
robot.respond /announce "(.*)"/i, (msg) ->
announcement = msg.match[1]
for room in allRooms
robot.messageRoom room, announcement
robot.respond /announce downtime for "(.*)" starting (.*)/i, (msg) ->
user = msg.message.user
service = msg.match[1]
startTime = msg.match[2]
message = ["The '#{service}' service will be going down for maintenance starting #{startTime}.",
"If you have questions about this maintenance, please talk to #{user.name} in the the #{user.room} room. Thank you for your patience."]
for room in allRooms
robot.messageRoom room, message...
msg.reply "Don't forget to pause monitoring for this service."
robot.respond /announce downtime complete for "(.*)"/i, (msg) ->
service = msg.match[1]
for room in allRooms
robot.messageRoom room,
"Maintenance for the '#{service}' service is complete."
msg.reply "Don't forget to resume monitoring for this service."
robot.router.post "/broadcast/create", (req, res) ->
if req.body.rooms
rooms = req.body.rooms.split(',')
else
rooms = allRooms
for room in rooms
robot.messageRoom room, req.body.message
res.end "Message Sent"
| true | # Description:
# Send messages to all chat rooms.
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_ANNOUNCE_ROOMS - comma-separated list of rooms
#
# Commands:
# hubot announce "<message>" - Sends a message to all hubot rooms.
# hubot announce downtime for "<service>" starting <timeframe> - Syntactic sugar for announcing downtime commencement
# hubot announce downtime complete for "<service>" - Syntactic sugar for announcing downtime completion
#
# Author:
# PI:NAME:<NAME>END_PI
#
# URLS:
# /broadcast/create - Send a message to designated, comma-separated rooms.
module.exports = (robot) ->
if process.env.HUBOT_ANNOUNCE_ROOMS
allRooms = process.env.HUBOT_ANNOUNCE_ROOMS.split(',')
else
allRooms = []
robot.respond /announce "(.*)"/i, (msg) ->
announcement = msg.match[1]
for room in allRooms
robot.messageRoom room, announcement
robot.respond /announce downtime for "(.*)" starting (.*)/i, (msg) ->
user = msg.message.user
service = msg.match[1]
startTime = msg.match[2]
message = ["The '#{service}' service will be going down for maintenance starting #{startTime}.",
"If you have questions about this maintenance, please talk to #{user.name} in the the #{user.room} room. Thank you for your patience."]
for room in allRooms
robot.messageRoom room, message...
msg.reply "Don't forget to pause monitoring for this service."
robot.respond /announce downtime complete for "(.*)"/i, (msg) ->
service = msg.match[1]
for room in allRooms
robot.messageRoom room,
"Maintenance for the '#{service}' service is complete."
msg.reply "Don't forget to resume monitoring for this service."
robot.router.post "/broadcast/create", (req, res) ->
if req.body.rooms
rooms = req.body.rooms.split(',')
else
rooms = allRooms
for room in rooms
robot.messageRoom room, req.body.message
res.end "Message Sent"
|
[
{
"context": " to generate an image\n\t\t\tres=JSZip.base64.decode(\"iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWc/KGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42//YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC\")\n\t\t\tcallback(null,res)\n\t\tdefaultImageCreator(res",
"end": 5578,
"score": 0.9996678233146667,
"start": 5234,
"tag": "KEY",
"value": "iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWc/KGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42//YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC"
}
] | coffee/docUtils.coffee | ssured/docxtemplater | 0 | fs=require('fs')
DOMParser = require('xmldom').DOMParser
XMLSerializer= require('xmldom').XMLSerializer
JSZip=require('jszip')
url=require('url')
http=require('http')
https=require('https')
DocUtils= {}
DocUtils.env= if fs.readFile? then 'node' else 'browser'
DocUtils.docX=[]
DocUtils.docXData=[]
DocUtils.getPathConfig=()->
if !DocUtils.pathConfig? then return ""
return if DocUtils.pathConfig.node? then DocUtils.pathConfig.node else DocUtils.pathConfig.browser
DocUtils.escapeRegExp= (str) ->
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
DocUtils.charMap=
'&':"&"
"'":"'"
"<":"<"
">":">"
DocUtils.wordToUtf8= (string) ->
for endChar,startChar of DocUtils.charMap
string=string.replace(new RegExp(DocUtils.escapeRegExp(startChar),"g"),endChar)
string
DocUtils.utf8ToWord= (string) ->
for startChar,endChar of DocUtils.charMap
string=string.replace(new RegExp(DocUtils.escapeRegExp(startChar),"g"),endChar)
string
DocUtils.defaultParser=(tag) ->
return {
'get':(scope) -> return scope[tag]
}
DocUtils.nl2br = (str,is_xhtml) ->
(str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
DocUtils.loadDoc= (path,options={}) ->
noDocx= if options.docx? then !options.docx else false
async=if options.async? then options.async else false
intelligentTagging=if options.intelligentTagging? then options.intelligentTagging else false
callback=if options.callback? then options.callback else null
basePath=""
if !path? then throw new Error('path not defined')
if path.indexOf('/')!=-1
totalPath= path
fileName= totalPath
else
fileName= path
if basePath=="" && DocUtils.pathConfig? #set basePath only if it wasn't set as an argument
basePath=DocUtils.getPathConfig()
totalPath= basePath+path
loadFile = (data) ->
DocUtils.docXData[fileName]=data
if noDocx==false
DocUtils.docX[fileName]=new DocxGen(data,{},{intelligentTagging:intelligentTagging})
return DocUtils.docX[fileName]
if callback?
callback(DocUtils.docXData[fileName])
if async==false
return DocUtils.docXData[fileName]
if DocUtils.env=='browser'
xhrDoc= new XMLHttpRequest()
xhrDoc.open('GET', totalPath , async)
if xhrDoc.overrideMimeType
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =(e)->
if this.readyState == 4
if this.status == 200
loadFile(this.response)
else
if callback? then callback(true)
xhrDoc.send()
else
httpRegex= new RegExp "(https?)","i"
# httpsRegex= new RegExp "(https)://"
if httpRegex.test(path)
urloptions=(url.parse(path))
options =
hostname:urloptions.hostname
path:urloptions.path
method: 'GET'
rejectUnauthorized:false
errorCallback= (e) ->
throw new Error("Error on HTTPS Call")
reqCallback= (res)->
res.setEncoding('binary')
data = ""
res.on('data', (chunk)->
data += chunk
)
res.on('end', ()->
loadFile(data))
switch urloptions.protocol
when "https:"
req = https.request(options, reqCallback).on('error',errorCallback)
when 'http:'
req = http.request(options, reqCallback).on('error',errorCallback)
req.end();
else
if async==true
fs.readFile totalPath,"binary", (err, data) ->
if err
if callback? then callback(true)
else
loadFile(data)
if callback? then callback(data)
else
try
data=fs.readFileSync(totalPath,"binary")
a=loadFile(data)
if callback? then callback(data) else return a
catch e
if callback? then callback()
DocUtils.loadHttp=(result,callback)->
if DocUtils.env=='node'
urloptions=(url.parse(result))
options =
hostname:urloptions.hostname
path:urloptions.path
method: 'GET'
rejectUnauthorized:false
errorCallback= (e) ->
callback(e)
reqCallback= (res)->
res.setEncoding('binary')
data = ""
res.on 'data',(chunk)-> data += chunk
res.on 'end',()->callback(null,data)
switch urloptions.protocol
when "https:"
req = https.request(options, reqCallback).on('error',errorCallback)
when 'http:'
req = http.request(options, reqCallback).on('error',errorCallback)
req.end()
else
xhrDoc= new XMLHttpRequest()
xhrDoc.open('GET', result , false)
if xhrDoc.overrideMimeType
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =(e)->
if this.readyState == 4
if this.status == 200
callback(null,this.response)
else
callback(true)
xhrDoc.send()
DocUtils.unsecureQrCode=(result,callback)->
if DocUtils.env=='node'
console.log 'Your are using an insecure qrcode image finder. With this function, a malicious user could read anyfile that is on the server where docxtemplater resides. The qrcode module now accepts a function as its first parameter instead of a bool see http://docxtemplater.readthedocs.org/en/latest/configuration.html#image-replacing'
if result.substr(0,5)=='http:' or result.substr(0,6)=='https:'
DocUtils.loadHttp(result,callback)
else if result.substr(0,4)=='gen:'
defaultImageCreator=(arg,callback) ->
#This is the image of an arrow, you can replace this function by whatever you want to generate an image
res=JSZip.base64.decode("iVBORw0KGgoAAAANSUhEUgAAABcAAAAXCAIAAABvSEP3AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACXSURBVDhPtY7BDYAwDAMZhCf7b8YMxeCoatOQJhWc/KGxT2zlCyaWcz8Y+X7Bs1TFVJSwIHIYyFkQufWIRVX9cNJyW1QpEo4rixaEe7JuQagAUctb7ZFYFh5MVJPBe84CVBnB42//YsZRgKjFDBVg3cI9WbRwXLktQJX8cNIiFhM1ZuTWk7PIYSBhkVcLzwIiCjCxhCjlAkBqYnqFoQQ2AAAAAElFTkSuQmCC")
callback(null,res)
defaultImageCreator(result,callback)
else if result!=null and result!= undefined and result.substr(0,22)!= 'error decoding QR Code'
if DocUtils.env=='node'
fs.readFile(DocUtils.getPathConfig()+result,callback)
else
DocUtils.loadHttp(DocUtils.getPathConfig()+result,callback)
else
callback()
DocUtils.tags=
start:'{'
end:'}'
DocUtils.clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = DocUtils.clone obj[key]
return newInstance
DocUtils.xml2Str = (xmlNode) ->
if xmlNode==undefined
throw new Error("xmlNode undefined!")
try
if global?
a= new XMLSerializer()
content= a.serializeToString(xmlNode)
# Gecko- and Webkit-based browsers (Firefox, Chrome), Opera.
else
content=(new XMLSerializer()).serializeToString(xmlNode);
catch e
content= xmlNode.xml;
content= content.replace /\x20xmlns=""/g, '' #remove all added xmlns="" (these cause the file to be corrupt and was a problem for firefox)
DocUtils.Str2xml= (str) ->
if DOMParser #Chrome, Firefox, and modern browsers
parser=new DOMParser();
xmlDoc=parser.parseFromString(str,"text/xml")
else # Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async=false
xmlDoc.loadXML(str)
xmlDoc
DocUtils.replaceFirstFrom = (string,search,replace,from) -> #replace first occurence of search (can be regex) after *from* offset
string.substr(0,from)+string.substr(from).replace(search,replace)
DocUtils.encode_utf8 = (s)->
unescape(encodeURIComponent(s))
DocUtils.convert_spaces= (s) ->
s.replace(new RegExp(String.fromCharCode(160),"g")," ")
DocUtils.decode_utf8= (s) ->
try
if s==undefined then return undefined
return decodeURIComponent(escape(DocUtils.convert_spaces(s))) #replace Ascii 160 space by the normal space, Ascii 32
catch e
console.log s
console.log 'could not decode'
throw new Error('end')
DocUtils.base64encode= (b) ->
btoa(unescape(encodeURIComponent(b)))
DocUtils.preg_match_all= (regex, content) ->
###regex is a string, content is the content. It returns an array of all matches with their offset, for example:
regex=la
content=lolalolilala
returns: [{0:'la',offset:2},{0:'la',offset:8},{0:'la',offset:10}]
###
regex= (new RegExp(regex,'g')) unless (typeof regex=='object')
matchArray= []
replacer = (match,pn ..., offset, string)->
pn.unshift match #add match so that pn[0] = whole match, pn[1]= first parenthesis,...
pn.offset= offset
matchArray.push pn
content.replace regex,replacer
matchArray
DocUtils.sizeOfObject = (obj) ->
size=0
log = 0
for key of obj
size++
size
DocUtils.maxArray = (a) -> Math.max.apply(null, a)
module.exports=DocUtils
| 215345 | fs=require('fs')
DOMParser = require('xmldom').DOMParser
XMLSerializer= require('xmldom').XMLSerializer
JSZip=require('jszip')
url=require('url')
http=require('http')
https=require('https')
DocUtils= {}
DocUtils.env= if fs.readFile? then 'node' else 'browser'
DocUtils.docX=[]
DocUtils.docXData=[]
DocUtils.getPathConfig=()->
if !DocUtils.pathConfig? then return ""
return if DocUtils.pathConfig.node? then DocUtils.pathConfig.node else DocUtils.pathConfig.browser
DocUtils.escapeRegExp= (str) ->
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
DocUtils.charMap=
'&':"&"
"'":"'"
"<":"<"
">":">"
DocUtils.wordToUtf8= (string) ->
for endChar,startChar of DocUtils.charMap
string=string.replace(new RegExp(DocUtils.escapeRegExp(startChar),"g"),endChar)
string
DocUtils.utf8ToWord= (string) ->
for startChar,endChar of DocUtils.charMap
string=string.replace(new RegExp(DocUtils.escapeRegExp(startChar),"g"),endChar)
string
DocUtils.defaultParser=(tag) ->
return {
'get':(scope) -> return scope[tag]
}
DocUtils.nl2br = (str,is_xhtml) ->
(str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
DocUtils.loadDoc= (path,options={}) ->
noDocx= if options.docx? then !options.docx else false
async=if options.async? then options.async else false
intelligentTagging=if options.intelligentTagging? then options.intelligentTagging else false
callback=if options.callback? then options.callback else null
basePath=""
if !path? then throw new Error('path not defined')
if path.indexOf('/')!=-1
totalPath= path
fileName= totalPath
else
fileName= path
if basePath=="" && DocUtils.pathConfig? #set basePath only if it wasn't set as an argument
basePath=DocUtils.getPathConfig()
totalPath= basePath+path
loadFile = (data) ->
DocUtils.docXData[fileName]=data
if noDocx==false
DocUtils.docX[fileName]=new DocxGen(data,{},{intelligentTagging:intelligentTagging})
return DocUtils.docX[fileName]
if callback?
callback(DocUtils.docXData[fileName])
if async==false
return DocUtils.docXData[fileName]
if DocUtils.env=='browser'
xhrDoc= new XMLHttpRequest()
xhrDoc.open('GET', totalPath , async)
if xhrDoc.overrideMimeType
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =(e)->
if this.readyState == 4
if this.status == 200
loadFile(this.response)
else
if callback? then callback(true)
xhrDoc.send()
else
httpRegex= new RegExp "(https?)","i"
# httpsRegex= new RegExp "(https)://"
if httpRegex.test(path)
urloptions=(url.parse(path))
options =
hostname:urloptions.hostname
path:urloptions.path
method: 'GET'
rejectUnauthorized:false
errorCallback= (e) ->
throw new Error("Error on HTTPS Call")
reqCallback= (res)->
res.setEncoding('binary')
data = ""
res.on('data', (chunk)->
data += chunk
)
res.on('end', ()->
loadFile(data))
switch urloptions.protocol
when "https:"
req = https.request(options, reqCallback).on('error',errorCallback)
when 'http:'
req = http.request(options, reqCallback).on('error',errorCallback)
req.end();
else
if async==true
fs.readFile totalPath,"binary", (err, data) ->
if err
if callback? then callback(true)
else
loadFile(data)
if callback? then callback(data)
else
try
data=fs.readFileSync(totalPath,"binary")
a=loadFile(data)
if callback? then callback(data) else return a
catch e
if callback? then callback()
DocUtils.loadHttp=(result,callback)->
if DocUtils.env=='node'
urloptions=(url.parse(result))
options =
hostname:urloptions.hostname
path:urloptions.path
method: 'GET'
rejectUnauthorized:false
errorCallback= (e) ->
callback(e)
reqCallback= (res)->
res.setEncoding('binary')
data = ""
res.on 'data',(chunk)-> data += chunk
res.on 'end',()->callback(null,data)
switch urloptions.protocol
when "https:"
req = https.request(options, reqCallback).on('error',errorCallback)
when 'http:'
req = http.request(options, reqCallback).on('error',errorCallback)
req.end()
else
xhrDoc= new XMLHttpRequest()
xhrDoc.open('GET', result , false)
if xhrDoc.overrideMimeType
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =(e)->
if this.readyState == 4
if this.status == 200
callback(null,this.response)
else
callback(true)
xhrDoc.send()
DocUtils.unsecureQrCode=(result,callback)->
if DocUtils.env=='node'
console.log 'Your are using an insecure qrcode image finder. With this function, a malicious user could read anyfile that is on the server where docxtemplater resides. The qrcode module now accepts a function as its first parameter instead of a bool see http://docxtemplater.readthedocs.org/en/latest/configuration.html#image-replacing'
if result.substr(0,5)=='http:' or result.substr(0,6)=='https:'
DocUtils.loadHttp(result,callback)
else if result.substr(0,4)=='gen:'
defaultImageCreator=(arg,callback) ->
#This is the image of an arrow, you can replace this function by whatever you want to generate an image
res=JSZip.base64.decode("<KEY>")
callback(null,res)
defaultImageCreator(result,callback)
else if result!=null and result!= undefined and result.substr(0,22)!= 'error decoding QR Code'
if DocUtils.env=='node'
fs.readFile(DocUtils.getPathConfig()+result,callback)
else
DocUtils.loadHttp(DocUtils.getPathConfig()+result,callback)
else
callback()
DocUtils.tags=
start:'{'
end:'}'
DocUtils.clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = DocUtils.clone obj[key]
return newInstance
DocUtils.xml2Str = (xmlNode) ->
if xmlNode==undefined
throw new Error("xmlNode undefined!")
try
if global?
a= new XMLSerializer()
content= a.serializeToString(xmlNode)
# Gecko- and Webkit-based browsers (Firefox, Chrome), Opera.
else
content=(new XMLSerializer()).serializeToString(xmlNode);
catch e
content= xmlNode.xml;
content= content.replace /\x20xmlns=""/g, '' #remove all added xmlns="" (these cause the file to be corrupt and was a problem for firefox)
DocUtils.Str2xml= (str) ->
if DOMParser #Chrome, Firefox, and modern browsers
parser=new DOMParser();
xmlDoc=parser.parseFromString(str,"text/xml")
else # Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async=false
xmlDoc.loadXML(str)
xmlDoc
DocUtils.replaceFirstFrom = (string,search,replace,from) -> #replace first occurence of search (can be regex) after *from* offset
string.substr(0,from)+string.substr(from).replace(search,replace)
DocUtils.encode_utf8 = (s)->
unescape(encodeURIComponent(s))
DocUtils.convert_spaces= (s) ->
s.replace(new RegExp(String.fromCharCode(160),"g")," ")
DocUtils.decode_utf8= (s) ->
try
if s==undefined then return undefined
return decodeURIComponent(escape(DocUtils.convert_spaces(s))) #replace Ascii 160 space by the normal space, Ascii 32
catch e
console.log s
console.log 'could not decode'
throw new Error('end')
DocUtils.base64encode= (b) ->
btoa(unescape(encodeURIComponent(b)))
DocUtils.preg_match_all= (regex, content) ->
###regex is a string, content is the content. It returns an array of all matches with their offset, for example:
regex=la
content=lolalolilala
returns: [{0:'la',offset:2},{0:'la',offset:8},{0:'la',offset:10}]
###
regex= (new RegExp(regex,'g')) unless (typeof regex=='object')
matchArray= []
replacer = (match,pn ..., offset, string)->
pn.unshift match #add match so that pn[0] = whole match, pn[1]= first parenthesis,...
pn.offset= offset
matchArray.push pn
content.replace regex,replacer
matchArray
DocUtils.sizeOfObject = (obj) ->
size=0
log = 0
for key of obj
size++
size
DocUtils.maxArray = (a) -> Math.max.apply(null, a)
module.exports=DocUtils
| true | fs=require('fs')
DOMParser = require('xmldom').DOMParser
XMLSerializer= require('xmldom').XMLSerializer
JSZip=require('jszip')
url=require('url')
http=require('http')
https=require('https')
DocUtils= {}
DocUtils.env= if fs.readFile? then 'node' else 'browser'
DocUtils.docX=[]
DocUtils.docXData=[]
DocUtils.getPathConfig=()->
if !DocUtils.pathConfig? then return ""
return if DocUtils.pathConfig.node? then DocUtils.pathConfig.node else DocUtils.pathConfig.browser
DocUtils.escapeRegExp= (str) ->
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
DocUtils.charMap=
'&':"&"
"'":"'"
"<":"<"
">":">"
DocUtils.wordToUtf8= (string) ->
for endChar,startChar of DocUtils.charMap
string=string.replace(new RegExp(DocUtils.escapeRegExp(startChar),"g"),endChar)
string
DocUtils.utf8ToWord= (string) ->
for startChar,endChar of DocUtils.charMap
string=string.replace(new RegExp(DocUtils.escapeRegExp(startChar),"g"),endChar)
string
DocUtils.defaultParser=(tag) ->
return {
'get':(scope) -> return scope[tag]
}
DocUtils.nl2br = (str,is_xhtml) ->
(str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
DocUtils.loadDoc= (path,options={}) ->
noDocx= if options.docx? then !options.docx else false
async=if options.async? then options.async else false
intelligentTagging=if options.intelligentTagging? then options.intelligentTagging else false
callback=if options.callback? then options.callback else null
basePath=""
if !path? then throw new Error('path not defined')
if path.indexOf('/')!=-1
totalPath= path
fileName= totalPath
else
fileName= path
if basePath=="" && DocUtils.pathConfig? #set basePath only if it wasn't set as an argument
basePath=DocUtils.getPathConfig()
totalPath= basePath+path
loadFile = (data) ->
DocUtils.docXData[fileName]=data
if noDocx==false
DocUtils.docX[fileName]=new DocxGen(data,{},{intelligentTagging:intelligentTagging})
return DocUtils.docX[fileName]
if callback?
callback(DocUtils.docXData[fileName])
if async==false
return DocUtils.docXData[fileName]
if DocUtils.env=='browser'
xhrDoc= new XMLHttpRequest()
xhrDoc.open('GET', totalPath , async)
if xhrDoc.overrideMimeType
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =(e)->
if this.readyState == 4
if this.status == 200
loadFile(this.response)
else
if callback? then callback(true)
xhrDoc.send()
else
httpRegex= new RegExp "(https?)","i"
# httpsRegex= new RegExp "(https)://"
if httpRegex.test(path)
urloptions=(url.parse(path))
options =
hostname:urloptions.hostname
path:urloptions.path
method: 'GET'
rejectUnauthorized:false
errorCallback= (e) ->
throw new Error("Error on HTTPS Call")
reqCallback= (res)->
res.setEncoding('binary')
data = ""
res.on('data', (chunk)->
data += chunk
)
res.on('end', ()->
loadFile(data))
switch urloptions.protocol
when "https:"
req = https.request(options, reqCallback).on('error',errorCallback)
when 'http:'
req = http.request(options, reqCallback).on('error',errorCallback)
req.end();
else
if async==true
fs.readFile totalPath,"binary", (err, data) ->
if err
if callback? then callback(true)
else
loadFile(data)
if callback? then callback(data)
else
try
data=fs.readFileSync(totalPath,"binary")
a=loadFile(data)
if callback? then callback(data) else return a
catch e
if callback? then callback()
DocUtils.loadHttp=(result,callback)->
if DocUtils.env=='node'
urloptions=(url.parse(result))
options =
hostname:urloptions.hostname
path:urloptions.path
method: 'GET'
rejectUnauthorized:false
errorCallback= (e) ->
callback(e)
reqCallback= (res)->
res.setEncoding('binary')
data = ""
res.on 'data',(chunk)-> data += chunk
res.on 'end',()->callback(null,data)
switch urloptions.protocol
when "https:"
req = https.request(options, reqCallback).on('error',errorCallback)
when 'http:'
req = http.request(options, reqCallback).on('error',errorCallback)
req.end()
else
xhrDoc= new XMLHttpRequest()
xhrDoc.open('GET', result , false)
if xhrDoc.overrideMimeType
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =(e)->
if this.readyState == 4
if this.status == 200
callback(null,this.response)
else
callback(true)
xhrDoc.send()
DocUtils.unsecureQrCode=(result,callback)->
if DocUtils.env=='node'
console.log 'Your are using an insecure qrcode image finder. With this function, a malicious user could read anyfile that is on the server where docxtemplater resides. The qrcode module now accepts a function as its first parameter instead of a bool see http://docxtemplater.readthedocs.org/en/latest/configuration.html#image-replacing'
if result.substr(0,5)=='http:' or result.substr(0,6)=='https:'
DocUtils.loadHttp(result,callback)
else if result.substr(0,4)=='gen:'
defaultImageCreator=(arg,callback) ->
#This is the image of an arrow, you can replace this function by whatever you want to generate an image
res=JSZip.base64.decode("PI:KEY:<KEY>END_PI")
callback(null,res)
defaultImageCreator(result,callback)
else if result!=null and result!= undefined and result.substr(0,22)!= 'error decoding QR Code'
if DocUtils.env=='node'
fs.readFile(DocUtils.getPathConfig()+result,callback)
else
DocUtils.loadHttp(DocUtils.getPathConfig()+result,callback)
else
callback()
DocUtils.tags=
start:'{'
end:'}'
DocUtils.clone = (obj) ->
if not obj? or typeof obj isnt 'object'
return obj
if obj instanceof Date
return new Date(obj.getTime())
if obj instanceof RegExp
flags = ''
flags += 'g' if obj.global?
flags += 'i' if obj.ignoreCase?
flags += 'm' if obj.multiline?
flags += 'y' if obj.sticky?
return new RegExp(obj.source, flags)
newInstance = new obj.constructor()
for key of obj
newInstance[key] = DocUtils.clone obj[key]
return newInstance
DocUtils.xml2Str = (xmlNode) ->
if xmlNode==undefined
throw new Error("xmlNode undefined!")
try
if global?
a= new XMLSerializer()
content= a.serializeToString(xmlNode)
# Gecko- and Webkit-based browsers (Firefox, Chrome), Opera.
else
content=(new XMLSerializer()).serializeToString(xmlNode);
catch e
content= xmlNode.xml;
content= content.replace /\x20xmlns=""/g, '' #remove all added xmlns="" (these cause the file to be corrupt and was a problem for firefox)
DocUtils.Str2xml= (str) ->
if DOMParser #Chrome, Firefox, and modern browsers
parser=new DOMParser();
xmlDoc=parser.parseFromString(str,"text/xml")
else # Internet Explorer
xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async=false
xmlDoc.loadXML(str)
xmlDoc
DocUtils.replaceFirstFrom = (string,search,replace,from) -> #replace first occurence of search (can be regex) after *from* offset
string.substr(0,from)+string.substr(from).replace(search,replace)
DocUtils.encode_utf8 = (s)->
unescape(encodeURIComponent(s))
DocUtils.convert_spaces= (s) ->
s.replace(new RegExp(String.fromCharCode(160),"g")," ")
DocUtils.decode_utf8= (s) ->
try
if s==undefined then return undefined
return decodeURIComponent(escape(DocUtils.convert_spaces(s))) #replace Ascii 160 space by the normal space, Ascii 32
catch e
console.log s
console.log 'could not decode'
throw new Error('end')
DocUtils.base64encode= (b) ->
btoa(unescape(encodeURIComponent(b)))
DocUtils.preg_match_all= (regex, content) ->
###regex is a string, content is the content. It returns an array of all matches with their offset, for example:
regex=la
content=lolalolilala
returns: [{0:'la',offset:2},{0:'la',offset:8},{0:'la',offset:10}]
###
regex= (new RegExp(regex,'g')) unless (typeof regex=='object')
matchArray= []
replacer = (match,pn ..., offset, string)->
pn.unshift match #add match so that pn[0] = whole match, pn[1]= first parenthesis,...
pn.offset= offset
matchArray.push pn
content.replace regex,replacer
matchArray
DocUtils.sizeOfObject = (obj) ->
size=0
log = 0
for key of obj
size++
size
DocUtils.maxArray = (a) -> Math.max.apply(null, a)
module.exports=DocUtils
|
[
{
"context": ":\n\t\tclientID: '1467152086895015'\n\t\tclientSecret: '8d15d8dd0acf82a4ea41d2612a4c6e2b'\n\t\tcallbackURL: 'http://anketa.co/auth/facebook/c",
"end": 108,
"score": 0.9996171593666077,
"start": 76,
"tag": "KEY",
"value": "8d15d8dd0acf82a4ea41d2612a4c6e2b"
},
{
"context": "lientPublic: 'CBAPCCKCEBABABABA'\n\t\tclientSecret: '6CECEBFDA04C0B5F718576B2'\n\t\tcallbackURL: 'http://anketa.co/auth/odnoklassn",
"end": 309,
"score": 0.9995847940444946,
"start": 285,
"tag": "KEY",
"value": "6CECEBFDA04C0B5F718576B2"
}
] | meta/socialConfig.coffee | winnlab/Polpharma | 0 | module.exports =
facebook:
clientID: '1467152086895015'
clientSecret: '8d15d8dd0acf82a4ea41d2612a4c6e2b'
callbackURL: 'http://anketa.co/auth/facebook/callback'
vk:
apiId: 4542267
odnoklassniki:
clientID: '1101082112'
clientPublic: 'CBAPCCKCEBABABABA'
clientSecret: '6CECEBFDA04C0B5F718576B2'
callbackURL: 'http://anketa.co/auth/odnoklassniki/callback' | 141144 | module.exports =
facebook:
clientID: '1467152086895015'
clientSecret: '<KEY>'
callbackURL: 'http://anketa.co/auth/facebook/callback'
vk:
apiId: 4542267
odnoklassniki:
clientID: '1101082112'
clientPublic: 'CBAPCCKCEBABABABA'
clientSecret: '<KEY>'
callbackURL: 'http://anketa.co/auth/odnoklassniki/callback' | true | module.exports =
facebook:
clientID: '1467152086895015'
clientSecret: 'PI:KEY:<KEY>END_PI'
callbackURL: 'http://anketa.co/auth/facebook/callback'
vk:
apiId: 4542267
odnoklassniki:
clientID: '1101082112'
clientPublic: 'CBAPCCKCEBABABABA'
clientSecret: 'PI:KEY:<KEY>END_PI'
callbackURL: 'http://anketa.co/auth/odnoklassniki/callback' |
[
{
"context": "ion\", (done) ->\n data =\n name: \"test\"\n slug: \"test\"\n docType: \"A",
"end": 874,
"score": 0.7311253547668457,
"start": 870,
"tag": "NAME",
"value": "test"
},
{
"context": " docType: \"Application\"\n password: \"token\"\n permissions:\n \"All\":\n",
"end": 964,
"score": 0.9991675615310669,
"start": 959,
"tag": "PASSWORD",
"value": "token"
},
{
"context": " #before (done) ->\n #Author.create name: \"John\", (err, author) =>\n #@author = author\n",
"end": 25641,
"score": 0.9986664056777954,
"start": 25637,
"tag": "NAME",
"value": "John"
},
{
"context": ">\n data =\n to: \"test@cozycloud.cc\"\n from: \"Cozy-test <test@cozyc",
"end": 26928,
"score": 0.9999266266822815,
"start": 26911,
"tag": "EMAIL",
"value": "test@cozycloud.cc"
},
{
"context": "zycloud.cc\"\n from: \"Cozy-test <test@cozycloud.cc>\"\n subject: \"Test jugglingdb\"\n",
"end": 26985,
"score": 0.99992835521698,
"start": 26968,
"tag": "EMAIL",
"value": "test@cozycloud.cc"
},
{
"context": " data =\n from: \"Cozy-test <test@cozycloud.cc>\"\n subject: \"Test jugglingdb\"\n",
"end": 27448,
"score": 0.9999281764030457,
"start": 27431,
"tag": "EMAIL",
"value": "test@cozycloud.cc"
},
{
"context": ">\n data =\n to: \"test@cozycloud.cc\"\n subject: \"Test jugglingdb\"\n ",
"end": 27906,
"score": 0.9999266862869263,
"start": 27889,
"tag": "EMAIL",
"value": "test@cozycloud.cc"
}
] | tests.coffee | aenario/jugglingdb-cozy-adapter | 2 | fs = require "fs"
should = require 'should'
async = require 'async'
http = require 'http'
Client = require("request-json").JsonClient
Schema = require('jugglingdb').Schema
CozyAdapter = require('./src/cozy_data_system')
client = new Client "http://localhost:9101/"
schema = new Schema 'memory'
schema.settings = {}
process.env.NAME = "test"
process.env.TOKEN = "token"
indexerPort = if process.env.NODE_ENV is 'test' then 9092 else 9102
require("./src/cozy_data_system").initialize(schema)
client.setBasicAuth "test", "token"
Note = schema.define 'Note',
title:
type: String
content:
type: Schema.Text
author:
type: String
MailBox = schema.define 'MailBox',
name:
type: String
describe "Create application with all permissions", ->
it "When I create application", (done) ->
data =
name: "test"
slug: "test"
docType: "Application"
password: "token"
permissions:
"All":
description: "..."
client.setBasicAuth "home", "token"
client.post 'data/', data, (error, response, body) =>
@response = response
@error = error
done()
it "Then no error should be returned", ->
should.not.exist @error
it "And 201 should be return as response code", ->
@response.statusCode.should.equal 201
describe "Existence", ->
before (done) ->
client.del "data/321/", (error, response, body) ->
client.setBasicAuth "test", "token"
data =
value: "created value"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Check Existence of a Document that does not exist in database", ->
it "When I check existence of Document with id 123", \
(done) ->
Note.exists 123, (err, isExist) =>
should.not.exist err
@isExist = isExist
done()
it "Then false should be returned", ->
@isExist.should.not.be.ok
describe "Check Existence of a Document that does exist in database", ->
it "When I check existence of Document with id 321", \
(done) ->
Note.exists 321, (err, isExist) =>
should.not.exist err
@isExist = isExist
done()
it "Then true should be returned", ->
@isExist.should.be.ok
describe "Find", ->
before (done) ->
client.post 'data/321/',
title: "my note"
content: "my content"
docType: "Note"
, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Find a note that does not exist in database", ->
it "When I claim note with id 123", (done) ->
Note.find 123, (err, note) =>
@note = note
done()
it "Then null should be returned", ->
should.not.exist @note
describe "Find a note that does exist in database", ->
it "When I claim note with id 321", (done) ->
Note.find 321, (err, note) =>
@note = note
done()
it "Then I should retrieve my note ", ->
should.exist @note
@note.title.should.equal "my note"
@note.content.should.equal "my content"
describe "Create", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
client.del "data/987/", (error, response, body) ->
done()
describe "Try to create a Document existing in Database", ->
after ->
@err = null
@note = null
it "When create a document with id 321", (done) ->
Note.create { id: "321", "content":"created value"}, \
(err, note) =>
@err = err
@note = note
done()
it "Then an error is returned", ->
should.exist @err
describe "Create a new Document with a given id", ->
before ->
@id = "987"
after ->
@err = null
@note = null
it "When I create a document with id 987", (done) ->
Note.create { id: @id, "content": "new note" }, (err, note) =>
@err = err
@note = note
done()
it "Then this should be set on document", ->
should.not.exist @err
should.exist @note
@note.id.should.equal @id
it "And the Document with id 987 should exist in Database", (done) ->
Note.exists @id, (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the Document in DB should equal the sent Document", (done) ->
Note.find @id, (err, note) =>
should.not.exist err
note.id.should.equal @id
note.content.should.equal "new note"
done()
describe "Create a new Document without an id", ->
before ->
@id = null
after (done) ->
@note.destroy =>
@err = null
@note = null
done()
it "When I create a document without an id", (done) ->
Note.create { "title": "cool note", "content": "new note" }, \
(err, note) =>
@err = err if err
@note = note
done()
it "Then the id of the new Document should be returned", ->
should.not.exist @err
should.exist @note.id
@id = @note.id
it "And the Document should exist in Database", (done) ->
Note.exists @id, (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the Document in DB should equal the sent Document", (done) ->
Note.find @id, (err, note) =>
should.not.exist err
note.id.should.equal @id
note.content.should.equal "new note"
done()
describe "Create a many documents without an id", ->
before ->
@ids = []
after (done) ->
@note1.destroy =>
@note2.destroy =>
@note3.destroy =>
done()
it "When I create a document without an id", (done) ->
dataList = [
{ "title": "cool note many 01", "content": "new note 01" }
{ "title": "cool note many 02", "content": "new note 02" }
{ "title": "cool note many 03", "content": "new note 03" }
]
Note.createMany dataList, (err, ids) =>
@err = err if err
@ids = ids
done()
it "Then the ids of the new documents should be returned", ->
should.not.exist @err
should.exist @ids
@ids.length.should.equal 3
it "And the Document should exist in Database", (done) ->
Note.exists @ids[0], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
Note.exists @ids[1], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
Note.exists @ids[2], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the documents in DB should equal the sent document", (done) ->
Note.find @ids[0], (err, note) =>
should.not.exist err
note.id.should.equal @ids[0]
note.content.should.equal "new note 01"
@note1 = note
Note.find @ids[1], (err, note) =>
should.not.exist err
note.id.should.equal @ids[1]
note.content.should.equal "new note 02"
@note2 = note
Note.find @ids[2], (err, note) =>
should.not.exist err
note.id.should.equal @ids[2]
note.content.should.equal "new note 03"
@note3 = note
done()
describe "Update", ->
before (done) ->
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
@note = new Note data
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Try to Update a Document that doesn't exist", ->
after ->
@err = null
it "When I update a document with id 123", (done) ->
@note.id = "123"
@note.save (err) =>
@err = err
done()
it "Then an error is returned", ->
should.exist @err
describe "Update a Document", ->
it "When I update document with id 321", (done) ->
@note.id = "321"
@note.title = "my new title"
@note.save (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And the old document must have been replaced in DB", (done) ->
Note.find @note.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "321"
updatedNote.title.should.equal "my new title"
done()
describe "Update attributes", ->
before (done) ->
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
@note = new Note data
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Try to update attributes of a document that doesn't exist", ->
after ->
@err = null
it "When I update a document with id 123", (done) ->
@note.updateAttributes title: "my new title", (err) =>
@err = err
done()
it "Then an error is returned", ->
should.exist @err
describe "Update a Document", ->
it "When I update document with id 321", (done) ->
@note.id = "321"
@note.updateAttributes title: "my new title", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And the old document must have been replaced in DB", (done) ->
Note.find @note.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "321"
updatedNote.title.should.equal "my new title"
done()
describe "Upsert attributes", ->
after (done) ->
client.del "data/654/", (error, response, body) ->
done()
describe "Upsert a non existing document", ->
it "When I upsert document with id 654", (done) ->
@data =
id: "654"
title: "my note"
content: "my content"
Note.updateOrCreate @data, (err) =>
@err = err
done()
it "Then no error should be returned.", ->
should.not.exist @err
it "And the document with id 654 should exist in Database", (done) ->
Note.find @data.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "654"
updatedNote.title.should.equal "my note"
done()
describe "Upsert an existing Document", ->
it "When I upsert document with id 654", (done) ->
@data =
id: "654"
title: "my new title"
Note.updateOrCreate @data, (err, note) =>
should.not.exist note
@err = err
done()
it "Then no data should be returned", ->
should.not.exist @err
it "And the document with id 654 should be updated", (done) ->
Note.find @data.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "654"
updatedNote.title.should.equal "my new title"
done()
describe "Delete", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
client.del "data/987/", (error, response, body) ->
done()
describe "Deletes a document that is not in Database", ->
it "When I delete Document with id 123", (done) ->
note = new Note id:123
note.destroy (err) =>
@err = err
done()
it "Then an error should be returned", ->
should.exist @err
describe "Deletes a document from database", ->
it "When I delete document with id 321", (done) ->
note = new Note id:321
note.destroy (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And Document with id 321 shouldn't exist in Database", (done) ->
Note.exists 321, (err, isExist) =>
isExist.should.not.be.ok
done()
### Indexation ###
ids = []
dragonNoteId = "0"
createNoteFunction = (title, content, author) ->
(callback) ->
if author? then authorId = author.id else authorId = null
data =
title: title
content: content
author: authorId
Note.create data, (err, note) ->
ids.push note.id
dragonNoteId = note.id if title is "Note 02"
note.index ["title", "content"], (err) ->
callback()
createTaskFunction = (description) ->
(callback) ->
client.post 'data/', {
description: "description"
docType: "task"
} , (error, response, body) ->
callback()
fakeServer = (json, code=200, callback=null) ->
http.createServer (req, res) ->
body = ""
req.on 'data', (chunk) ->
body += chunk
req.on 'end', ->
if callback?
data = JSON.parse body if body? and body.length > 0
code = callback req.url, data
res.writeHead code, 'Content-Type': 'application/json'
res.end(JSON.stringify json)
deleteNoteFunction = (id) ->
(callback) ->
client.del "data/#{id}/", (err) -> callback()
describe "Search features", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
funcs = []
for id in ids
funcs.push deleteNoteFunction(id)
async.series funcs, ->
ids = []
done()
describe "index", ->
before (done) ->
client.del "data/index/clear-all/", (err, response) ->
done()
it "When given I index four notes", (done) ->
async.series [
createNoteFunction "Note 01", "little stories begin"
createNoteFunction "Note 02", "great dragons are coming"
createNoteFunction "Note 03", "small hobbits are afraid"
createNoteFunction "Note 04", "such as humans"
], =>
data = ids: [dragonNoteId]
@indexer = fakeServer data, 200, (url, body) ->
if url is '/index/'
should.exist body.fields
should.exist body.doc
should.exist body.doc.docType
200
else if url is '/search/'
should.exist body.query
body.query.should.equal "dragons"
200
else 204
@indexer.listen indexerPort
setTimeout done, 500
it "And I send a request to search the notes containing dragons", \
(done) ->
Note.search "dragons", (err, notes) =>
@notes = notes
@indexer.close()
done()
it "Then result is the second note I created", ->
@notes.length.should.equal 1
@notes[0].title.should.equal "Note 02"
@notes[0].content.should.equal "great dragons are coming"
describe "retrieve notes with result numbers", ->
before (done) ->
client.del "data/index/clear-all/", (err, response) ->
done()
it "When given I index four notes", (done) ->
data = ids: [dragonNoteId], numResults: 1
@indexer = fakeServer data, 200, (url, body) ->
if url is '/index/'
should.exist body.fields
should.exist body.doc
should.exist body.doc.docType
200
else if url is '/search/'
should.exist body.query
body.query.should.equal "dragons"
200
else 204
@indexer.listen indexerPort
setTimeout done, 500
it "When I search again with the options", (done) ->
options =
query: "dragons"
numPage: 1
numByPage: 10
Note.search options, (err, notes) =>
@notes = notes
@indexer.close()
done()
it "Then result should be made of the results themselves and the total number of results", ->
{results, numResults} = @notes
should.exist results
should.exist numResults
results.length.should.equal 1
results[0].title.should.equal "Note 02"
results[0].content.should.equal "great dragons are coming"
numResults.should.equal 1
### Attachments ###
describe "Attachments", ->
before (done) ->
@note = new Note id: 321
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Add an attachment", ->
it "When I add an attachment", (done) ->
@note.attachFile "./test.png", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Retrieve an attachment", ->
it "When I claim this attachment", (done) ->
stream = @note.getFile "test.png", -> done()
stream.pipe fs.createWriteStream('./test-get.png')
it "Then I got the same file I attached before", ->
fileStats = fs.statSync('./test.png')
resultStats = fs.statSync('./test-get.png')
resultStats.size.should.equal fileStats.size
describe "Remove an attachment", ->
it "When I remove this attachment", (done) ->
@note.removeFile "test.png", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "When I claim this attachment", (done) ->
stream = @note.getFile "test.png", (err) =>
@err = err
done()
stream.pipe fs.createWriteStream('./test-get.png')
it "Then I got an error", ->
should.exist @err
checkNoError = ->
it "Then no error should be returned", ->
should.not.exist @err
checkError = ->
it "Then error should be returned", ->
should.exist @err
describe "Requests", ->
before (done) ->
async.series [
createNoteFunction "Note 01", "little stories begin"
createNoteFunction "Note 02", "great dragons are coming"
createNoteFunction "Note 03", "small hobbits are afraid"
createNoteFunction "Note 04", "such as humans"
createTaskFunction "Task 01"
createTaskFunction "Task 02"
createTaskFunction "Task 03"
], ->
done()
after (done) ->
funcs = []
for id in ids
funcs.push deleteNoteFunction(id)
async.series funcs, ->
ids = []
done()
describe "index", ->
describe "View creation", ->
describe "Creation of the first view + design document creation", ->
it "When I send a request to create view every_docs", (done) ->
delete @err
@map = (doc) ->
emit doc._id, doc
return
Note.defineRequest "every_notes", @map, (err) ->
should.not.exist err
done()
checkNoError()
describe "Access to a view without option", ->
describe "Access to a non existing view", ->
it "When I send a request to access view dont-exist", (done) ->
delete @err
Note.request "dont-exist", (err, notes) =>
@err = err
should.exist err
done()
checkError()
describe "Access to an existing view : every_notes", (done) ->
it "When I send a request to access view every_docs", (done) ->
delete @err
Note.request "every_notes", (err, notes) =>
@notes = notes
done()
it "Then I should have 4 documents returned", ->
@notes.should.have.length 4
describe "Access to a doc from a view : every_notes", (done) ->
it "When I send a request to access doc 3 from every_docs", \
(done) ->
delete @err
Note.request "every_notes", {key: ids[3]}, (err, notes) =>
@notes = notes
done()
it "Then I should have 1 documents returned", ->
@notes.should.have.length 1
@notes[0].id.should.equal ids[3]
describe "Deletion of docs through requests", ->
describe "Delete a doc from a view : every_notes", (done) ->
it "When I send a request to delete a doc from every_docs", \
(done) ->
Note.requestDestroy "every_notes", {key: ids[3]}, (err) ->
should.not.exist err
done()
it "And I send a request to access view every_docs", (done) ->
delete @err
delete @notes
Note.request "every_notes", {key: ids[3]}, (err, notes) =>
@notes = notes
done()
it "Then I should have 0 documents returned", ->
@notes.should.have.length 0
it "And other documents are still there", (done) ->
Note.request "every_notes", (err, notes) =>
should.not.exist err
notes.should.have.length 3
done()
describe "Delete all doc from a view : every_notes", (done) ->
it "When I delete all docs from every_docs", (done) ->
Note.requestDestroy "every_notes", (err) ->
should.not.exist err
done()
it "And I send a request to grab all docs from every_docs", \
(done) ->
delete @err
delete @notes
Note.request "every_notes", (err, notes) =>
@notes = notes
done()
it "Then I should have 0 documents returned", ->
@notes.should.have.length 0
describe "Deletion of an existing view", ->
it "When I send a request to delete view every_notes", (done) ->
Note.removeRequest "every_notes", (err) ->
should.not.exist err
done()
# Following DS commit 8e43fc66
# the request will be kept in case another app use it
#### Relations ###
#describe "Relations", ->
#before (done) ->
#Author.create name: "John", (err, author) =>
#@author = author
#async.series [
#createNoteFunction "Note 01", "little stories begin", author
#createNoteFunction "Note 02", "great dragons are coming", author
#createNoteFunction "Note 03", "small hobbits are afraid", author
#createNoteFunction "Note 04", "such as humans", null
#], ->
#done()
#after (done) ->
#funcs = []
#for id in ids
#funcs.push deleteNoteFunction(id)
#async.series funcs, ->
#ids = []
#if author?
#@author.destroy ->
#done()
#else
#done()
#describe "Has many relation", ->
#it "When I require all notes related to given author", (done) ->
#@author.notes (err, notes) =>
#should.not.exist err
#@notes = notes
#done()
#it "Then I have three notes", ->
#should.exist @notes
#@notes.length.should.equal 3
###describe "Send mail", ->
describe "Send common mail", ->
it "When I send the mail", (done) ->
data =
to: "test@cozycloud.cc"
from: "Cozy-test <test@cozycloud.cc>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMail data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Send mail to user", ->
it "When I send the mail", (done) ->
data =
from: "Cozy-test <test@cozycloud.cc>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMailToUser data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Send mail from user", ->
it "When I send the mail", (done) ->
data =
to: "test@cozycloud.cc"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMailFromUser data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err###
| 179112 | fs = require "fs"
should = require 'should'
async = require 'async'
http = require 'http'
Client = require("request-json").JsonClient
Schema = require('jugglingdb').Schema
CozyAdapter = require('./src/cozy_data_system')
client = new Client "http://localhost:9101/"
schema = new Schema 'memory'
schema.settings = {}
process.env.NAME = "test"
process.env.TOKEN = "token"
indexerPort = if process.env.NODE_ENV is 'test' then 9092 else 9102
require("./src/cozy_data_system").initialize(schema)
client.setBasicAuth "test", "token"
Note = schema.define 'Note',
title:
type: String
content:
type: Schema.Text
author:
type: String
MailBox = schema.define 'MailBox',
name:
type: String
describe "Create application with all permissions", ->
it "When I create application", (done) ->
data =
name: "<NAME>"
slug: "test"
docType: "Application"
password: "<PASSWORD>"
permissions:
"All":
description: "..."
client.setBasicAuth "home", "token"
client.post 'data/', data, (error, response, body) =>
@response = response
@error = error
done()
it "Then no error should be returned", ->
should.not.exist @error
it "And 201 should be return as response code", ->
@response.statusCode.should.equal 201
describe "Existence", ->
before (done) ->
client.del "data/321/", (error, response, body) ->
client.setBasicAuth "test", "token"
data =
value: "created value"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Check Existence of a Document that does not exist in database", ->
it "When I check existence of Document with id 123", \
(done) ->
Note.exists 123, (err, isExist) =>
should.not.exist err
@isExist = isExist
done()
it "Then false should be returned", ->
@isExist.should.not.be.ok
describe "Check Existence of a Document that does exist in database", ->
it "When I check existence of Document with id 321", \
(done) ->
Note.exists 321, (err, isExist) =>
should.not.exist err
@isExist = isExist
done()
it "Then true should be returned", ->
@isExist.should.be.ok
describe "Find", ->
before (done) ->
client.post 'data/321/',
title: "my note"
content: "my content"
docType: "Note"
, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Find a note that does not exist in database", ->
it "When I claim note with id 123", (done) ->
Note.find 123, (err, note) =>
@note = note
done()
it "Then null should be returned", ->
should.not.exist @note
describe "Find a note that does exist in database", ->
it "When I claim note with id 321", (done) ->
Note.find 321, (err, note) =>
@note = note
done()
it "Then I should retrieve my note ", ->
should.exist @note
@note.title.should.equal "my note"
@note.content.should.equal "my content"
describe "Create", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
client.del "data/987/", (error, response, body) ->
done()
describe "Try to create a Document existing in Database", ->
after ->
@err = null
@note = null
it "When create a document with id 321", (done) ->
Note.create { id: "321", "content":"created value"}, \
(err, note) =>
@err = err
@note = note
done()
it "Then an error is returned", ->
should.exist @err
describe "Create a new Document with a given id", ->
before ->
@id = "987"
after ->
@err = null
@note = null
it "When I create a document with id 987", (done) ->
Note.create { id: @id, "content": "new note" }, (err, note) =>
@err = err
@note = note
done()
it "Then this should be set on document", ->
should.not.exist @err
should.exist @note
@note.id.should.equal @id
it "And the Document with id 987 should exist in Database", (done) ->
Note.exists @id, (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the Document in DB should equal the sent Document", (done) ->
Note.find @id, (err, note) =>
should.not.exist err
note.id.should.equal @id
note.content.should.equal "new note"
done()
describe "Create a new Document without an id", ->
before ->
@id = null
after (done) ->
@note.destroy =>
@err = null
@note = null
done()
it "When I create a document without an id", (done) ->
Note.create { "title": "cool note", "content": "new note" }, \
(err, note) =>
@err = err if err
@note = note
done()
it "Then the id of the new Document should be returned", ->
should.not.exist @err
should.exist @note.id
@id = @note.id
it "And the Document should exist in Database", (done) ->
Note.exists @id, (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the Document in DB should equal the sent Document", (done) ->
Note.find @id, (err, note) =>
should.not.exist err
note.id.should.equal @id
note.content.should.equal "new note"
done()
describe "Create a many documents without an id", ->
before ->
@ids = []
after (done) ->
@note1.destroy =>
@note2.destroy =>
@note3.destroy =>
done()
it "When I create a document without an id", (done) ->
dataList = [
{ "title": "cool note many 01", "content": "new note 01" }
{ "title": "cool note many 02", "content": "new note 02" }
{ "title": "cool note many 03", "content": "new note 03" }
]
Note.createMany dataList, (err, ids) =>
@err = err if err
@ids = ids
done()
it "Then the ids of the new documents should be returned", ->
should.not.exist @err
should.exist @ids
@ids.length.should.equal 3
it "And the Document should exist in Database", (done) ->
Note.exists @ids[0], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
Note.exists @ids[1], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
Note.exists @ids[2], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the documents in DB should equal the sent document", (done) ->
Note.find @ids[0], (err, note) =>
should.not.exist err
note.id.should.equal @ids[0]
note.content.should.equal "new note 01"
@note1 = note
Note.find @ids[1], (err, note) =>
should.not.exist err
note.id.should.equal @ids[1]
note.content.should.equal "new note 02"
@note2 = note
Note.find @ids[2], (err, note) =>
should.not.exist err
note.id.should.equal @ids[2]
note.content.should.equal "new note 03"
@note3 = note
done()
describe "Update", ->
before (done) ->
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
@note = new Note data
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Try to Update a Document that doesn't exist", ->
after ->
@err = null
it "When I update a document with id 123", (done) ->
@note.id = "123"
@note.save (err) =>
@err = err
done()
it "Then an error is returned", ->
should.exist @err
describe "Update a Document", ->
it "When I update document with id 321", (done) ->
@note.id = "321"
@note.title = "my new title"
@note.save (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And the old document must have been replaced in DB", (done) ->
Note.find @note.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "321"
updatedNote.title.should.equal "my new title"
done()
describe "Update attributes", ->
before (done) ->
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
@note = new Note data
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Try to update attributes of a document that doesn't exist", ->
after ->
@err = null
it "When I update a document with id 123", (done) ->
@note.updateAttributes title: "my new title", (err) =>
@err = err
done()
it "Then an error is returned", ->
should.exist @err
describe "Update a Document", ->
it "When I update document with id 321", (done) ->
@note.id = "321"
@note.updateAttributes title: "my new title", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And the old document must have been replaced in DB", (done) ->
Note.find @note.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "321"
updatedNote.title.should.equal "my new title"
done()
describe "Upsert attributes", ->
after (done) ->
client.del "data/654/", (error, response, body) ->
done()
describe "Upsert a non existing document", ->
it "When I upsert document with id 654", (done) ->
@data =
id: "654"
title: "my note"
content: "my content"
Note.updateOrCreate @data, (err) =>
@err = err
done()
it "Then no error should be returned.", ->
should.not.exist @err
it "And the document with id 654 should exist in Database", (done) ->
Note.find @data.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "654"
updatedNote.title.should.equal "my note"
done()
describe "Upsert an existing Document", ->
it "When I upsert document with id 654", (done) ->
@data =
id: "654"
title: "my new title"
Note.updateOrCreate @data, (err, note) =>
should.not.exist note
@err = err
done()
it "Then no data should be returned", ->
should.not.exist @err
it "And the document with id 654 should be updated", (done) ->
Note.find @data.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "654"
updatedNote.title.should.equal "my new title"
done()
describe "Delete", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
client.del "data/987/", (error, response, body) ->
done()
describe "Deletes a document that is not in Database", ->
it "When I delete Document with id 123", (done) ->
note = new Note id:123
note.destroy (err) =>
@err = err
done()
it "Then an error should be returned", ->
should.exist @err
describe "Deletes a document from database", ->
it "When I delete document with id 321", (done) ->
note = new Note id:321
note.destroy (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And Document with id 321 shouldn't exist in Database", (done) ->
Note.exists 321, (err, isExist) =>
isExist.should.not.be.ok
done()
### Indexation ###
ids = []
dragonNoteId = "0"
createNoteFunction = (title, content, author) ->
(callback) ->
if author? then authorId = author.id else authorId = null
data =
title: title
content: content
author: authorId
Note.create data, (err, note) ->
ids.push note.id
dragonNoteId = note.id if title is "Note 02"
note.index ["title", "content"], (err) ->
callback()
createTaskFunction = (description) ->
(callback) ->
client.post 'data/', {
description: "description"
docType: "task"
} , (error, response, body) ->
callback()
fakeServer = (json, code=200, callback=null) ->
http.createServer (req, res) ->
body = ""
req.on 'data', (chunk) ->
body += chunk
req.on 'end', ->
if callback?
data = JSON.parse body if body? and body.length > 0
code = callback req.url, data
res.writeHead code, 'Content-Type': 'application/json'
res.end(JSON.stringify json)
deleteNoteFunction = (id) ->
(callback) ->
client.del "data/#{id}/", (err) -> callback()
describe "Search features", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
funcs = []
for id in ids
funcs.push deleteNoteFunction(id)
async.series funcs, ->
ids = []
done()
describe "index", ->
before (done) ->
client.del "data/index/clear-all/", (err, response) ->
done()
it "When given I index four notes", (done) ->
async.series [
createNoteFunction "Note 01", "little stories begin"
createNoteFunction "Note 02", "great dragons are coming"
createNoteFunction "Note 03", "small hobbits are afraid"
createNoteFunction "Note 04", "such as humans"
], =>
data = ids: [dragonNoteId]
@indexer = fakeServer data, 200, (url, body) ->
if url is '/index/'
should.exist body.fields
should.exist body.doc
should.exist body.doc.docType
200
else if url is '/search/'
should.exist body.query
body.query.should.equal "dragons"
200
else 204
@indexer.listen indexerPort
setTimeout done, 500
it "And I send a request to search the notes containing dragons", \
(done) ->
Note.search "dragons", (err, notes) =>
@notes = notes
@indexer.close()
done()
it "Then result is the second note I created", ->
@notes.length.should.equal 1
@notes[0].title.should.equal "Note 02"
@notes[0].content.should.equal "great dragons are coming"
describe "retrieve notes with result numbers", ->
before (done) ->
client.del "data/index/clear-all/", (err, response) ->
done()
it "When given I index four notes", (done) ->
data = ids: [dragonNoteId], numResults: 1
@indexer = fakeServer data, 200, (url, body) ->
if url is '/index/'
should.exist body.fields
should.exist body.doc
should.exist body.doc.docType
200
else if url is '/search/'
should.exist body.query
body.query.should.equal "dragons"
200
else 204
@indexer.listen indexerPort
setTimeout done, 500
it "When I search again with the options", (done) ->
options =
query: "dragons"
numPage: 1
numByPage: 10
Note.search options, (err, notes) =>
@notes = notes
@indexer.close()
done()
it "Then result should be made of the results themselves and the total number of results", ->
{results, numResults} = @notes
should.exist results
should.exist numResults
results.length.should.equal 1
results[0].title.should.equal "Note 02"
results[0].content.should.equal "great dragons are coming"
numResults.should.equal 1
### Attachments ###
describe "Attachments", ->
before (done) ->
@note = new Note id: 321
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Add an attachment", ->
it "When I add an attachment", (done) ->
@note.attachFile "./test.png", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Retrieve an attachment", ->
it "When I claim this attachment", (done) ->
stream = @note.getFile "test.png", -> done()
stream.pipe fs.createWriteStream('./test-get.png')
it "Then I got the same file I attached before", ->
fileStats = fs.statSync('./test.png')
resultStats = fs.statSync('./test-get.png')
resultStats.size.should.equal fileStats.size
describe "Remove an attachment", ->
it "When I remove this attachment", (done) ->
@note.removeFile "test.png", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "When I claim this attachment", (done) ->
stream = @note.getFile "test.png", (err) =>
@err = err
done()
stream.pipe fs.createWriteStream('./test-get.png')
it "Then I got an error", ->
should.exist @err
checkNoError = ->
it "Then no error should be returned", ->
should.not.exist @err
checkError = ->
it "Then error should be returned", ->
should.exist @err
describe "Requests", ->
before (done) ->
async.series [
createNoteFunction "Note 01", "little stories begin"
createNoteFunction "Note 02", "great dragons are coming"
createNoteFunction "Note 03", "small hobbits are afraid"
createNoteFunction "Note 04", "such as humans"
createTaskFunction "Task 01"
createTaskFunction "Task 02"
createTaskFunction "Task 03"
], ->
done()
after (done) ->
funcs = []
for id in ids
funcs.push deleteNoteFunction(id)
async.series funcs, ->
ids = []
done()
describe "index", ->
describe "View creation", ->
describe "Creation of the first view + design document creation", ->
it "When I send a request to create view every_docs", (done) ->
delete @err
@map = (doc) ->
emit doc._id, doc
return
Note.defineRequest "every_notes", @map, (err) ->
should.not.exist err
done()
checkNoError()
describe "Access to a view without option", ->
describe "Access to a non existing view", ->
it "When I send a request to access view dont-exist", (done) ->
delete @err
Note.request "dont-exist", (err, notes) =>
@err = err
should.exist err
done()
checkError()
describe "Access to an existing view : every_notes", (done) ->
it "When I send a request to access view every_docs", (done) ->
delete @err
Note.request "every_notes", (err, notes) =>
@notes = notes
done()
it "Then I should have 4 documents returned", ->
@notes.should.have.length 4
describe "Access to a doc from a view : every_notes", (done) ->
it "When I send a request to access doc 3 from every_docs", \
(done) ->
delete @err
Note.request "every_notes", {key: ids[3]}, (err, notes) =>
@notes = notes
done()
it "Then I should have 1 documents returned", ->
@notes.should.have.length 1
@notes[0].id.should.equal ids[3]
describe "Deletion of docs through requests", ->
describe "Delete a doc from a view : every_notes", (done) ->
it "When I send a request to delete a doc from every_docs", \
(done) ->
Note.requestDestroy "every_notes", {key: ids[3]}, (err) ->
should.not.exist err
done()
it "And I send a request to access view every_docs", (done) ->
delete @err
delete @notes
Note.request "every_notes", {key: ids[3]}, (err, notes) =>
@notes = notes
done()
it "Then I should have 0 documents returned", ->
@notes.should.have.length 0
it "And other documents are still there", (done) ->
Note.request "every_notes", (err, notes) =>
should.not.exist err
notes.should.have.length 3
done()
describe "Delete all doc from a view : every_notes", (done) ->
it "When I delete all docs from every_docs", (done) ->
Note.requestDestroy "every_notes", (err) ->
should.not.exist err
done()
it "And I send a request to grab all docs from every_docs", \
(done) ->
delete @err
delete @notes
Note.request "every_notes", (err, notes) =>
@notes = notes
done()
it "Then I should have 0 documents returned", ->
@notes.should.have.length 0
describe "Deletion of an existing view", ->
it "When I send a request to delete view every_notes", (done) ->
Note.removeRequest "every_notes", (err) ->
should.not.exist err
done()
# Following DS commit 8e43fc66
# the request will be kept in case another app use it
#### Relations ###
#describe "Relations", ->
#before (done) ->
#Author.create name: "<NAME>", (err, author) =>
#@author = author
#async.series [
#createNoteFunction "Note 01", "little stories begin", author
#createNoteFunction "Note 02", "great dragons are coming", author
#createNoteFunction "Note 03", "small hobbits are afraid", author
#createNoteFunction "Note 04", "such as humans", null
#], ->
#done()
#after (done) ->
#funcs = []
#for id in ids
#funcs.push deleteNoteFunction(id)
#async.series funcs, ->
#ids = []
#if author?
#@author.destroy ->
#done()
#else
#done()
#describe "Has many relation", ->
#it "When I require all notes related to given author", (done) ->
#@author.notes (err, notes) =>
#should.not.exist err
#@notes = notes
#done()
#it "Then I have three notes", ->
#should.exist @notes
#@notes.length.should.equal 3
###describe "Send mail", ->
describe "Send common mail", ->
it "When I send the mail", (done) ->
data =
to: "<EMAIL>"
from: "Cozy-test <<EMAIL>>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMail data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Send mail to user", ->
it "When I send the mail", (done) ->
data =
from: "Cozy-test <<EMAIL>>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMailToUser data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Send mail from user", ->
it "When I send the mail", (done) ->
data =
to: "<EMAIL>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMailFromUser data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err###
| true | fs = require "fs"
should = require 'should'
async = require 'async'
http = require 'http'
Client = require("request-json").JsonClient
Schema = require('jugglingdb').Schema
CozyAdapter = require('./src/cozy_data_system')
client = new Client "http://localhost:9101/"
schema = new Schema 'memory'
schema.settings = {}
process.env.NAME = "test"
process.env.TOKEN = "token"
indexerPort = if process.env.NODE_ENV is 'test' then 9092 else 9102
require("./src/cozy_data_system").initialize(schema)
client.setBasicAuth "test", "token"
Note = schema.define 'Note',
title:
type: String
content:
type: Schema.Text
author:
type: String
MailBox = schema.define 'MailBox',
name:
type: String
describe "Create application with all permissions", ->
it "When I create application", (done) ->
data =
name: "PI:NAME:<NAME>END_PI"
slug: "test"
docType: "Application"
password: "PI:PASSWORD:<PASSWORD>END_PI"
permissions:
"All":
description: "..."
client.setBasicAuth "home", "token"
client.post 'data/', data, (error, response, body) =>
@response = response
@error = error
done()
it "Then no error should be returned", ->
should.not.exist @error
it "And 201 should be return as response code", ->
@response.statusCode.should.equal 201
describe "Existence", ->
before (done) ->
client.del "data/321/", (error, response, body) ->
client.setBasicAuth "test", "token"
data =
value: "created value"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Check Existence of a Document that does not exist in database", ->
it "When I check existence of Document with id 123", \
(done) ->
Note.exists 123, (err, isExist) =>
should.not.exist err
@isExist = isExist
done()
it "Then false should be returned", ->
@isExist.should.not.be.ok
describe "Check Existence of a Document that does exist in database", ->
it "When I check existence of Document with id 321", \
(done) ->
Note.exists 321, (err, isExist) =>
should.not.exist err
@isExist = isExist
done()
it "Then true should be returned", ->
@isExist.should.be.ok
describe "Find", ->
before (done) ->
client.post 'data/321/',
title: "my note"
content: "my content"
docType: "Note"
, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Find a note that does not exist in database", ->
it "When I claim note with id 123", (done) ->
Note.find 123, (err, note) =>
@note = note
done()
it "Then null should be returned", ->
should.not.exist @note
describe "Find a note that does exist in database", ->
it "When I claim note with id 321", (done) ->
Note.find 321, (err, note) =>
@note = note
done()
it "Then I should retrieve my note ", ->
should.exist @note
@note.title.should.equal "my note"
@note.content.should.equal "my content"
describe "Create", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
client.del "data/987/", (error, response, body) ->
done()
describe "Try to create a Document existing in Database", ->
after ->
@err = null
@note = null
it "When create a document with id 321", (done) ->
Note.create { id: "321", "content":"created value"}, \
(err, note) =>
@err = err
@note = note
done()
it "Then an error is returned", ->
should.exist @err
describe "Create a new Document with a given id", ->
before ->
@id = "987"
after ->
@err = null
@note = null
it "When I create a document with id 987", (done) ->
Note.create { id: @id, "content": "new note" }, (err, note) =>
@err = err
@note = note
done()
it "Then this should be set on document", ->
should.not.exist @err
should.exist @note
@note.id.should.equal @id
it "And the Document with id 987 should exist in Database", (done) ->
Note.exists @id, (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the Document in DB should equal the sent Document", (done) ->
Note.find @id, (err, note) =>
should.not.exist err
note.id.should.equal @id
note.content.should.equal "new note"
done()
describe "Create a new Document without an id", ->
before ->
@id = null
after (done) ->
@note.destroy =>
@err = null
@note = null
done()
it "When I create a document without an id", (done) ->
Note.create { "title": "cool note", "content": "new note" }, \
(err, note) =>
@err = err if err
@note = note
done()
it "Then the id of the new Document should be returned", ->
should.not.exist @err
should.exist @note.id
@id = @note.id
it "And the Document should exist in Database", (done) ->
Note.exists @id, (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the Document in DB should equal the sent Document", (done) ->
Note.find @id, (err, note) =>
should.not.exist err
note.id.should.equal @id
note.content.should.equal "new note"
done()
describe "Create a many documents without an id", ->
before ->
@ids = []
after (done) ->
@note1.destroy =>
@note2.destroy =>
@note3.destroy =>
done()
it "When I create a document without an id", (done) ->
dataList = [
{ "title": "cool note many 01", "content": "new note 01" }
{ "title": "cool note many 02", "content": "new note 02" }
{ "title": "cool note many 03", "content": "new note 03" }
]
Note.createMany dataList, (err, ids) =>
@err = err if err
@ids = ids
done()
it "Then the ids of the new documents should be returned", ->
should.not.exist @err
should.exist @ids
@ids.length.should.equal 3
it "And the Document should exist in Database", (done) ->
Note.exists @ids[0], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
Note.exists @ids[1], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
Note.exists @ids[2], (err, isExist) =>
should.not.exist err
isExist.should.be.ok
done()
it "And the documents in DB should equal the sent document", (done) ->
Note.find @ids[0], (err, note) =>
should.not.exist err
note.id.should.equal @ids[0]
note.content.should.equal "new note 01"
@note1 = note
Note.find @ids[1], (err, note) =>
should.not.exist err
note.id.should.equal @ids[1]
note.content.should.equal "new note 02"
@note2 = note
Note.find @ids[2], (err, note) =>
should.not.exist err
note.id.should.equal @ids[2]
note.content.should.equal "new note 03"
@note3 = note
done()
describe "Update", ->
before (done) ->
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
@note = new Note data
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Try to Update a Document that doesn't exist", ->
after ->
@err = null
it "When I update a document with id 123", (done) ->
@note.id = "123"
@note.save (err) =>
@err = err
done()
it "Then an error is returned", ->
should.exist @err
describe "Update a Document", ->
it "When I update document with id 321", (done) ->
@note.id = "321"
@note.title = "my new title"
@note.save (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And the old document must have been replaced in DB", (done) ->
Note.find @note.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "321"
updatedNote.title.should.equal "my new title"
done()
describe "Update attributes", ->
before (done) ->
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
@note = new Note data
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Try to update attributes of a document that doesn't exist", ->
after ->
@err = null
it "When I update a document with id 123", (done) ->
@note.updateAttributes title: "my new title", (err) =>
@err = err
done()
it "Then an error is returned", ->
should.exist @err
describe "Update a Document", ->
it "When I update document with id 321", (done) ->
@note.id = "321"
@note.updateAttributes title: "my new title", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And the old document must have been replaced in DB", (done) ->
Note.find @note.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "321"
updatedNote.title.should.equal "my new title"
done()
describe "Upsert attributes", ->
after (done) ->
client.del "data/654/", (error, response, body) ->
done()
describe "Upsert a non existing document", ->
it "When I upsert document with id 654", (done) ->
@data =
id: "654"
title: "my note"
content: "my content"
Note.updateOrCreate @data, (err) =>
@err = err
done()
it "Then no error should be returned.", ->
should.not.exist @err
it "And the document with id 654 should exist in Database", (done) ->
Note.find @data.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "654"
updatedNote.title.should.equal "my note"
done()
describe "Upsert an existing Document", ->
it "When I upsert document with id 654", (done) ->
@data =
id: "654"
title: "my new title"
Note.updateOrCreate @data, (err, note) =>
should.not.exist note
@err = err
done()
it "Then no data should be returned", ->
should.not.exist @err
it "And the document with id 654 should be updated", (done) ->
Note.find @data.id, (err, updatedNote) =>
should.not.exist err
updatedNote.id.should.equal "654"
updatedNote.title.should.equal "my new title"
done()
describe "Delete", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
client.del "data/987/", (error, response, body) ->
done()
describe "Deletes a document that is not in Database", ->
it "When I delete Document with id 123", (done) ->
note = new Note id:123
note.destroy (err) =>
@err = err
done()
it "Then an error should be returned", ->
should.exist @err
describe "Deletes a document from database", ->
it "When I delete document with id 321", (done) ->
note = new Note id:321
note.destroy (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "And Document with id 321 shouldn't exist in Database", (done) ->
Note.exists 321, (err, isExist) =>
isExist.should.not.be.ok
done()
### Indexation ###
ids = []
dragonNoteId = "0"
createNoteFunction = (title, content, author) ->
(callback) ->
if author? then authorId = author.id else authorId = null
data =
title: title
content: content
author: authorId
Note.create data, (err, note) ->
ids.push note.id
dragonNoteId = note.id if title is "Note 02"
note.index ["title", "content"], (err) ->
callback()
createTaskFunction = (description) ->
(callback) ->
client.post 'data/', {
description: "description"
docType: "task"
} , (error, response, body) ->
callback()
fakeServer = (json, code=200, callback=null) ->
http.createServer (req, res) ->
body = ""
req.on 'data', (chunk) ->
body += chunk
req.on 'end', ->
if callback?
data = JSON.parse body if body? and body.length > 0
code = callback req.url, data
res.writeHead code, 'Content-Type': 'application/json'
res.end(JSON.stringify json)
deleteNoteFunction = (id) ->
(callback) ->
client.del "data/#{id}/", (err) -> callback()
describe "Search features", ->
before (done) ->
client.post 'data/321/', {
title: "my note"
content: "my content"
docType: "Note"
} , (error, response, body) ->
done()
after (done) ->
funcs = []
for id in ids
funcs.push deleteNoteFunction(id)
async.series funcs, ->
ids = []
done()
describe "index", ->
before (done) ->
client.del "data/index/clear-all/", (err, response) ->
done()
it "When given I index four notes", (done) ->
async.series [
createNoteFunction "Note 01", "little stories begin"
createNoteFunction "Note 02", "great dragons are coming"
createNoteFunction "Note 03", "small hobbits are afraid"
createNoteFunction "Note 04", "such as humans"
], =>
data = ids: [dragonNoteId]
@indexer = fakeServer data, 200, (url, body) ->
if url is '/index/'
should.exist body.fields
should.exist body.doc
should.exist body.doc.docType
200
else if url is '/search/'
should.exist body.query
body.query.should.equal "dragons"
200
else 204
@indexer.listen indexerPort
setTimeout done, 500
it "And I send a request to search the notes containing dragons", \
(done) ->
Note.search "dragons", (err, notes) =>
@notes = notes
@indexer.close()
done()
it "Then result is the second note I created", ->
@notes.length.should.equal 1
@notes[0].title.should.equal "Note 02"
@notes[0].content.should.equal "great dragons are coming"
describe "retrieve notes with result numbers", ->
before (done) ->
client.del "data/index/clear-all/", (err, response) ->
done()
it "When given I index four notes", (done) ->
data = ids: [dragonNoteId], numResults: 1
@indexer = fakeServer data, 200, (url, body) ->
if url is '/index/'
should.exist body.fields
should.exist body.doc
should.exist body.doc.docType
200
else if url is '/search/'
should.exist body.query
body.query.should.equal "dragons"
200
else 204
@indexer.listen indexerPort
setTimeout done, 500
it "When I search again with the options", (done) ->
options =
query: "dragons"
numPage: 1
numByPage: 10
Note.search options, (err, notes) =>
@notes = notes
@indexer.close()
done()
it "Then result should be made of the results themselves and the total number of results", ->
{results, numResults} = @notes
should.exist results
should.exist numResults
results.length.should.equal 1
results[0].title.should.equal "Note 02"
results[0].content.should.equal "great dragons are coming"
numResults.should.equal 1
### Attachments ###
describe "Attachments", ->
before (done) ->
@note = new Note id: 321
data =
title: "my note"
content: "my content"
docType: "Note"
client.post 'data/321/', data, (error, response, body) ->
done()
after (done) ->
client.del "data/321/", (error, response, body) ->
done()
describe "Add an attachment", ->
it "When I add an attachment", (done) ->
@note.attachFile "./test.png", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Retrieve an attachment", ->
it "When I claim this attachment", (done) ->
stream = @note.getFile "test.png", -> done()
stream.pipe fs.createWriteStream('./test-get.png')
it "Then I got the same file I attached before", ->
fileStats = fs.statSync('./test.png')
resultStats = fs.statSync('./test-get.png')
resultStats.size.should.equal fileStats.size
describe "Remove an attachment", ->
it "When I remove this attachment", (done) ->
@note.removeFile "test.png", (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
it "When I claim this attachment", (done) ->
stream = @note.getFile "test.png", (err) =>
@err = err
done()
stream.pipe fs.createWriteStream('./test-get.png')
it "Then I got an error", ->
should.exist @err
checkNoError = ->
it "Then no error should be returned", ->
should.not.exist @err
checkError = ->
it "Then error should be returned", ->
should.exist @err
describe "Requests", ->
before (done) ->
async.series [
createNoteFunction "Note 01", "little stories begin"
createNoteFunction "Note 02", "great dragons are coming"
createNoteFunction "Note 03", "small hobbits are afraid"
createNoteFunction "Note 04", "such as humans"
createTaskFunction "Task 01"
createTaskFunction "Task 02"
createTaskFunction "Task 03"
], ->
done()
after (done) ->
funcs = []
for id in ids
funcs.push deleteNoteFunction(id)
async.series funcs, ->
ids = []
done()
describe "index", ->
describe "View creation", ->
describe "Creation of the first view + design document creation", ->
it "When I send a request to create view every_docs", (done) ->
delete @err
@map = (doc) ->
emit doc._id, doc
return
Note.defineRequest "every_notes", @map, (err) ->
should.not.exist err
done()
checkNoError()
describe "Access to a view without option", ->
describe "Access to a non existing view", ->
it "When I send a request to access view dont-exist", (done) ->
delete @err
Note.request "dont-exist", (err, notes) =>
@err = err
should.exist err
done()
checkError()
describe "Access to an existing view : every_notes", (done) ->
it "When I send a request to access view every_docs", (done) ->
delete @err
Note.request "every_notes", (err, notes) =>
@notes = notes
done()
it "Then I should have 4 documents returned", ->
@notes.should.have.length 4
describe "Access to a doc from a view : every_notes", (done) ->
it "When I send a request to access doc 3 from every_docs", \
(done) ->
delete @err
Note.request "every_notes", {key: ids[3]}, (err, notes) =>
@notes = notes
done()
it "Then I should have 1 documents returned", ->
@notes.should.have.length 1
@notes[0].id.should.equal ids[3]
describe "Deletion of docs through requests", ->
describe "Delete a doc from a view : every_notes", (done) ->
it "When I send a request to delete a doc from every_docs", \
(done) ->
Note.requestDestroy "every_notes", {key: ids[3]}, (err) ->
should.not.exist err
done()
it "And I send a request to access view every_docs", (done) ->
delete @err
delete @notes
Note.request "every_notes", {key: ids[3]}, (err, notes) =>
@notes = notes
done()
it "Then I should have 0 documents returned", ->
@notes.should.have.length 0
it "And other documents are still there", (done) ->
Note.request "every_notes", (err, notes) =>
should.not.exist err
notes.should.have.length 3
done()
describe "Delete all doc from a view : every_notes", (done) ->
it "When I delete all docs from every_docs", (done) ->
Note.requestDestroy "every_notes", (err) ->
should.not.exist err
done()
it "And I send a request to grab all docs from every_docs", \
(done) ->
delete @err
delete @notes
Note.request "every_notes", (err, notes) =>
@notes = notes
done()
it "Then I should have 0 documents returned", ->
@notes.should.have.length 0
describe "Deletion of an existing view", ->
it "When I send a request to delete view every_notes", (done) ->
Note.removeRequest "every_notes", (err) ->
should.not.exist err
done()
# Following DS commit 8e43fc66
# the request will be kept in case another app use it
#### Relations ###
#describe "Relations", ->
#before (done) ->
#Author.create name: "PI:NAME:<NAME>END_PI", (err, author) =>
#@author = author
#async.series [
#createNoteFunction "Note 01", "little stories begin", author
#createNoteFunction "Note 02", "great dragons are coming", author
#createNoteFunction "Note 03", "small hobbits are afraid", author
#createNoteFunction "Note 04", "such as humans", null
#], ->
#done()
#after (done) ->
#funcs = []
#for id in ids
#funcs.push deleteNoteFunction(id)
#async.series funcs, ->
#ids = []
#if author?
#@author.destroy ->
#done()
#else
#done()
#describe "Has many relation", ->
#it "When I require all notes related to given author", (done) ->
#@author.notes (err, notes) =>
#should.not.exist err
#@notes = notes
#done()
#it "Then I have three notes", ->
#should.exist @notes
#@notes.length.should.equal 3
###describe "Send mail", ->
describe "Send common mail", ->
it "When I send the mail", (done) ->
data =
to: "PI:EMAIL:<EMAIL>END_PI"
from: "Cozy-test <PI:EMAIL:<EMAIL>END_PI>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMail data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Send mail to user", ->
it "When I send the mail", (done) ->
data =
from: "Cozy-test <PI:EMAIL:<EMAIL>END_PI>"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMailToUser data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err
describe "Send mail from user", ->
it "When I send the mail", (done) ->
data =
to: "PI:EMAIL:<EMAIL>END_PI"
subject: "Test jugglingdb"
content: "Content of mail"
CozyAdapter.sendMailFromUser data, (err) =>
@err = err
done()
it "Then no error is returned", ->
should.not.exist @err###
|
[
{
"context": "parent\n account = @parent.getData()\n { firstName } = account.profile\n\n { provider, nicename } =",
"end": 879,
"score": 0.5839129686355591,
"start": 870,
"tag": "NAME",
"value": "firstName"
},
{
"context": " #{nicename} profile\"\n else title : \"Go to #{firstName}'s #{nicename} profile\"\n\n\n click: (event) ->\n\n ",
"end": 1526,
"score": 0.6317570805549622,
"start": 1517,
"tag": "NAME",
"value": "firstName"
}
] | client/members/lib/contentdisplays/externalprofileview.coffee | ezgikaysi/koding | 1 | kd = require 'kd'
isMine = require 'app/util/isMine'
JView = require 'app/jview'
jspath = require 'jspath'
module.exports = class ExternalProfileView extends JView
{ warn } = kd
constructor: (options, account) ->
options.tagName or= 'a'
options.provider or= ''
options.cssClass = kd.utils.curry "external-profile #{options.provider}", options.cssClass
options.attributes = { href : '#' }
super options, account
@linked = no
{ provider } = @getOptions()
mainController = kd.getSingleton 'mainController'
mainController.on "ForeignAuthSuccess.#{provider}", @bound 'setLinkedState'
viewAppended: ->
super
@setTooltip { title : "Click to link your #{@getOption 'nicename'} account" }
@setLinkedState()
setLinkedState: ->
return unless @parent
account = @parent.getData()
{ firstName } = account.profile
{ provider, nicename } = @getOptions()
account.fetchStorage "ext|profile|#{provider}", (err, storage) =>
return warn err if err
return unless storage
return unless urlLocation = @getOption 'urlLocation'
@setData storage
@$().detach()
@$().prependTo @parent.$('.external-profiles')
@linked = yes
@setClass 'linked'
@setAttributes
href : jspath.getAt storage.content, urlLocation
target : '_blank'
@setTooltip if isMine(account)
then title : "Go to my #{nicename} profile"
else title : "Go to #{firstName}'s #{nicename} profile"
click: (event) ->
return if @linked
{ provider } = @getOptions()
if isMine @parent.getData()
kd.utils.stopDOMEvent event
kd.singletons.oauthController.openPopup provider
pistachio: ->
'''
<span class="icon"></span>
'''
| 170061 | kd = require 'kd'
isMine = require 'app/util/isMine'
JView = require 'app/jview'
jspath = require 'jspath'
module.exports = class ExternalProfileView extends JView
{ warn } = kd
constructor: (options, account) ->
options.tagName or= 'a'
options.provider or= ''
options.cssClass = kd.utils.curry "external-profile #{options.provider}", options.cssClass
options.attributes = { href : '#' }
super options, account
@linked = no
{ provider } = @getOptions()
mainController = kd.getSingleton 'mainController'
mainController.on "ForeignAuthSuccess.#{provider}", @bound 'setLinkedState'
viewAppended: ->
super
@setTooltip { title : "Click to link your #{@getOption 'nicename'} account" }
@setLinkedState()
setLinkedState: ->
return unless @parent
account = @parent.getData()
{ <NAME> } = account.profile
{ provider, nicename } = @getOptions()
account.fetchStorage "ext|profile|#{provider}", (err, storage) =>
return warn err if err
return unless storage
return unless urlLocation = @getOption 'urlLocation'
@setData storage
@$().detach()
@$().prependTo @parent.$('.external-profiles')
@linked = yes
@setClass 'linked'
@setAttributes
href : jspath.getAt storage.content, urlLocation
target : '_blank'
@setTooltip if isMine(account)
then title : "Go to my #{nicename} profile"
else title : "Go to #{<NAME>}'s #{nicename} profile"
click: (event) ->
return if @linked
{ provider } = @getOptions()
if isMine @parent.getData()
kd.utils.stopDOMEvent event
kd.singletons.oauthController.openPopup provider
pistachio: ->
'''
<span class="icon"></span>
'''
| true | kd = require 'kd'
isMine = require 'app/util/isMine'
JView = require 'app/jview'
jspath = require 'jspath'
module.exports = class ExternalProfileView extends JView
{ warn } = kd
constructor: (options, account) ->
options.tagName or= 'a'
options.provider or= ''
options.cssClass = kd.utils.curry "external-profile #{options.provider}", options.cssClass
options.attributes = { href : '#' }
super options, account
@linked = no
{ provider } = @getOptions()
mainController = kd.getSingleton 'mainController'
mainController.on "ForeignAuthSuccess.#{provider}", @bound 'setLinkedState'
viewAppended: ->
super
@setTooltip { title : "Click to link your #{@getOption 'nicename'} account" }
@setLinkedState()
setLinkedState: ->
return unless @parent
account = @parent.getData()
{ PI:NAME:<NAME>END_PI } = account.profile
{ provider, nicename } = @getOptions()
account.fetchStorage "ext|profile|#{provider}", (err, storage) =>
return warn err if err
return unless storage
return unless urlLocation = @getOption 'urlLocation'
@setData storage
@$().detach()
@$().prependTo @parent.$('.external-profiles')
@linked = yes
@setClass 'linked'
@setAttributes
href : jspath.getAt storage.content, urlLocation
target : '_blank'
@setTooltip if isMine(account)
then title : "Go to my #{nicename} profile"
else title : "Go to #{PI:NAME:<NAME>END_PI}'s #{nicename} profile"
click: (event) ->
return if @linked
{ provider } = @getOptions()
if isMine @parent.getData()
kd.utils.stopDOMEvent event
kd.singletons.oauthController.openPopup provider
pistachio: ->
'''
<span class="icon"></span>
'''
|
[
{
"context": "d] = unchecked_nodes.pop()\n child_key = child.toString()\n if child_key of minimized_nodes\n #",
"end": 3097,
"score": 0.7437474727630615,
"start": 3089,
"tag": "KEY",
"value": "toString"
}
] | src/collection/dawg.coffee | DhrubajitPC/liblevenshtein-coffeescript | 13 | # ============================================================================
# Taken and modified for my purposes from the following source:
# o http://stevehanov.ca/blog/index.php?id=115
# ============================================================================
#
# This class represents a node in the directed acyclic word graph (DAWG,
# a.k.a. Minimal Acyclic Finite State Automaton, or MA-FSA). It has a list
# of edges to other nodes. It has functions for testing whether it is
# equivalent to another node. Nodes are equivalent if they have identical
# edges, and each identical edge leads to identical states.
class DawgNode
@next_id = 0
constructor: ->
@id = DawgNode.next_id; DawgNode.next_id += 1
@['is_final'] = false
@['edges'] = {}
bisect_left: (edges, edge, lower, upper) ->
while lower < upper
i = (lower + upper) >> 1
if edges[i] < edge
lower = i + 1
else
upper = i
return lower
'toString': ->
edges = []
for label, node of @['edges'] # insertion sort
edge = label + node.id.toString()
edges.splice(@bisect_left(edges, edge, 0, edges.length), 0, edge)
(+ @['is_final']) + edges.join('')
class Dawg
constructor: (dictionary) ->
unless dictionary and typeof dictionary.length is 'number'
throw new Error("Expected dictionary to be array-like")
@previous_word = ''
@['root'] = new DawgNode()
# Here is a list of nodes that have not been checked for duplication.
@unchecked_nodes = []
# Here is a list of unique nodes that have been checked for duplication.
@minimized_nodes = {}
@['insert'](word) for word in dictionary
@finish()
'insert': (word) ->
# Find longest common prefix between word and previous word
i = 0; previous_word = @previous_word
upper_bound =
if word.length < previous_word.length
word.length
else
previous_word.length
i += 1 while i < upper_bound and word[i] is previous_word[i]
# Check the unchecked_nodes for redundant nodes, proceeding from last one
# down to the common prefix size. Then truncate the list at that point.
@minimize(i)
unchecked_nodes = @unchecked_nodes
# Add the suffix, starting from the correct node mid-way through the graph.
if unchecked_nodes.length is 0
node = @['root']
else
node = unchecked_nodes[unchecked_nodes.length - 1][2]
while (character = word[i]) isnt `undefined`
next_node = new DawgNode()
node['edges'][character] = next_node
unchecked_nodes.push([node, character, next_node])
node = next_node
i += 1
node['is_final'] = true
@previous_word = word
return
finish: ->
# minimize all unchecked_nodes
@minimize(0)
return
minimize: (lower_bound) ->
# proceed from the leaf up to a certain point
minimized_nodes = @minimized_nodes
unchecked_nodes = @unchecked_nodes
j = unchecked_nodes.length
while j > lower_bound
[parent, character, child] = unchecked_nodes.pop()
child_key = child.toString()
if child_key of minimized_nodes
# replace the child with the previously encountered one
parent['edges'][character] = minimized_nodes[child_key]
else
# add the state to the minimized nodes
minimized_nodes[child_key] = child
j -= 1
return
'accepts': (word) ->
node = @['root']
for edge in word
node = node['edges'][edge]
return false unless node
node['is_final']
global =
if typeof exports is 'object'
exports
else if typeof window is 'object'
window
else
this
global['levenshtein'] ||= {}
global['levenshtein']['DawgNode'] = DawgNode
global['levenshtein']['Dawg'] = Dawg
| 57386 | # ============================================================================
# Taken and modified for my purposes from the following source:
# o http://stevehanov.ca/blog/index.php?id=115
# ============================================================================
#
# This class represents a node in the directed acyclic word graph (DAWG,
# a.k.a. Minimal Acyclic Finite State Automaton, or MA-FSA). It has a list
# of edges to other nodes. It has functions for testing whether it is
# equivalent to another node. Nodes are equivalent if they have identical
# edges, and each identical edge leads to identical states.
class DawgNode
@next_id = 0
constructor: ->
@id = DawgNode.next_id; DawgNode.next_id += 1
@['is_final'] = false
@['edges'] = {}
bisect_left: (edges, edge, lower, upper) ->
while lower < upper
i = (lower + upper) >> 1
if edges[i] < edge
lower = i + 1
else
upper = i
return lower
'toString': ->
edges = []
for label, node of @['edges'] # insertion sort
edge = label + node.id.toString()
edges.splice(@bisect_left(edges, edge, 0, edges.length), 0, edge)
(+ @['is_final']) + edges.join('')
class Dawg
constructor: (dictionary) ->
unless dictionary and typeof dictionary.length is 'number'
throw new Error("Expected dictionary to be array-like")
@previous_word = ''
@['root'] = new DawgNode()
# Here is a list of nodes that have not been checked for duplication.
@unchecked_nodes = []
# Here is a list of unique nodes that have been checked for duplication.
@minimized_nodes = {}
@['insert'](word) for word in dictionary
@finish()
'insert': (word) ->
# Find longest common prefix between word and previous word
i = 0; previous_word = @previous_word
upper_bound =
if word.length < previous_word.length
word.length
else
previous_word.length
i += 1 while i < upper_bound and word[i] is previous_word[i]
# Check the unchecked_nodes for redundant nodes, proceeding from last one
# down to the common prefix size. Then truncate the list at that point.
@minimize(i)
unchecked_nodes = @unchecked_nodes
# Add the suffix, starting from the correct node mid-way through the graph.
if unchecked_nodes.length is 0
node = @['root']
else
node = unchecked_nodes[unchecked_nodes.length - 1][2]
while (character = word[i]) isnt `undefined`
next_node = new DawgNode()
node['edges'][character] = next_node
unchecked_nodes.push([node, character, next_node])
node = next_node
i += 1
node['is_final'] = true
@previous_word = word
return
finish: ->
# minimize all unchecked_nodes
@minimize(0)
return
minimize: (lower_bound) ->
# proceed from the leaf up to a certain point
minimized_nodes = @minimized_nodes
unchecked_nodes = @unchecked_nodes
j = unchecked_nodes.length
while j > lower_bound
[parent, character, child] = unchecked_nodes.pop()
child_key = child.<KEY>()
if child_key of minimized_nodes
# replace the child with the previously encountered one
parent['edges'][character] = minimized_nodes[child_key]
else
# add the state to the minimized nodes
minimized_nodes[child_key] = child
j -= 1
return
'accepts': (word) ->
node = @['root']
for edge in word
node = node['edges'][edge]
return false unless node
node['is_final']
global =
if typeof exports is 'object'
exports
else if typeof window is 'object'
window
else
this
global['levenshtein'] ||= {}
global['levenshtein']['DawgNode'] = DawgNode
global['levenshtein']['Dawg'] = Dawg
| true | # ============================================================================
# Taken and modified for my purposes from the following source:
# o http://stevehanov.ca/blog/index.php?id=115
# ============================================================================
#
# This class represents a node in the directed acyclic word graph (DAWG,
# a.k.a. Minimal Acyclic Finite State Automaton, or MA-FSA). It has a list
# of edges to other nodes. It has functions for testing whether it is
# equivalent to another node. Nodes are equivalent if they have identical
# edges, and each identical edge leads to identical states.
class DawgNode
@next_id = 0
constructor: ->
@id = DawgNode.next_id; DawgNode.next_id += 1
@['is_final'] = false
@['edges'] = {}
bisect_left: (edges, edge, lower, upper) ->
while lower < upper
i = (lower + upper) >> 1
if edges[i] < edge
lower = i + 1
else
upper = i
return lower
'toString': ->
edges = []
for label, node of @['edges'] # insertion sort
edge = label + node.id.toString()
edges.splice(@bisect_left(edges, edge, 0, edges.length), 0, edge)
(+ @['is_final']) + edges.join('')
class Dawg
constructor: (dictionary) ->
unless dictionary and typeof dictionary.length is 'number'
throw new Error("Expected dictionary to be array-like")
@previous_word = ''
@['root'] = new DawgNode()
# Here is a list of nodes that have not been checked for duplication.
@unchecked_nodes = []
# Here is a list of unique nodes that have been checked for duplication.
@minimized_nodes = {}
@['insert'](word) for word in dictionary
@finish()
'insert': (word) ->
# Find longest common prefix between word and previous word
i = 0; previous_word = @previous_word
upper_bound =
if word.length < previous_word.length
word.length
else
previous_word.length
i += 1 while i < upper_bound and word[i] is previous_word[i]
# Check the unchecked_nodes for redundant nodes, proceeding from last one
# down to the common prefix size. Then truncate the list at that point.
@minimize(i)
unchecked_nodes = @unchecked_nodes
# Add the suffix, starting from the correct node mid-way through the graph.
if unchecked_nodes.length is 0
node = @['root']
else
node = unchecked_nodes[unchecked_nodes.length - 1][2]
while (character = word[i]) isnt `undefined`
next_node = new DawgNode()
node['edges'][character] = next_node
unchecked_nodes.push([node, character, next_node])
node = next_node
i += 1
node['is_final'] = true
@previous_word = word
return
finish: ->
# minimize all unchecked_nodes
@minimize(0)
return
minimize: (lower_bound) ->
# proceed from the leaf up to a certain point
minimized_nodes = @minimized_nodes
unchecked_nodes = @unchecked_nodes
j = unchecked_nodes.length
while j > lower_bound
[parent, character, child] = unchecked_nodes.pop()
child_key = child.PI:KEY:<KEY>END_PI()
if child_key of minimized_nodes
# replace the child with the previously encountered one
parent['edges'][character] = minimized_nodes[child_key]
else
# add the state to the minimized nodes
minimized_nodes[child_key] = child
j -= 1
return
'accepts': (word) ->
node = @['root']
for edge in word
node = node['edges'][edge]
return false unless node
node['is_final']
global =
if typeof exports is 'object'
exports
else if typeof window is 'object'
window
else
this
global['levenshtein'] ||= {}
global['levenshtein']['DawgNode'] = DawgNode
global['levenshtein']['Dawg'] = Dawg
|
[
{
"context": "belongsTo\"\n models = models[0]\n\n key = key[0].toLowerCase() + key.substr(1)\n\n # add the instance to the op",
"end": 6229,
"score": 0.8920140862464905,
"start": 6207,
"tag": "KEY",
"value": "key[0].toLowerCase() +"
},
{
"context": " models[0]\n\n key = key[0].toLowerCase() + key.substr(1)\n\n # add the instance to the options, so the",
"end": 6242,
"score": 0.9297969937324524,
"start": 6234,
"tag": "KEY",
"value": "substr(1"
}
] | src/server/models/dao/sequelize.coffee | komola/salad | 2 | class Salad.DAO.Sequelize extends Salad.DAO.Base
create: (attributes, callback) ->
attributes = @_cleanAttributes attributes
options = {}
if App.transaction
options.transaction = App.transaction
query = @daoModelInstance.create(attributes, options)
query.then (daoResource) =>
resource = @_buildModelInstance daoResource
return callback null, resource
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Create: Query returned error",
sql: error.sql
attributes: attributes
App.Logger.error error
return callback error
# TODO: Optimize this. Right now this would create an additional select and update
# query for each update operation.
# We could use a instance hash of all daoModel objects and then just update those
_getSequelizeModelBySaladModel: (model, callback) ->
options = {}
if App.transaction
options.transaction = App.transaction
conditions =
where:
id: model.get("id")
query = @daoModelInstance.find(conditions, options)
query.then (sequelizeModel) =>
unless sequelizeModel
error = new Error "Could not find model with id: #{model.get("id")}"
return callback error
return callback null, sequelizeModel
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Find: Query returned error",
sql: error.sql
conditions: conditions
App.Logger.error error
return callback error
update: (model, attributes, callback) ->
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
options =
fields: _.keys(attributes)
if App.transaction
options.transaction = App.transaction
query = sequelizeModel.updateAttributes(attributes, options)
query.then (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Update: Query returned error",
sql: error.sql
attributes: attributes
options: _.omit options, "transaction"
App.Logger.error error
return callback error
###
Destroy models in the database
Usage:
# destroy single instance
App.Todo.first (err, todo) =>
todo.destroy()
# destroy all objects
App.Todo.destroy (err) =>
console.log "everything gone"
###
destroy: (model, callback) ->
if model instanceof Salad.Model
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
options = {}
if App.transaction
options.transaction = App.transaction
query = sequelizeModel.destroy(options)
query.then =>
callback null
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Destroy: Query returned error",
sql: error.sql
App.Logger.error error
return callback error
else
sequelizeModel = @daoModelInstance
options = {}
if App.transaction
options.transaction = App.transaction
options.where = model.conditions
query = sequelizeModel.destroy(options)
query.then =>
return callback null
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Query returned error",
sql: error.sql
App.Logger.error error
return callback error
findAll: (options, callback) ->
params = @_buildOptions options
if App.transaction
params.transaction = App.transaction
query = @daoModelInstance.findAll(params)
query.then (rawResources) =>
resources = []
for res in rawResources
resources.push @_buildModelInstance res
callback null, resources
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "findAll: Query returned error",
sql: error.sql
parameter: params
App.Logger.error error
return callback error
count: (options, callback) ->
params = @_buildOptions options
if App.transaction
params.transaction = App.transaction
query = @daoModelInstance.count(params)
query.then (count) =>
callback null, count
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Count: Query returned error",
sql: error.sql
parameter: params
App.Logger.error error
return callback error
lazyInstantiate: (daoInstance) =>
@_buildModelInstance daoInstance
_cleanAttributes: (rawAttributes) =>
attributes = {}
attributes[key] = val for key, val of rawAttributes when val isnt null
attributes
_buildModelInstance: (daoInstance) =>
options =
isNew: false
daoInstance: @
eagerlyLoadedAssociations: {}
# make a copy of the datavalues.
# the possibly eagerloaded associations will be removed from this
# object later because they are initialized in a different way
dataValues = _.clone daoInstance.dataValues
associationKeys = _.map @modelClass.metadata().associations, "as"
# TODO: When does this happen? Seems like dataValues is null
for key in associationKeys when dataValues?[key]
delete dataValues[key]
# fetch the association model class from the associations object
associationModelClass = @modelClass.getAssociation key
associationType = @modelClass.getAssociationType key
daoModels = daoInstance.dataValues[key]
models = null
if daoModels is null
continue
# create an instance of the associated model passing along our dao model instance
if associationType is "belongsTo"
daoModels = [daoModels]
models = daoModels.map associationModelClass.daoInstance.lazyInstantiate
# Unwrap the model from the array if it is a belongsTo association.
# There can only be one association of this model
if associationType is "belongsTo"
models = models[0]
key = key[0].toLowerCase() + key.substr(1)
# add the instance to the options, so the constructor of modelInstance
# model can pick them up
options.eagerlyLoadedAssociations[key] = models
attributes = dataValues
return new @modelClass attributes, options
_buildOptions: (options) ->
params = {}
if _.keys(options.conditions).length > 0
params.where = options.conditions
# Apply search parameters
if _.keys(options.searches).length > 0
for field, matchString of options.searches
searchCondition = {}
searchCondition[field] = {
# DEPRECATED: This is deprecated in future sequelize versions
$iLike: "%#{matchString}%"
}
params.where = Object.assign(params.where || {}, searchCondition)
if options.limit > 0
params.limit = options.limit
if options.offset > 0
params.offset = options.offset
if options.order.length > 0
# transform the order params into i.e. 'name DESC'
order = []
for elm in options.order
order.push [
# BUG this will cause problems with mysql drivers because the
# escaping is off
"\"#{elm.field}\""
elm.type.toUpperCase()
]
params.order = order
if options.contains.length > 0
tableName = @modelClass.daoInstance.daoModelInstance.name
params.where or= {}
for contains in options.contains
params.where[contains.field] = {
"$contains": [contains.value]
}
if params.limit is -1
delete params.limit
if options.includes?.length > 0
params.include = []
for option in options.includes
option = @_transformInclude option
params.include.push option
return params
_transformInclude: (include) ->
if typeof include is "object" and include.as
include.model = include.model.daoModelInstance
if include.includes
nestedIncludes = []
for nestedInclude in include.includes
nestedIncludes.push @_transformInclude(nestedInclude)
delete include.includes
include.include = nestedIncludes
include
###
Increment the field of a model.
This prevents concurrency issues
Usage:
App.Model.first (err, model) =>
model.increment "field", 3, (err, newModel) =>
console.log model.get("field") is newModel.get("field") # => true
###
increment: (model, field, change, callback) =>
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
successCallback = (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
options = {}
if typeof field is "object"
options.by = 1
else
options.by = change
if App.transaction
options.transaction = App.transaction
sequelizeModel.increment(field, options).then successCallback
###
Decrement the field of a model
This prevents concurrency issues
Usage:
App.Model.first (err, model) =>
model.decrement "field", 3, (err, newModel) =>
console.log model.get("field") is newModel.get("field") # => true
###
decrement: (model, field, change, callback) =>
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
successCallback = (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
options = {}
if typeof field is "object"
options.by = 1
else
options.by = change
if App.transaction
options.transaction = App.transaction
sequelizeModel.decrement(field, options).then successCallback
| 157373 | class Salad.DAO.Sequelize extends Salad.DAO.Base
create: (attributes, callback) ->
attributes = @_cleanAttributes attributes
options = {}
if App.transaction
options.transaction = App.transaction
query = @daoModelInstance.create(attributes, options)
query.then (daoResource) =>
resource = @_buildModelInstance daoResource
return callback null, resource
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Create: Query returned error",
sql: error.sql
attributes: attributes
App.Logger.error error
return callback error
# TODO: Optimize this. Right now this would create an additional select and update
# query for each update operation.
# We could use a instance hash of all daoModel objects and then just update those
_getSequelizeModelBySaladModel: (model, callback) ->
options = {}
if App.transaction
options.transaction = App.transaction
conditions =
where:
id: model.get("id")
query = @daoModelInstance.find(conditions, options)
query.then (sequelizeModel) =>
unless sequelizeModel
error = new Error "Could not find model with id: #{model.get("id")}"
return callback error
return callback null, sequelizeModel
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Find: Query returned error",
sql: error.sql
conditions: conditions
App.Logger.error error
return callback error
update: (model, attributes, callback) ->
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
options =
fields: _.keys(attributes)
if App.transaction
options.transaction = App.transaction
query = sequelizeModel.updateAttributes(attributes, options)
query.then (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Update: Query returned error",
sql: error.sql
attributes: attributes
options: _.omit options, "transaction"
App.Logger.error error
return callback error
###
Destroy models in the database
Usage:
# destroy single instance
App.Todo.first (err, todo) =>
todo.destroy()
# destroy all objects
App.Todo.destroy (err) =>
console.log "everything gone"
###
destroy: (model, callback) ->
if model instanceof Salad.Model
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
options = {}
if App.transaction
options.transaction = App.transaction
query = sequelizeModel.destroy(options)
query.then =>
callback null
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Destroy: Query returned error",
sql: error.sql
App.Logger.error error
return callback error
else
sequelizeModel = @daoModelInstance
options = {}
if App.transaction
options.transaction = App.transaction
options.where = model.conditions
query = sequelizeModel.destroy(options)
query.then =>
return callback null
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Query returned error",
sql: error.sql
App.Logger.error error
return callback error
findAll: (options, callback) ->
params = @_buildOptions options
if App.transaction
params.transaction = App.transaction
query = @daoModelInstance.findAll(params)
query.then (rawResources) =>
resources = []
for res in rawResources
resources.push @_buildModelInstance res
callback null, resources
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "findAll: Query returned error",
sql: error.sql
parameter: params
App.Logger.error error
return callback error
count: (options, callback) ->
params = @_buildOptions options
if App.transaction
params.transaction = App.transaction
query = @daoModelInstance.count(params)
query.then (count) =>
callback null, count
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Count: Query returned error",
sql: error.sql
parameter: params
App.Logger.error error
return callback error
lazyInstantiate: (daoInstance) =>
@_buildModelInstance daoInstance
_cleanAttributes: (rawAttributes) =>
attributes = {}
attributes[key] = val for key, val of rawAttributes when val isnt null
attributes
_buildModelInstance: (daoInstance) =>
options =
isNew: false
daoInstance: @
eagerlyLoadedAssociations: {}
# make a copy of the datavalues.
# the possibly eagerloaded associations will be removed from this
# object later because they are initialized in a different way
dataValues = _.clone daoInstance.dataValues
associationKeys = _.map @modelClass.metadata().associations, "as"
# TODO: When does this happen? Seems like dataValues is null
for key in associationKeys when dataValues?[key]
delete dataValues[key]
# fetch the association model class from the associations object
associationModelClass = @modelClass.getAssociation key
associationType = @modelClass.getAssociationType key
daoModels = daoInstance.dataValues[key]
models = null
if daoModels is null
continue
# create an instance of the associated model passing along our dao model instance
if associationType is "belongsTo"
daoModels = [daoModels]
models = daoModels.map associationModelClass.daoInstance.lazyInstantiate
# Unwrap the model from the array if it is a belongsTo association.
# There can only be one association of this model
if associationType is "belongsTo"
models = models[0]
key = <KEY> key.<KEY>)
# add the instance to the options, so the constructor of modelInstance
# model can pick them up
options.eagerlyLoadedAssociations[key] = models
attributes = dataValues
return new @modelClass attributes, options
_buildOptions: (options) ->
params = {}
if _.keys(options.conditions).length > 0
params.where = options.conditions
# Apply search parameters
if _.keys(options.searches).length > 0
for field, matchString of options.searches
searchCondition = {}
searchCondition[field] = {
# DEPRECATED: This is deprecated in future sequelize versions
$iLike: "%#{matchString}%"
}
params.where = Object.assign(params.where || {}, searchCondition)
if options.limit > 0
params.limit = options.limit
if options.offset > 0
params.offset = options.offset
if options.order.length > 0
# transform the order params into i.e. 'name DESC'
order = []
for elm in options.order
order.push [
# BUG this will cause problems with mysql drivers because the
# escaping is off
"\"#{elm.field}\""
elm.type.toUpperCase()
]
params.order = order
if options.contains.length > 0
tableName = @modelClass.daoInstance.daoModelInstance.name
params.where or= {}
for contains in options.contains
params.where[contains.field] = {
"$contains": [contains.value]
}
if params.limit is -1
delete params.limit
if options.includes?.length > 0
params.include = []
for option in options.includes
option = @_transformInclude option
params.include.push option
return params
_transformInclude: (include) ->
if typeof include is "object" and include.as
include.model = include.model.daoModelInstance
if include.includes
nestedIncludes = []
for nestedInclude in include.includes
nestedIncludes.push @_transformInclude(nestedInclude)
delete include.includes
include.include = nestedIncludes
include
###
Increment the field of a model.
This prevents concurrency issues
Usage:
App.Model.first (err, model) =>
model.increment "field", 3, (err, newModel) =>
console.log model.get("field") is newModel.get("field") # => true
###
increment: (model, field, change, callback) =>
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
successCallback = (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
options = {}
if typeof field is "object"
options.by = 1
else
options.by = change
if App.transaction
options.transaction = App.transaction
sequelizeModel.increment(field, options).then successCallback
###
Decrement the field of a model
This prevents concurrency issues
Usage:
App.Model.first (err, model) =>
model.decrement "field", 3, (err, newModel) =>
console.log model.get("field") is newModel.get("field") # => true
###
decrement: (model, field, change, callback) =>
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
successCallback = (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
options = {}
if typeof field is "object"
options.by = 1
else
options.by = change
if App.transaction
options.transaction = App.transaction
sequelizeModel.decrement(field, options).then successCallback
| true | class Salad.DAO.Sequelize extends Salad.DAO.Base
create: (attributes, callback) ->
attributes = @_cleanAttributes attributes
options = {}
if App.transaction
options.transaction = App.transaction
query = @daoModelInstance.create(attributes, options)
query.then (daoResource) =>
resource = @_buildModelInstance daoResource
return callback null, resource
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Create: Query returned error",
sql: error.sql
attributes: attributes
App.Logger.error error
return callback error
# TODO: Optimize this. Right now this would create an additional select and update
# query for each update operation.
# We could use a instance hash of all daoModel objects and then just update those
_getSequelizeModelBySaladModel: (model, callback) ->
options = {}
if App.transaction
options.transaction = App.transaction
conditions =
where:
id: model.get("id")
query = @daoModelInstance.find(conditions, options)
query.then (sequelizeModel) =>
unless sequelizeModel
error = new Error "Could not find model with id: #{model.get("id")}"
return callback error
return callback null, sequelizeModel
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Find: Query returned error",
sql: error.sql
conditions: conditions
App.Logger.error error
return callback error
update: (model, attributes, callback) ->
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
options =
fields: _.keys(attributes)
if App.transaction
options.transaction = App.transaction
query = sequelizeModel.updateAttributes(attributes, options)
query.then (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Update: Query returned error",
sql: error.sql
attributes: attributes
options: _.omit options, "transaction"
App.Logger.error error
return callback error
###
Destroy models in the database
Usage:
# destroy single instance
App.Todo.first (err, todo) =>
todo.destroy()
# destroy all objects
App.Todo.destroy (err) =>
console.log "everything gone"
###
destroy: (model, callback) ->
if model instanceof Salad.Model
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
options = {}
if App.transaction
options.transaction = App.transaction
query = sequelizeModel.destroy(options)
query.then =>
callback null
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Destroy: Query returned error",
sql: error.sql
App.Logger.error error
return callback error
else
sequelizeModel = @daoModelInstance
options = {}
if App.transaction
options.transaction = App.transaction
options.where = model.conditions
query = sequelizeModel.destroy(options)
query.then =>
return callback null
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Query returned error",
sql: error.sql
App.Logger.error error
return callback error
findAll: (options, callback) ->
params = @_buildOptions options
if App.transaction
params.transaction = App.transaction
query = @daoModelInstance.findAll(params)
query.then (rawResources) =>
resources = []
for res in rawResources
resources.push @_buildModelInstance res
callback null, resources
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "findAll: Query returned error",
sql: error.sql
parameter: params
App.Logger.error error
return callback error
count: (options, callback) ->
params = @_buildOptions options
if App.transaction
params.transaction = App.transaction
query = @daoModelInstance.count(params)
query.then (count) =>
callback null, count
query.catch (error) =>
if Salad.env isnt "test"
App.Logger.error "Count: Query returned error",
sql: error.sql
parameter: params
App.Logger.error error
return callback error
lazyInstantiate: (daoInstance) =>
@_buildModelInstance daoInstance
_cleanAttributes: (rawAttributes) =>
attributes = {}
attributes[key] = val for key, val of rawAttributes when val isnt null
attributes
_buildModelInstance: (daoInstance) =>
options =
isNew: false
daoInstance: @
eagerlyLoadedAssociations: {}
# make a copy of the datavalues.
# the possibly eagerloaded associations will be removed from this
# object later because they are initialized in a different way
dataValues = _.clone daoInstance.dataValues
associationKeys = _.map @modelClass.metadata().associations, "as"
# TODO: When does this happen? Seems like dataValues is null
for key in associationKeys when dataValues?[key]
delete dataValues[key]
# fetch the association model class from the associations object
associationModelClass = @modelClass.getAssociation key
associationType = @modelClass.getAssociationType key
daoModels = daoInstance.dataValues[key]
models = null
if daoModels is null
continue
# create an instance of the associated model passing along our dao model instance
if associationType is "belongsTo"
daoModels = [daoModels]
models = daoModels.map associationModelClass.daoInstance.lazyInstantiate
# Unwrap the model from the array if it is a belongsTo association.
# There can only be one association of this model
if associationType is "belongsTo"
models = models[0]
key = PI:KEY:<KEY>END_PI key.PI:KEY:<KEY>END_PI)
# add the instance to the options, so the constructor of modelInstance
# model can pick them up
options.eagerlyLoadedAssociations[key] = models
attributes = dataValues
return new @modelClass attributes, options
_buildOptions: (options) ->
params = {}
if _.keys(options.conditions).length > 0
params.where = options.conditions
# Apply search parameters
if _.keys(options.searches).length > 0
for field, matchString of options.searches
searchCondition = {}
searchCondition[field] = {
# DEPRECATED: This is deprecated in future sequelize versions
$iLike: "%#{matchString}%"
}
params.where = Object.assign(params.where || {}, searchCondition)
if options.limit > 0
params.limit = options.limit
if options.offset > 0
params.offset = options.offset
if options.order.length > 0
# transform the order params into i.e. 'name DESC'
order = []
for elm in options.order
order.push [
# BUG this will cause problems with mysql drivers because the
# escaping is off
"\"#{elm.field}\""
elm.type.toUpperCase()
]
params.order = order
if options.contains.length > 0
tableName = @modelClass.daoInstance.daoModelInstance.name
params.where or= {}
for contains in options.contains
params.where[contains.field] = {
"$contains": [contains.value]
}
if params.limit is -1
delete params.limit
if options.includes?.length > 0
params.include = []
for option in options.includes
option = @_transformInclude option
params.include.push option
return params
_transformInclude: (include) ->
if typeof include is "object" and include.as
include.model = include.model.daoModelInstance
if include.includes
nestedIncludes = []
for nestedInclude in include.includes
nestedIncludes.push @_transformInclude(nestedInclude)
delete include.includes
include.include = nestedIncludes
include
###
Increment the field of a model.
This prevents concurrency issues
Usage:
App.Model.first (err, model) =>
model.increment "field", 3, (err, newModel) =>
console.log model.get("field") is newModel.get("field") # => true
###
increment: (model, field, change, callback) =>
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
successCallback = (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
options = {}
if typeof field is "object"
options.by = 1
else
options.by = change
if App.transaction
options.transaction = App.transaction
sequelizeModel.increment(field, options).then successCallback
###
Decrement the field of a model
This prevents concurrency issues
Usage:
App.Model.first (err, model) =>
model.decrement "field", 3, (err, newModel) =>
console.log model.get("field") is newModel.get("field") # => true
###
decrement: (model, field, change, callback) =>
@_getSequelizeModelBySaladModel model, (err, sequelizeModel) =>
return callback err if err
successCallback = (daoResource) =>
resource = @_buildModelInstance daoResource
callback null, resource
options = {}
if typeof field is "object"
options.by = 1
else
options.by = change
if App.transaction
options.transaction = App.transaction
sequelizeModel.decrement(field, options).then successCallback
|
[
{
"context": "t base64 <text> - encode to base64\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n\n ",
"end": 190,
"score": 0.9997409582138062,
"start": 183,
"tag": "USERNAME",
"value": "bouzuya"
},
{
"context": "text> - encode to base64\n#\n# Author:\n# bouzuya <m@bouzuya.net>\n#\nmodule.exports = (robot) ->\n\n robot.respond /",
"end": 205,
"score": 0.9999287724494934,
"start": 192,
"tag": "EMAIL",
"value": "m@bouzuya.net"
}
] | src/scripts/base64.coffee | bouzuya/hubot-base64 | 1 | # Description
# A Hubot script that encode to base64
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot base64 <text> - encode to base64
#
# Author:
# bouzuya <m@bouzuya.net>
#
module.exports = (robot) ->
robot.respond /base64\s+(.+?)\s*$/i, (res) ->
text = res.match[1]
buffer = new Buffer text, 'utf-8'
res.send buffer.toString('base64')
| 99128 | # Description
# A Hubot script that encode to base64
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot base64 <text> - encode to base64
#
# Author:
# bouzuya <<EMAIL>>
#
module.exports = (robot) ->
robot.respond /base64\s+(.+?)\s*$/i, (res) ->
text = res.match[1]
buffer = new Buffer text, 'utf-8'
res.send buffer.toString('base64')
| true | # Description
# A Hubot script that encode to base64
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot base64 <text> - encode to base64
#
# Author:
# bouzuya <PI:EMAIL:<EMAIL>END_PI>
#
module.exports = (robot) ->
robot.respond /base64\s+(.+?)\s*$/i, (res) ->
text = res.match[1]
buffer = new Buffer text, 'utf-8'
res.send buffer.toString('base64')
|
[
{
"context": "\n #unless password && record.password==SS.server.user.crpassword(password)\n # delete record.email\n ",
"end": 2950,
"score": 0.9521849155426025,
"start": 2925,
"tag": "PASSWORD",
"value": "SS.server.user.crpassword"
},
{
"context": "hen \"reset\"\n doc.password = doc.mail.newpass\n doc.mail=\n ",
"end": 6201,
"score": 0.9992088675498962,
"start": 6185,
"tag": "PASSWORD",
"value": "doc.mail.newpass"
},
{
"context": "s.findOne {\"userid\":req.session.userId,\"password\":Server.user.crpassword(query.password)},(err,record)=>\n ",
"end": 8019,
"score": 0.6840689182281494,
"start": 8013,
"tag": "PASSWORD",
"value": "Server"
},
{
"context": "erid\":req.session.userId,\"password\":Server.user.crpassword(query.password)},(err,record)=>\n if er",
"end": 8035,
"score": 0.6041399240493774,
"start": 8027,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "eq.session.userId}, {$set:{password:Server.user.crpassword(query.newpass)}},{safe:true},(err,count)=>\n ",
"end": 8444,
"score": 0.5418962240219116,
"start": 8436,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "One {\"userid\":req.session.userId,\"password\":Server.user.crpassword(query.password)},(err,record)=>\n if er",
"end": 8748,
"score": 0.6617788076400757,
"start": 8733,
"tag": "PASSWORD",
"value": "user.crpassword"
},
{
"context": " {\n userid: query.userid\n password: Server.user.crpassword(query.password)\n name: query.userid\n ",
"end": 11072,
"score": 0.995408833026886,
"start": 11050,
"tag": "PASSWORD",
"value": "Server.user.crpassword"
},
{
"context": "rid\n password: Server.user.crpassword(query.password)\n name: query.userid\n icon:\"\" # ico",
"end": 11087,
"score": 0.9455097913742065,
"start": 11079,
"tag": "PASSWORD",
"value": "password"
}
] | server/rpc/user.coffee | Yukimir/jinrou | 0 | # Server-side Code
Shared=
game:require '../../client/code/shared/game.coffee'
prize:require '../../client/code/shared/prize.coffee'
Server=
user:module.exports
prize:require '../prize.coffee'
oauth:require '../oauth.coffee'
mailer=require '../mailer.coffee'
crypto=require 'crypto'
url=require 'url'
# 内部関数的なログイン
login= (query,req,cb,ss)->
auth=require('./../auth.coffee')
#req.session.authenticate './session_storage/internal.coffee', query, (response)=>
auth.authenticate query,(response)=>
if response.success
req.session.setUserId response.userid
#console.log "login."
#console.log req
response.ip=req.clientIp
req.session.user=response
#req.session.room=null # 今入っている部屋
req.session.channel.reset()
req.session.save (err)->
# お知らせ情報をとってきてあげる
M.news.find().sort({time:-1}).nextObject (err,doc)->
cb {
login:true
lastNews:doc?.time
}
# IPアドレスを記録してあげる
M.users.update {"userid":response.userid},{$set:{ip:response.ip}}
else
cb {
login:false
}
exports.actions =(req,res,ss)->
req.use 'user.fire.wall'
req.use 'session'
# ログイン
# cb: 失敗なら真
login: (query)->
login query,req,res,ss
# ログアウト
logout: ->
#req.session.user.logout(cb)
req.session.setUserId null
req.session.channel.reset()
req.session.save (err)->
res()
# 新規登録
# cb: 错误メッセージ(成功なら偽)
newentry: (query)->
unless /^\w+$/.test(query.userid)
res {
login:false
error:"ID包含了非法字符"
}
return
unless /^\w+$/.test(query.password)
res {
login:false
error:"密码包含了非法字符"
}
return
M.users.find({"userid":query.userid}).count (err,count)->
if count>0
res {
login:false
error:"这个ID已被使用"
}
return
userobj = makeuserdata(query)
M.users.insert userobj,{safe:true},(err,records)->
if err?
res {
login:false
error:"DB err:#{err}"
}
return
login query,req,res,ss
# ユーザー数据が欲しい
userData: (userid,password)->
M.users.findOne {"userid":userid},(err,record)->
if err?
res null
return
if !record?
res null
return
delete record.password
delete record.prize
#unless password && record.password==SS.server.user.crpassword(password)
# delete record.email
res record
myProfile: ->
unless req.session.userId
res null
return
u=JSON.parse JSON.stringify req.session.user
if u
res userProfile(u)
else
res null
# お知らせをとってきてもらう
getNews:->
M.news.find().sort({time:-1}).limit(5).toArray (err,results)->
if err?
res {error:err}
return
res results
# twitter头像を調べてあげる
getTwitterIcon:(id)->
Server.oauth.getTwitterIcon id,(url)->
res url
# 配置变更 返り値=变更後 {"error":"message"}
changeProfile: (query)->
M.users.findOne {"userid":req.session.userId,"password":Server.user.crpassword(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if query.name?
if query.name==""
res {error:"请输入昵称"}
return
record.name=query.name
#max bytes of nick name
maxLength=20
record.name = record.name.trim()
if record.name == ''
res {error:"昵称不能仅为空格"}
return
else if record.name.replace(/[^\x00-\xFF]/g,'**').length > maxLength
res {error:"昵称不能超过"+maxLength+"个字节。"}
return
if query.comment? && query.comment.length<=200
record.comment=query.comment
if query.icon? && query.icon.length<=300
record.icon=query.icon
M.users.update {"userid":req.session.userId}, record, {safe:true},(err,count)=>
if err?
res {error:"配置变更失败"}
return
delete record.password
req.session.user=record
req.session.save ->
res userProfile(record)
sendConfirmMail:(query)->
mailer.sendConfirmMail(query,req,res,ss)
confirmMail:(query)->
if query.match /\/my\?token\=(\w){128}\×tamp\=(\d){13}$/
query = url.parse(query,true).query
# console.log query
M.users.findOne {"mail.token":query.token,"mail.timestamp":Number(query.timestamp)},(err,doc)->
# 有效时间:1小时
if err?
res {error:"验证链接无效或已经过期"}
return
unless doc?.mail? && Date.now() < Number(doc.mail.timestamp) + 3600*1000
res {error:"验证链接无效或已经过期"}
return
strfor=doc.mail.for
switch doc.mail.for
when "confirm"
doc.mail=
address:doc.mail.new
verified:true
when "change"
doc.mail=
address:doc.mail.new
verified:true
when "remove"
delete doc.mail
when "reset"
doc.password = doc.mail.newpass
doc.mail=
address:doc.mail.address
verified:true
M.users.update {"userid":doc.userid}, doc, {safe:true},(err,count)=>
if err?
res {error:"邮箱绑定失败"}
return
delete doc.password
req.session.user = doc
req.session.save ->
if strfor in ["confirm","change"]
doc.info="邮箱「#{doc.mail.address}」认证成功。"
else if strfor == "remove"
doc.mail=
address:""
verified:false
doc.info="邮箱解除认证成功。"
else if strfor == "reset"
doc.info="密码重置成功,请重新登陆。"
doc.reset=true
res doc
return
res null
resetPassword:(query)->
unless /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test query.mail
res {info:"请输入有效的邮箱地址"}
query.userid = query.userid.trim()
query.mail = query.mail.trim()
if query.newpass!=query.newpass2
res {error:"两次输入的密码不一致"}
return
M.users.findOne {"userid":query.userid,"mail.address":query.mail,"mail.verified":true},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"账号或邮箱不正确"}
return
else
mailer.sendResetMail(query,req,res,ss)
return
changePassword:(query)->
M.users.findOne {"userid":req.session.userId,"password":Server.user.crpassword(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if query.newpass!=query.newpass2
res {error:"两次输入的密码不一致"}
return
M.users.update {"userid":req.session.userId}, {$set:{password:Server.user.crpassword(query.newpass)}},{safe:true},(err,count)=>
if err?
res {error:"配置变更失败"}
return
res null
usePrize: (query)->
# 表示する称号を変える query.prize
M.users.findOne {"userid":req.session.userId,"password":Server.user.crpassword(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if typeof query.prize?.every=="function"
# 称号構成を得る
comp=Shared.prize.getPrizesComposition record.prize.length
if query.prize.every((x,i)->x.type==comp[i])
# 合致する
if query.prize.every((x)->
if x.type=="prize"
!x.value || x.value in record.prize # 持っている称号のみ
else
!x.value || x.value in Shared.prize.conjunctions
)
# 所持もOK
M.users.update {"userid":req.session.userId}, {$set:{nowprize:query.prize}},{safe:true},(err)=>
req.session.user.nowprize=query.prize
req.session.save ->
res null
else
console.log "invalid1 ",query.prize,record.prize
res {error:"称号无效"}
else
console.log "invalid2",query.prize,comp
res {error:"称号无效"}
else
console.log "invalid3",query.prize
res {error:"称号无效"}
# 成績をくわしく見る
getMyuserlog:->
unless req.session.userId
res {error:"请登陆"}
return
myid=req.session.userId
# DBから自己のやつを引っ張ってくる
results=[]
M.userlogs.findOne {userid:myid},(err,doc)->
if err?
console.error err
unless doc?
# 戦績数据がない
res null
return
res doc
######
#密码ハッシュ化
# crpassword: (raw)-> raw && hashlib.sha256(raw+hashlib.md5(raw))
exports.crpassword= (raw)->
return "" unless raw
sha256=crypto.createHash "sha256"
md5=crypto.createHash "md5"
md5.update raw # md5でハッシュ化
sha256.update raw+md5.digest 'hex' # sha256でさらにハッシュ化
sha256.digest 'hex' # 结果を返す
#ユーザー数据作る
makeuserdata=(query)->
{
userid: query.userid
password: Server.user.crpassword(query.password)
name: query.userid
icon:"" # iconのURL
comment: ""
win:[] # 勝ち試合
lose:[] # 負け試合
gone:[] # 行方不明試合
ip:"" # IPアドレス
prize:[]# 现在持っている称号
ownprize:[] # 何かで与えられた称号(prizeに含まれる)
nowprize:null # 现在设定している肩書き
# [{type:"prize",value:(prizeid)},{type:"conjunction",value:"が"},...]
}
# profileに表示する用のユーザーデータをdocから作る
userProfile = (doc)->
doc.wp = unless doc.win? && doc.lose?
"???"
else if doc.win.length+doc.lose.length==0
"???"
else
"#{(doc.win.length/(doc.win.length+doc.lose.length)*100).toPrecision(2)}%"
# 称号の処理をしてあげる
doc.prize ?= []
doc.prizenames = doc.prize.map (x)->{id:x,name:Server.prize.prizeName(x),phonetic:Server.prize.prizePhonetic(x) ? "undefined"}
delete doc.prize
if !doc.mail?
doc.mail =
address:""
new:""
verified:false
else
doc.mail =
address:doc.mail.address
new:doc.mail.new
verified:doc.mail.verified
return doc
| 164808 | # Server-side Code
Shared=
game:require '../../client/code/shared/game.coffee'
prize:require '../../client/code/shared/prize.coffee'
Server=
user:module.exports
prize:require '../prize.coffee'
oauth:require '../oauth.coffee'
mailer=require '../mailer.coffee'
crypto=require 'crypto'
url=require 'url'
# 内部関数的なログイン
login= (query,req,cb,ss)->
auth=require('./../auth.coffee')
#req.session.authenticate './session_storage/internal.coffee', query, (response)=>
auth.authenticate query,(response)=>
if response.success
req.session.setUserId response.userid
#console.log "login."
#console.log req
response.ip=req.clientIp
req.session.user=response
#req.session.room=null # 今入っている部屋
req.session.channel.reset()
req.session.save (err)->
# お知らせ情報をとってきてあげる
M.news.find().sort({time:-1}).nextObject (err,doc)->
cb {
login:true
lastNews:doc?.time
}
# IPアドレスを記録してあげる
M.users.update {"userid":response.userid},{$set:{ip:response.ip}}
else
cb {
login:false
}
exports.actions =(req,res,ss)->
req.use 'user.fire.wall'
req.use 'session'
# ログイン
# cb: 失敗なら真
login: (query)->
login query,req,res,ss
# ログアウト
logout: ->
#req.session.user.logout(cb)
req.session.setUserId null
req.session.channel.reset()
req.session.save (err)->
res()
# 新規登録
# cb: 错误メッセージ(成功なら偽)
newentry: (query)->
unless /^\w+$/.test(query.userid)
res {
login:false
error:"ID包含了非法字符"
}
return
unless /^\w+$/.test(query.password)
res {
login:false
error:"密码包含了非法字符"
}
return
M.users.find({"userid":query.userid}).count (err,count)->
if count>0
res {
login:false
error:"这个ID已被使用"
}
return
userobj = makeuserdata(query)
M.users.insert userobj,{safe:true},(err,records)->
if err?
res {
login:false
error:"DB err:#{err}"
}
return
login query,req,res,ss
# ユーザー数据が欲しい
userData: (userid,password)->
M.users.findOne {"userid":userid},(err,record)->
if err?
res null
return
if !record?
res null
return
delete record.password
delete record.prize
#unless password && record.password==<PASSWORD>(password)
# delete record.email
res record
myProfile: ->
unless req.session.userId
res null
return
u=JSON.parse JSON.stringify req.session.user
if u
res userProfile(u)
else
res null
# お知らせをとってきてもらう
getNews:->
M.news.find().sort({time:-1}).limit(5).toArray (err,results)->
if err?
res {error:err}
return
res results
# twitter头像を調べてあげる
getTwitterIcon:(id)->
Server.oauth.getTwitterIcon id,(url)->
res url
# 配置变更 返り値=变更後 {"error":"message"}
changeProfile: (query)->
M.users.findOne {"userid":req.session.userId,"password":Server.user.crpassword(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if query.name?
if query.name==""
res {error:"请输入昵称"}
return
record.name=query.name
#max bytes of nick name
maxLength=20
record.name = record.name.trim()
if record.name == ''
res {error:"昵称不能仅为空格"}
return
else if record.name.replace(/[^\x00-\xFF]/g,'**').length > maxLength
res {error:"昵称不能超过"+maxLength+"个字节。"}
return
if query.comment? && query.comment.length<=200
record.comment=query.comment
if query.icon? && query.icon.length<=300
record.icon=query.icon
M.users.update {"userid":req.session.userId}, record, {safe:true},(err,count)=>
if err?
res {error:"配置变更失败"}
return
delete record.password
req.session.user=record
req.session.save ->
res userProfile(record)
sendConfirmMail:(query)->
mailer.sendConfirmMail(query,req,res,ss)
confirmMail:(query)->
if query.match /\/my\?token\=(\w){128}\×tamp\=(\d){13}$/
query = url.parse(query,true).query
# console.log query
M.users.findOne {"mail.token":query.token,"mail.timestamp":Number(query.timestamp)},(err,doc)->
# 有效时间:1小时
if err?
res {error:"验证链接无效或已经过期"}
return
unless doc?.mail? && Date.now() < Number(doc.mail.timestamp) + 3600*1000
res {error:"验证链接无效或已经过期"}
return
strfor=doc.mail.for
switch doc.mail.for
when "confirm"
doc.mail=
address:doc.mail.new
verified:true
when "change"
doc.mail=
address:doc.mail.new
verified:true
when "remove"
delete doc.mail
when "reset"
doc.password = <PASSWORD>
doc.mail=
address:doc.mail.address
verified:true
M.users.update {"userid":doc.userid}, doc, {safe:true},(err,count)=>
if err?
res {error:"邮箱绑定失败"}
return
delete doc.password
req.session.user = doc
req.session.save ->
if strfor in ["confirm","change"]
doc.info="邮箱「#{doc.mail.address}」认证成功。"
else if strfor == "remove"
doc.mail=
address:""
verified:false
doc.info="邮箱解除认证成功。"
else if strfor == "reset"
doc.info="密码重置成功,请重新登陆。"
doc.reset=true
res doc
return
res null
resetPassword:(query)->
unless /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test query.mail
res {info:"请输入有效的邮箱地址"}
query.userid = query.userid.trim()
query.mail = query.mail.trim()
if query.newpass!=query.newpass2
res {error:"两次输入的密码不一致"}
return
M.users.findOne {"userid":query.userid,"mail.address":query.mail,"mail.verified":true},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"账号或邮箱不正确"}
return
else
mailer.sendResetMail(query,req,res,ss)
return
changePassword:(query)->
M.users.findOne {"userid":req.session.userId,"password":<PASSWORD>.user.cr<PASSWORD>(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if query.newpass!=query.newpass2
res {error:"两次输入的密码不一致"}
return
M.users.update {"userid":req.session.userId}, {$set:{password:Server.user.cr<PASSWORD>(query.newpass)}},{safe:true},(err,count)=>
if err?
res {error:"配置变更失败"}
return
res null
usePrize: (query)->
# 表示する称号を変える query.prize
M.users.findOne {"userid":req.session.userId,"password":Server.<PASSWORD>(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if typeof query.prize?.every=="function"
# 称号構成を得る
comp=Shared.prize.getPrizesComposition record.prize.length
if query.prize.every((x,i)->x.type==comp[i])
# 合致する
if query.prize.every((x)->
if x.type=="prize"
!x.value || x.value in record.prize # 持っている称号のみ
else
!x.value || x.value in Shared.prize.conjunctions
)
# 所持もOK
M.users.update {"userid":req.session.userId}, {$set:{nowprize:query.prize}},{safe:true},(err)=>
req.session.user.nowprize=query.prize
req.session.save ->
res null
else
console.log "invalid1 ",query.prize,record.prize
res {error:"称号无效"}
else
console.log "invalid2",query.prize,comp
res {error:"称号无效"}
else
console.log "invalid3",query.prize
res {error:"称号无效"}
# 成績をくわしく見る
getMyuserlog:->
unless req.session.userId
res {error:"请登陆"}
return
myid=req.session.userId
# DBから自己のやつを引っ張ってくる
results=[]
M.userlogs.findOne {userid:myid},(err,doc)->
if err?
console.error err
unless doc?
# 戦績数据がない
res null
return
res doc
######
#密码ハッシュ化
# crpassword: (raw)-> raw && hashlib.sha256(raw+hashlib.md5(raw))
exports.crpassword= (raw)->
return "" unless raw
sha256=crypto.createHash "sha256"
md5=crypto.createHash "md5"
md5.update raw # md5でハッシュ化
sha256.update raw+md5.digest 'hex' # sha256でさらにハッシュ化
sha256.digest 'hex' # 结果を返す
#ユーザー数据作る
makeuserdata=(query)->
{
userid: query.userid
password: <PASSWORD>(query.<PASSWORD>)
name: query.userid
icon:"" # iconのURL
comment: ""
win:[] # 勝ち試合
lose:[] # 負け試合
gone:[] # 行方不明試合
ip:"" # IPアドレス
prize:[]# 现在持っている称号
ownprize:[] # 何かで与えられた称号(prizeに含まれる)
nowprize:null # 现在设定している肩書き
# [{type:"prize",value:(prizeid)},{type:"conjunction",value:"が"},...]
}
# profileに表示する用のユーザーデータをdocから作る
userProfile = (doc)->
doc.wp = unless doc.win? && doc.lose?
"???"
else if doc.win.length+doc.lose.length==0
"???"
else
"#{(doc.win.length/(doc.win.length+doc.lose.length)*100).toPrecision(2)}%"
# 称号の処理をしてあげる
doc.prize ?= []
doc.prizenames = doc.prize.map (x)->{id:x,name:Server.prize.prizeName(x),phonetic:Server.prize.prizePhonetic(x) ? "undefined"}
delete doc.prize
if !doc.mail?
doc.mail =
address:""
new:""
verified:false
else
doc.mail =
address:doc.mail.address
new:doc.mail.new
verified:doc.mail.verified
return doc
| true | # Server-side Code
Shared=
game:require '../../client/code/shared/game.coffee'
prize:require '../../client/code/shared/prize.coffee'
Server=
user:module.exports
prize:require '../prize.coffee'
oauth:require '../oauth.coffee'
mailer=require '../mailer.coffee'
crypto=require 'crypto'
url=require 'url'
# 内部関数的なログイン
login= (query,req,cb,ss)->
auth=require('./../auth.coffee')
#req.session.authenticate './session_storage/internal.coffee', query, (response)=>
auth.authenticate query,(response)=>
if response.success
req.session.setUserId response.userid
#console.log "login."
#console.log req
response.ip=req.clientIp
req.session.user=response
#req.session.room=null # 今入っている部屋
req.session.channel.reset()
req.session.save (err)->
# お知らせ情報をとってきてあげる
M.news.find().sort({time:-1}).nextObject (err,doc)->
cb {
login:true
lastNews:doc?.time
}
# IPアドレスを記録してあげる
M.users.update {"userid":response.userid},{$set:{ip:response.ip}}
else
cb {
login:false
}
exports.actions =(req,res,ss)->
req.use 'user.fire.wall'
req.use 'session'
# ログイン
# cb: 失敗なら真
login: (query)->
login query,req,res,ss
# ログアウト
logout: ->
#req.session.user.logout(cb)
req.session.setUserId null
req.session.channel.reset()
req.session.save (err)->
res()
# 新規登録
# cb: 错误メッセージ(成功なら偽)
newentry: (query)->
unless /^\w+$/.test(query.userid)
res {
login:false
error:"ID包含了非法字符"
}
return
unless /^\w+$/.test(query.password)
res {
login:false
error:"密码包含了非法字符"
}
return
M.users.find({"userid":query.userid}).count (err,count)->
if count>0
res {
login:false
error:"这个ID已被使用"
}
return
userobj = makeuserdata(query)
M.users.insert userobj,{safe:true},(err,records)->
if err?
res {
login:false
error:"DB err:#{err}"
}
return
login query,req,res,ss
# ユーザー数据が欲しい
userData: (userid,password)->
M.users.findOne {"userid":userid},(err,record)->
if err?
res null
return
if !record?
res null
return
delete record.password
delete record.prize
#unless password && record.password==PI:PASSWORD:<PASSWORD>END_PI(password)
# delete record.email
res record
myProfile: ->
unless req.session.userId
res null
return
u=JSON.parse JSON.stringify req.session.user
if u
res userProfile(u)
else
res null
# お知らせをとってきてもらう
getNews:->
M.news.find().sort({time:-1}).limit(5).toArray (err,results)->
if err?
res {error:err}
return
res results
# twitter头像を調べてあげる
getTwitterIcon:(id)->
Server.oauth.getTwitterIcon id,(url)->
res url
# 配置变更 返り値=变更後 {"error":"message"}
changeProfile: (query)->
M.users.findOne {"userid":req.session.userId,"password":Server.user.crpassword(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if query.name?
if query.name==""
res {error:"请输入昵称"}
return
record.name=query.name
#max bytes of nick name
maxLength=20
record.name = record.name.trim()
if record.name == ''
res {error:"昵称不能仅为空格"}
return
else if record.name.replace(/[^\x00-\xFF]/g,'**').length > maxLength
res {error:"昵称不能超过"+maxLength+"个字节。"}
return
if query.comment? && query.comment.length<=200
record.comment=query.comment
if query.icon? && query.icon.length<=300
record.icon=query.icon
M.users.update {"userid":req.session.userId}, record, {safe:true},(err,count)=>
if err?
res {error:"配置变更失败"}
return
delete record.password
req.session.user=record
req.session.save ->
res userProfile(record)
sendConfirmMail:(query)->
mailer.sendConfirmMail(query,req,res,ss)
confirmMail:(query)->
if query.match /\/my\?token\=(\w){128}\×tamp\=(\d){13}$/
query = url.parse(query,true).query
# console.log query
M.users.findOne {"mail.token":query.token,"mail.timestamp":Number(query.timestamp)},(err,doc)->
# 有效时间:1小时
if err?
res {error:"验证链接无效或已经过期"}
return
unless doc?.mail? && Date.now() < Number(doc.mail.timestamp) + 3600*1000
res {error:"验证链接无效或已经过期"}
return
strfor=doc.mail.for
switch doc.mail.for
when "confirm"
doc.mail=
address:doc.mail.new
verified:true
when "change"
doc.mail=
address:doc.mail.new
verified:true
when "remove"
delete doc.mail
when "reset"
doc.password = PI:PASSWORD:<PASSWORD>END_PI
doc.mail=
address:doc.mail.address
verified:true
M.users.update {"userid":doc.userid}, doc, {safe:true},(err,count)=>
if err?
res {error:"邮箱绑定失败"}
return
delete doc.password
req.session.user = doc
req.session.save ->
if strfor in ["confirm","change"]
doc.info="邮箱「#{doc.mail.address}」认证成功。"
else if strfor == "remove"
doc.mail=
address:""
verified:false
doc.info="邮箱解除认证成功。"
else if strfor == "reset"
doc.info="密码重置成功,请重新登陆。"
doc.reset=true
res doc
return
res null
resetPassword:(query)->
unless /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/.test query.mail
res {info:"请输入有效的邮箱地址"}
query.userid = query.userid.trim()
query.mail = query.mail.trim()
if query.newpass!=query.newpass2
res {error:"两次输入的密码不一致"}
return
M.users.findOne {"userid":query.userid,"mail.address":query.mail,"mail.verified":true},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"账号或邮箱不正确"}
return
else
mailer.sendResetMail(query,req,res,ss)
return
changePassword:(query)->
M.users.findOne {"userid":req.session.userId,"password":PI:PASSWORD:<PASSWORD>END_PI.user.crPI:PASSWORD:<PASSWORD>END_PI(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if query.newpass!=query.newpass2
res {error:"两次输入的密码不一致"}
return
M.users.update {"userid":req.session.userId}, {$set:{password:Server.user.crPI:PASSWORD:<PASSWORD>END_PI(query.newpass)}},{safe:true},(err,count)=>
if err?
res {error:"配置变更失败"}
return
res null
usePrize: (query)->
# 表示する称号を変える query.prize
M.users.findOne {"userid":req.session.userId,"password":Server.PI:PASSWORD:<PASSWORD>END_PI(query.password)},(err,record)=>
if err?
res {error:"DB err:#{err}"}
return
if !record?
res {error:"用户认证失败"}
return
if typeof query.prize?.every=="function"
# 称号構成を得る
comp=Shared.prize.getPrizesComposition record.prize.length
if query.prize.every((x,i)->x.type==comp[i])
# 合致する
if query.prize.every((x)->
if x.type=="prize"
!x.value || x.value in record.prize # 持っている称号のみ
else
!x.value || x.value in Shared.prize.conjunctions
)
# 所持もOK
M.users.update {"userid":req.session.userId}, {$set:{nowprize:query.prize}},{safe:true},(err)=>
req.session.user.nowprize=query.prize
req.session.save ->
res null
else
console.log "invalid1 ",query.prize,record.prize
res {error:"称号无效"}
else
console.log "invalid2",query.prize,comp
res {error:"称号无效"}
else
console.log "invalid3",query.prize
res {error:"称号无效"}
# 成績をくわしく見る
getMyuserlog:->
unless req.session.userId
res {error:"请登陆"}
return
myid=req.session.userId
# DBから自己のやつを引っ張ってくる
results=[]
M.userlogs.findOne {userid:myid},(err,doc)->
if err?
console.error err
unless doc?
# 戦績数据がない
res null
return
res doc
######
#密码ハッシュ化
# crpassword: (raw)-> raw && hashlib.sha256(raw+hashlib.md5(raw))
exports.crpassword= (raw)->
return "" unless raw
sha256=crypto.createHash "sha256"
md5=crypto.createHash "md5"
md5.update raw # md5でハッシュ化
sha256.update raw+md5.digest 'hex' # sha256でさらにハッシュ化
sha256.digest 'hex' # 结果を返す
#ユーザー数据作る
makeuserdata=(query)->
{
userid: query.userid
password: PI:PASSWORD:<PASSWORD>END_PI(query.PI:PASSWORD:<PASSWORD>END_PI)
name: query.userid
icon:"" # iconのURL
comment: ""
win:[] # 勝ち試合
lose:[] # 負け試合
gone:[] # 行方不明試合
ip:"" # IPアドレス
prize:[]# 现在持っている称号
ownprize:[] # 何かで与えられた称号(prizeに含まれる)
nowprize:null # 现在设定している肩書き
# [{type:"prize",value:(prizeid)},{type:"conjunction",value:"が"},...]
}
# profileに表示する用のユーザーデータをdocから作る
userProfile = (doc)->
doc.wp = unless doc.win? && doc.lose?
"???"
else if doc.win.length+doc.lose.length==0
"???"
else
"#{(doc.win.length/(doc.win.length+doc.lose.length)*100).toPrecision(2)}%"
# 称号の処理をしてあげる
doc.prize ?= []
doc.prizenames = doc.prize.map (x)->{id:x,name:Server.prize.prizeName(x),phonetic:Server.prize.prizePhonetic(x) ? "undefined"}
delete doc.prize
if !doc.mail?
doc.mail =
address:""
new:""
verified:false
else
doc.mail =
address:doc.mail.address
new:doc.mail.new
verified:doc.mail.verified
return doc
|
[
{
"context": "= Mailer.createTransport(\"SMTP\", {\r\n\t\t\t\t\t\t\thost: '10.1.224.110',\r\n\t\t\t\t\t\t\tport: 25,\r\n\t\t\t\t\t\t})\r\n\t\t\t\t\t\r\n\t\t\t\t\t\ttrans",
"end": 1203,
"score": 0.999772846698761,
"start": 1191,
"tag": "IP_ADDRESS",
"value": "10.1.224.110"
},
{
"context": "dMail({\r\n\t\t\t\t\t\t\tto: user.userName,\r\n\t\t\t\t\t\t\tfrom: 'admin@qref.com',\r\n\t\t\t\t\t\t\tsubject: 'QRef Mobile - Password Recove",
"end": 1325,
"score": 0.9999204277992249,
"start": 1311,
"tag": "EMAIL",
"value": "admin@qref.com"
}
] | Workspace/QRef/NodeServer/src/router/routes/rpc/auth/PasswordRecoveryRequestRoute.coffee | qrefdev/qref | 0 | RpcRoute = require('../../../RpcRoute')
RpcResponse = require('../../../../serialization/RpcResponse')
UserAuth = require('../../../../security/UserAuth')
Mailer = require('nodemailer')
fs = require('fs')
###
Service route that is used to create a new user account.
Password Recovery Request Email!
###
class PasswordRecoveryRequestRoute extends RpcRoute
constructor: () ->
super [{ method: 'POST', path: '/passwordRecoveryRequest' }]
post: (req, res) =>
if not @.isValidRequest(req)
resp = new RpcResponse(null)
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
UserAuth.createPasswordAuthCode(req.body.userName, (err, tk) =>
if err?
resp = new RpcResponse(null)
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
if tk?
resp = new RpcResponse(null)
res.json(resp, 200)
user = tk.user
@.getEmailTemplate('passwordRecoveryRequest.html', (data) ->
if data?
data = data.replace(/\{COPYDATE\}/gi, (new Date()).getFullYear());
data = data.replace(/\{recoveryCode\}/g, tk.code)
transport = Mailer.createTransport("SMTP", {
host: '10.1.224.110',
port: 25,
})
transport.sendMail({
to: user.userName,
from: 'admin@qref.com',
subject: 'QRef Mobile - Password Recovery',
html: data
}, (err, result) ->
if err?
console.log(JSON.stringify(err))
)
else
console.log("No email template found")
)
return
else
resp = new RpcResponse(null)
resp.failure('Failed to generate password recovery token', 500)
res.json(resp, 200)
return
)
getEmailTemplate: (file, callback) ->
fs.readFile('../WebContent/email/' + file, 'utf8', (err, data) ->
if err?
console.log(JSON.stringify(err))
callback(null);
return
if data?
callback(data);
return
else
callback(null);
return
)
isValidRequest: (req) ->
if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.userName?
true
else
false
module.exports = new PasswordRecoveryRequestRoute() | 89520 | RpcRoute = require('../../../RpcRoute')
RpcResponse = require('../../../../serialization/RpcResponse')
UserAuth = require('../../../../security/UserAuth')
Mailer = require('nodemailer')
fs = require('fs')
###
Service route that is used to create a new user account.
Password Recovery Request Email!
###
class PasswordRecoveryRequestRoute extends RpcRoute
constructor: () ->
super [{ method: 'POST', path: '/passwordRecoveryRequest' }]
post: (req, res) =>
if not @.isValidRequest(req)
resp = new RpcResponse(null)
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
UserAuth.createPasswordAuthCode(req.body.userName, (err, tk) =>
if err?
resp = new RpcResponse(null)
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
if tk?
resp = new RpcResponse(null)
res.json(resp, 200)
user = tk.user
@.getEmailTemplate('passwordRecoveryRequest.html', (data) ->
if data?
data = data.replace(/\{COPYDATE\}/gi, (new Date()).getFullYear());
data = data.replace(/\{recoveryCode\}/g, tk.code)
transport = Mailer.createTransport("SMTP", {
host: '10.1.224.110',
port: 25,
})
transport.sendMail({
to: user.userName,
from: '<EMAIL>',
subject: 'QRef Mobile - Password Recovery',
html: data
}, (err, result) ->
if err?
console.log(JSON.stringify(err))
)
else
console.log("No email template found")
)
return
else
resp = new RpcResponse(null)
resp.failure('Failed to generate password recovery token', 500)
res.json(resp, 200)
return
)
getEmailTemplate: (file, callback) ->
fs.readFile('../WebContent/email/' + file, 'utf8', (err, data) ->
if err?
console.log(JSON.stringify(err))
callback(null);
return
if data?
callback(data);
return
else
callback(null);
return
)
isValidRequest: (req) ->
if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.userName?
true
else
false
module.exports = new PasswordRecoveryRequestRoute() | true | RpcRoute = require('../../../RpcRoute')
RpcResponse = require('../../../../serialization/RpcResponse')
UserAuth = require('../../../../security/UserAuth')
Mailer = require('nodemailer')
fs = require('fs')
###
Service route that is used to create a new user account.
Password Recovery Request Email!
###
class PasswordRecoveryRequestRoute extends RpcRoute
constructor: () ->
super [{ method: 'POST', path: '/passwordRecoveryRequest' }]
post: (req, res) =>
if not @.isValidRequest(req)
resp = new RpcResponse(null)
resp.failure('Bad Request', 400)
res.json(resp, 200)
return
UserAuth.createPasswordAuthCode(req.body.userName, (err, tk) =>
if err?
resp = new RpcResponse(null)
resp.failure('Internal Error', 500)
res.json(resp, 200)
return
if tk?
resp = new RpcResponse(null)
res.json(resp, 200)
user = tk.user
@.getEmailTemplate('passwordRecoveryRequest.html', (data) ->
if data?
data = data.replace(/\{COPYDATE\}/gi, (new Date()).getFullYear());
data = data.replace(/\{recoveryCode\}/g, tk.code)
transport = Mailer.createTransport("SMTP", {
host: '10.1.224.110',
port: 25,
})
transport.sendMail({
to: user.userName,
from: 'PI:EMAIL:<EMAIL>END_PI',
subject: 'QRef Mobile - Password Recovery',
html: data
}, (err, result) ->
if err?
console.log(JSON.stringify(err))
)
else
console.log("No email template found")
)
return
else
resp = new RpcResponse(null)
resp.failure('Failed to generate password recovery token', 500)
res.json(resp, 200)
return
)
getEmailTemplate: (file, callback) ->
fs.readFile('../WebContent/email/' + file, 'utf8', (err, data) ->
if err?
console.log(JSON.stringify(err))
callback(null);
return
if data?
callback(data);
return
else
callback(null);
return
)
isValidRequest: (req) ->
if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.userName?
true
else
false
module.exports = new PasswordRecoveryRequestRoute() |
[
{
"context": " { type: 'object' } }\n }\n }\n data = { name: 'Bob', numbers: [\n {'number':'401-401-1337', 'type'",
"end": 206,
"score": 0.9996512532234192,
"start": 203,
"tag": "NAME",
"value": "Bob"
}
] | test/getters-setters/insert.coffee | lgr7/codecombattreema | 66 | describe 'TreemaNode.insert', ->
schema = {
type: 'object',
properties: {
name: { type: 'string' }
numbers: { type: 'array', items: { type: 'object' } }
}
}
data = { name: 'Bob', numbers: [
{'number':'401-401-1337', 'type':'Home'},
{'number':'123-456-7890', 'type':'Work'}
]}
treema = TreemaNode.make(null, {data: data, schema: schema})
treema.build()
it 'appends data to the end of an array', ->
expect(treema.insert('/numbers', {'number':'4321'})).toBeTruthy()
numbers = treema.get('/numbers')
expect(numbers.length).toBe(3)
expect(numbers[2].number).toBe('4321')
it 'returns false for paths that are not arrays', ->
expect(treema.insert('/numbers/0', 'boom')).toBeFalsy()
it 'returns false for paths that do not exist', ->
expect(treema.insert('/numbahs', 'boom')).toBeFalsy() | 162354 | describe 'TreemaNode.insert', ->
schema = {
type: 'object',
properties: {
name: { type: 'string' }
numbers: { type: 'array', items: { type: 'object' } }
}
}
data = { name: '<NAME>', numbers: [
{'number':'401-401-1337', 'type':'Home'},
{'number':'123-456-7890', 'type':'Work'}
]}
treema = TreemaNode.make(null, {data: data, schema: schema})
treema.build()
it 'appends data to the end of an array', ->
expect(treema.insert('/numbers', {'number':'4321'})).toBeTruthy()
numbers = treema.get('/numbers')
expect(numbers.length).toBe(3)
expect(numbers[2].number).toBe('4321')
it 'returns false for paths that are not arrays', ->
expect(treema.insert('/numbers/0', 'boom')).toBeFalsy()
it 'returns false for paths that do not exist', ->
expect(treema.insert('/numbahs', 'boom')).toBeFalsy() | true | describe 'TreemaNode.insert', ->
schema = {
type: 'object',
properties: {
name: { type: 'string' }
numbers: { type: 'array', items: { type: 'object' } }
}
}
data = { name: 'PI:NAME:<NAME>END_PI', numbers: [
{'number':'401-401-1337', 'type':'Home'},
{'number':'123-456-7890', 'type':'Work'}
]}
treema = TreemaNode.make(null, {data: data, schema: schema})
treema.build()
it 'appends data to the end of an array', ->
expect(treema.insert('/numbers', {'number':'4321'})).toBeTruthy()
numbers = treema.get('/numbers')
expect(numbers.length).toBe(3)
expect(numbers[2].number).toBe('4321')
it 'returns false for paths that are not arrays', ->
expect(treema.insert('/numbers/0', 'boom')).toBeFalsy()
it 'returns false for paths that do not exist', ->
expect(treema.insert('/numbahs', 'boom')).toBeFalsy() |
[
{
"context": "icode BOM can be required and disallowed\n# @author Andrew Johnston <https:#github.com/ehjay>\n###\n'use strict'\n\n#----",
"end": 104,
"score": 0.9998447299003601,
"start": 89,
"tag": "NAME",
"value": "Andrew Johnston"
},
{
"context": "owed\n# @author Andrew Johnston <https:#github.com/ehjay>\n###\n'use strict'\n\n#-----------------------------",
"end": 129,
"score": 0.9971144795417786,
"start": 124,
"tag": "USERNAME",
"value": "ehjay"
}
] | src/tests/rules/unicode-bom.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Check that the Unicode BOM can be required and disallowed
# @author Andrew Johnston <https:#github.com/ehjay>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/unicode-bom'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'unicode-bom', rule,
valid: [
code: '\uFEFF a = 123'
options: ['always']
,
code: 'a = 123'
options: ['never']
,
code: 'a = 123 \uFEFF'
options: ['never']
]
invalid: [
code: 'a = 123'
output: '\uFEFFa = 123'
options: ['always']
errors: [
message: 'Expected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: " # here's a comment \na = 123"
output: "\uFEFF # here's a comment \na = 123"
options: ['always']
errors: [
message: 'Expected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: '\uFEFF a = 123'
output: ' a = 123'
errors: [
message: 'Unexpected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: '\uFEFF a = 123'
output: ' a = 123'
options: ['never']
errors: [
message: 'Unexpected Unicode BOM (Byte Order Mark).', type: 'Program'
]
]
| 81325 | ###*
# @fileoverview Check that the Unicode BOM can be required and disallowed
# @author <NAME> <https:#github.com/ehjay>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/unicode-bom'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'unicode-bom', rule,
valid: [
code: '\uFEFF a = 123'
options: ['always']
,
code: 'a = 123'
options: ['never']
,
code: 'a = 123 \uFEFF'
options: ['never']
]
invalid: [
code: 'a = 123'
output: '\uFEFFa = 123'
options: ['always']
errors: [
message: 'Expected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: " # here's a comment \na = 123"
output: "\uFEFF # here's a comment \na = 123"
options: ['always']
errors: [
message: 'Expected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: '\uFEFF a = 123'
output: ' a = 123'
errors: [
message: 'Unexpected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: '\uFEFF a = 123'
output: ' a = 123'
options: ['never']
errors: [
message: 'Unexpected Unicode BOM (Byte Order Mark).', type: 'Program'
]
]
| true | ###*
# @fileoverview Check that the Unicode BOM can be required and disallowed
# @author PI:NAME:<NAME>END_PI <https:#github.com/ehjay>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require 'eslint/lib/rules/unicode-bom'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'unicode-bom', rule,
valid: [
code: '\uFEFF a = 123'
options: ['always']
,
code: 'a = 123'
options: ['never']
,
code: 'a = 123 \uFEFF'
options: ['never']
]
invalid: [
code: 'a = 123'
output: '\uFEFFa = 123'
options: ['always']
errors: [
message: 'Expected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: " # here's a comment \na = 123"
output: "\uFEFF # here's a comment \na = 123"
options: ['always']
errors: [
message: 'Expected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: '\uFEFF a = 123'
output: ' a = 123'
errors: [
message: 'Unexpected Unicode BOM (Byte Order Mark).', type: 'Program'
]
,
code: '\uFEFF a = 123'
output: ' a = 123'
options: ['never']
errors: [
message: 'Unexpected Unicode BOM (Byte Order Mark).', type: 'Program'
]
]
|
[
{
"context": "###\n* Copyright 2014 Laura Taylor\n* (https://github.com/techstreams/TSTranslateKhme",
"end": 33,
"score": 0.9998748302459717,
"start": 21,
"tag": "NAME",
"value": "Laura Taylor"
},
{
"context": "Copyright 2014 Laura Taylor\n* (https://github.com/techstreams/TSTranslateKhmer)\n*\n* Licensed under the Apache L",
"end": 67,
"score": 0.9673293232917786,
"start": 56,
"tag": "USERNAME",
"value": "techstreams"
}
] | src/tstranslatekhmer.coffee | techstreams/TSTranslateKhmer | 0 | ###
* Copyright 2014 Laura Taylor
* (https://github.com/techstreams/TSTranslateKhmer)
*
* 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.
###
###
* Adds a custom menu to the active document
###
`function onOpen() {
FormApp.getUi()
.createMenu('TSTranslateKhmer')
.addItem('Create Form', 'createForm')
.addItem('Enable Submit Trigger', 'enableSubmitTrigger')
.addSubMenu(FormApp.getUi().createMenu('Utilities')
.addItem('Translate Form Text to Khmer', 'translateToKhmer')
.addItem('Translate Form Text to English', 'translateToEnglish'))
.addSeparator()
.addItem('About', 'about')
.addToUi();
}`
###
* Setup form submit trigger
###
`function enableSubmitTrigger() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).setFormTrigger('checkResponses');
FormApp.getUi().alert('Form Submit Trigger has been enabled.');
}`
###
* Create the form
###
`function createForm() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).createForm();
FormApp.getUi().alert('Form has been created.');
}`
###
* Convert form text to Khmer
###
`function translateToKhmer() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).translateText('en', 'km');
FormApp.getUi().alert('Form text has been translated to Khmer.');
}`
###
* Convert form text to English
###
`function translateToEnglish() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).translateText('km', 'en');
FormApp.getUi().alert('Form text has been translated to English.');
}`
###
* Show About Information
###
`function about() {
FormApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('about').setSandboxMode(HtmlService.SandboxMode.IFRAME), ' ');
}`
###
* Process form response
* @param {object} form submit trigger event
###
`function checkResponses(e) {
var tstk;
try {
tstk = new TSTranslateKhmer(FormApp.getActiveForm(), e.response).sendEmail();
} catch(error) {
// Send errors to owner
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'TSTranslateKhmer: Error processing form submission', error.message);
}
}`
###
* Define TSTranslateKhmer Class
###
do ->
###
* TSTranslateKhmer
* @class
###
class @TSTranslateKhmer
###
* @constructor
* @param {object} form object
* @param {object} form response object
* @param {string} email template name
* @param {string} email subject line
* @return {TSTranslateKhmer} this object for chaining
###
constructor: (@form, @formResponse = null, @email = 'email', @subjectline = 'Form Submission') ->
@lang =
to: 'en'
from: 'km'
@meta = null
@
# PUBLIC FUNCTIONS
###
* Create Form
* @return {TSTranslateKhmer} this object for chaining
###
createForm: ->
@clearForm_()
@form.setTitle('Khmer to English Translator').setDescription('Complete the following form. Click the button to submit.').setConfirmationMessage('Your response has been submitted.')
@form.addParagraphTextItem()
.setTitle('Message')
.setHelpText('Enter your message in the Khmer language.')
.setRequired(true)
@
###
* Generate form meta and send email
* @return {TSTranslateKhmer} this object for chaining
###
sendEmail: ->
# Generate an object with form submission data
@generateFormResponseMeta_()
# Send email
if @meta
@sendEmail_()
@
###
* Set a form trigger for processing form responses
* @param {string} function name to be run on trigger
* @return {TSTranslateKhmer} this object for chaining
###
setFormTrigger: (functionName) ->
# Set form submit trigger - call when generating form
triggers = ScriptApp.getProjectTriggers()
triggers.forEach (trigger) ->
ScriptApp.deleteTrigger(trigger)
ScriptApp.newTrigger(functionName)
.forForm(@form)
.onFormSubmit()
.create()
@
###
* Translate form text
* @return {TSTranslateKhmer} this object for chaining
###
translateText: (from, to) ->
@form.setTitle(LanguageApp.translate(@form.getTitle(), from, to))
if @form.getDescription() and @form.getDescription() isnt ''
@form.setDescription(LanguageApp.translate(@form.getDescription(), from, to))
if @form.getConfirmationMessage() and @form.getConfirmationMessage() isnt ''
@form.setConfirmationMessage(LanguageApp.translate(@form.getConfirmationMessage(), from, to))
children = @form.getItems()
children.forEach (item) ->
if item.getTitle() and item.getTitle() isnt ''
item.setTitle(LanguageApp.translate(item.getTitle(), from, to))
if item.getHelpText() and item.getHelpText() isnt ''
item.setHelpText(LanguageApp.translate(item.getHelpText(), from, to))
null
@
# PRIVATE FUNCTIONS
###
* Remove form items
* @return {TSTranslateKhmer} this object for chaining
* @private
###
clearForm_: ->
children = @form.getItems()
children.forEach (item) =>
@form.deleteItem(item)
@
###
* Generate form response meta
* @return {TSTranslateKhmer} this object for chaining
* @private
###
generateFormResponseMeta_: ->
if @formResponse
meta = new Object()
meta.url = @form.getPublishedUrl()
meta.title = @form.getTitle()
if @form.collectsEmail()
meta.submitter = @formResponse.getRespondentEmail()
msgItems = @getFormResponseItemsByType_(@formResponse, FormApp.ItemType.PARAGRAPH_TEXT)
if msgItems.length > 0
meta.msg = msgItems[0].response
meta.msgtranslated = LanguageApp.translate(msgItems[0].response, @lang.from, @lang.to)
@meta = meta
else
throw new Error('Message form item missing in form submission!')
@
###
* Get response items by type
* @param {object} form response object
* @param {object} form response item type
* @return {array} array of form objects by type
* @private
###
getFormResponseItemsByType_: (response, type) ->
items = []
response.getItemResponses().forEach (ir) ->
item = ir.getItem()
if item.getType() is type
itemObj = new Object()
switch item.getType()
when FormApp.ItemType.CHECKBOX
submitType = true
itemObj.type = 'checkbox'
when FormApp.ItemType.DATE
submitType = true
itemObj.type = 'date'
when FormApp.ItemType.DATETIME
submitType = true
itemObj.type = 'datetime'
when FormApp.ItemType.DURATION
submitType = true
itemObj.type = 'duration'
when FormApp.ItemType.GRID
submitType = true
itemObj.type = 'grid'
when FormApp.ItemType.LIST
submitType = true
itemObj.type = 'list'
when FormApp.ItemType.MULTIPLE_CHOICE
submitType = true
itemObj.type = 'multiplechoice'
when FormApp.ItemType.PARAGRAPH_TEXT
submitType = true
itemObj.type = 'paragraph'
when FormApp.ItemType.SCALE
submitType = true
itemObj.type = 'scale'
when FormApp.ItemType.TEXT
submitType = true
itemObj.type = 'text'
when FormApp.ItemType.TIME
submitType = true
itemObj.type = 'time'
else
submitType = false
if submitType
itemObj.helptext = item.getHelpText()
itemObj.index = item.getIndex()
itemObj.id = item.getId()
itemObj.response = ir.getResponse()
itemObj.title = item.getTitle()
items.push itemObj
null
items
###
* Send email
* @return {TSTranslateKhmer} this object for chaining
* @private
###
sendEmail_: () ->
email = HtmlService.createTemplateFromFile(@email)
email.meta = @meta
params =
htmlBody: email.evaluate().getContent()
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), @subjectline, "", params)
@
| 13932 | ###
* Copyright 2014 <NAME>
* (https://github.com/techstreams/TSTranslateKhmer)
*
* 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.
###
###
* Adds a custom menu to the active document
###
`function onOpen() {
FormApp.getUi()
.createMenu('TSTranslateKhmer')
.addItem('Create Form', 'createForm')
.addItem('Enable Submit Trigger', 'enableSubmitTrigger')
.addSubMenu(FormApp.getUi().createMenu('Utilities')
.addItem('Translate Form Text to Khmer', 'translateToKhmer')
.addItem('Translate Form Text to English', 'translateToEnglish'))
.addSeparator()
.addItem('About', 'about')
.addToUi();
}`
###
* Setup form submit trigger
###
`function enableSubmitTrigger() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).setFormTrigger('checkResponses');
FormApp.getUi().alert('Form Submit Trigger has been enabled.');
}`
###
* Create the form
###
`function createForm() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).createForm();
FormApp.getUi().alert('Form has been created.');
}`
###
* Convert form text to Khmer
###
`function translateToKhmer() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).translateText('en', 'km');
FormApp.getUi().alert('Form text has been translated to Khmer.');
}`
###
* Convert form text to English
###
`function translateToEnglish() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).translateText('km', 'en');
FormApp.getUi().alert('Form text has been translated to English.');
}`
###
* Show About Information
###
`function about() {
FormApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('about').setSandboxMode(HtmlService.SandboxMode.IFRAME), ' ');
}`
###
* Process form response
* @param {object} form submit trigger event
###
`function checkResponses(e) {
var tstk;
try {
tstk = new TSTranslateKhmer(FormApp.getActiveForm(), e.response).sendEmail();
} catch(error) {
// Send errors to owner
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'TSTranslateKhmer: Error processing form submission', error.message);
}
}`
###
* Define TSTranslateKhmer Class
###
do ->
###
* TSTranslateKhmer
* @class
###
class @TSTranslateKhmer
###
* @constructor
* @param {object} form object
* @param {object} form response object
* @param {string} email template name
* @param {string} email subject line
* @return {TSTranslateKhmer} this object for chaining
###
constructor: (@form, @formResponse = null, @email = 'email', @subjectline = 'Form Submission') ->
@lang =
to: 'en'
from: 'km'
@meta = null
@
# PUBLIC FUNCTIONS
###
* Create Form
* @return {TSTranslateKhmer} this object for chaining
###
createForm: ->
@clearForm_()
@form.setTitle('Khmer to English Translator').setDescription('Complete the following form. Click the button to submit.').setConfirmationMessage('Your response has been submitted.')
@form.addParagraphTextItem()
.setTitle('Message')
.setHelpText('Enter your message in the Khmer language.')
.setRequired(true)
@
###
* Generate form meta and send email
* @return {TSTranslateKhmer} this object for chaining
###
sendEmail: ->
# Generate an object with form submission data
@generateFormResponseMeta_()
# Send email
if @meta
@sendEmail_()
@
###
* Set a form trigger for processing form responses
* @param {string} function name to be run on trigger
* @return {TSTranslateKhmer} this object for chaining
###
setFormTrigger: (functionName) ->
# Set form submit trigger - call when generating form
triggers = ScriptApp.getProjectTriggers()
triggers.forEach (trigger) ->
ScriptApp.deleteTrigger(trigger)
ScriptApp.newTrigger(functionName)
.forForm(@form)
.onFormSubmit()
.create()
@
###
* Translate form text
* @return {TSTranslateKhmer} this object for chaining
###
translateText: (from, to) ->
@form.setTitle(LanguageApp.translate(@form.getTitle(), from, to))
if @form.getDescription() and @form.getDescription() isnt ''
@form.setDescription(LanguageApp.translate(@form.getDescription(), from, to))
if @form.getConfirmationMessage() and @form.getConfirmationMessage() isnt ''
@form.setConfirmationMessage(LanguageApp.translate(@form.getConfirmationMessage(), from, to))
children = @form.getItems()
children.forEach (item) ->
if item.getTitle() and item.getTitle() isnt ''
item.setTitle(LanguageApp.translate(item.getTitle(), from, to))
if item.getHelpText() and item.getHelpText() isnt ''
item.setHelpText(LanguageApp.translate(item.getHelpText(), from, to))
null
@
# PRIVATE FUNCTIONS
###
* Remove form items
* @return {TSTranslateKhmer} this object for chaining
* @private
###
clearForm_: ->
children = @form.getItems()
children.forEach (item) =>
@form.deleteItem(item)
@
###
* Generate form response meta
* @return {TSTranslateKhmer} this object for chaining
* @private
###
generateFormResponseMeta_: ->
if @formResponse
meta = new Object()
meta.url = @form.getPublishedUrl()
meta.title = @form.getTitle()
if @form.collectsEmail()
meta.submitter = @formResponse.getRespondentEmail()
msgItems = @getFormResponseItemsByType_(@formResponse, FormApp.ItemType.PARAGRAPH_TEXT)
if msgItems.length > 0
meta.msg = msgItems[0].response
meta.msgtranslated = LanguageApp.translate(msgItems[0].response, @lang.from, @lang.to)
@meta = meta
else
throw new Error('Message form item missing in form submission!')
@
###
* Get response items by type
* @param {object} form response object
* @param {object} form response item type
* @return {array} array of form objects by type
* @private
###
getFormResponseItemsByType_: (response, type) ->
items = []
response.getItemResponses().forEach (ir) ->
item = ir.getItem()
if item.getType() is type
itemObj = new Object()
switch item.getType()
when FormApp.ItemType.CHECKBOX
submitType = true
itemObj.type = 'checkbox'
when FormApp.ItemType.DATE
submitType = true
itemObj.type = 'date'
when FormApp.ItemType.DATETIME
submitType = true
itemObj.type = 'datetime'
when FormApp.ItemType.DURATION
submitType = true
itemObj.type = 'duration'
when FormApp.ItemType.GRID
submitType = true
itemObj.type = 'grid'
when FormApp.ItemType.LIST
submitType = true
itemObj.type = 'list'
when FormApp.ItemType.MULTIPLE_CHOICE
submitType = true
itemObj.type = 'multiplechoice'
when FormApp.ItemType.PARAGRAPH_TEXT
submitType = true
itemObj.type = 'paragraph'
when FormApp.ItemType.SCALE
submitType = true
itemObj.type = 'scale'
when FormApp.ItemType.TEXT
submitType = true
itemObj.type = 'text'
when FormApp.ItemType.TIME
submitType = true
itemObj.type = 'time'
else
submitType = false
if submitType
itemObj.helptext = item.getHelpText()
itemObj.index = item.getIndex()
itemObj.id = item.getId()
itemObj.response = ir.getResponse()
itemObj.title = item.getTitle()
items.push itemObj
null
items
###
* Send email
* @return {TSTranslateKhmer} this object for chaining
* @private
###
sendEmail_: () ->
email = HtmlService.createTemplateFromFile(@email)
email.meta = @meta
params =
htmlBody: email.evaluate().getContent()
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), @subjectline, "", params)
@
| true | ###
* Copyright 2014 PI:NAME:<NAME>END_PI
* (https://github.com/techstreams/TSTranslateKhmer)
*
* 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.
###
###
* Adds a custom menu to the active document
###
`function onOpen() {
FormApp.getUi()
.createMenu('TSTranslateKhmer')
.addItem('Create Form', 'createForm')
.addItem('Enable Submit Trigger', 'enableSubmitTrigger')
.addSubMenu(FormApp.getUi().createMenu('Utilities')
.addItem('Translate Form Text to Khmer', 'translateToKhmer')
.addItem('Translate Form Text to English', 'translateToEnglish'))
.addSeparator()
.addItem('About', 'about')
.addToUi();
}`
###
* Setup form submit trigger
###
`function enableSubmitTrigger() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).setFormTrigger('checkResponses');
FormApp.getUi().alert('Form Submit Trigger has been enabled.');
}`
###
* Create the form
###
`function createForm() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).createForm();
FormApp.getUi().alert('Form has been created.');
}`
###
* Convert form text to Khmer
###
`function translateToKhmer() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).translateText('en', 'km');
FormApp.getUi().alert('Form text has been translated to Khmer.');
}`
###
* Convert form text to English
###
`function translateToEnglish() {
var tstk;
tstk = new TSTranslateKhmer(FormApp.getActiveForm()).translateText('km', 'en');
FormApp.getUi().alert('Form text has been translated to English.');
}`
###
* Show About Information
###
`function about() {
FormApp.getUi().showModelessDialog(HtmlService.createHtmlOutputFromFile('about').setSandboxMode(HtmlService.SandboxMode.IFRAME), ' ');
}`
###
* Process form response
* @param {object} form submit trigger event
###
`function checkResponses(e) {
var tstk;
try {
tstk = new TSTranslateKhmer(FormApp.getActiveForm(), e.response).sendEmail();
} catch(error) {
// Send errors to owner
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), 'TSTranslateKhmer: Error processing form submission', error.message);
}
}`
###
* Define TSTranslateKhmer Class
###
do ->
###
* TSTranslateKhmer
* @class
###
class @TSTranslateKhmer
###
* @constructor
* @param {object} form object
* @param {object} form response object
* @param {string} email template name
* @param {string} email subject line
* @return {TSTranslateKhmer} this object for chaining
###
constructor: (@form, @formResponse = null, @email = 'email', @subjectline = 'Form Submission') ->
@lang =
to: 'en'
from: 'km'
@meta = null
@
# PUBLIC FUNCTIONS
###
* Create Form
* @return {TSTranslateKhmer} this object for chaining
###
createForm: ->
@clearForm_()
@form.setTitle('Khmer to English Translator').setDescription('Complete the following form. Click the button to submit.').setConfirmationMessage('Your response has been submitted.')
@form.addParagraphTextItem()
.setTitle('Message')
.setHelpText('Enter your message in the Khmer language.')
.setRequired(true)
@
###
* Generate form meta and send email
* @return {TSTranslateKhmer} this object for chaining
###
sendEmail: ->
# Generate an object with form submission data
@generateFormResponseMeta_()
# Send email
if @meta
@sendEmail_()
@
###
* Set a form trigger for processing form responses
* @param {string} function name to be run on trigger
* @return {TSTranslateKhmer} this object for chaining
###
setFormTrigger: (functionName) ->
# Set form submit trigger - call when generating form
triggers = ScriptApp.getProjectTriggers()
triggers.forEach (trigger) ->
ScriptApp.deleteTrigger(trigger)
ScriptApp.newTrigger(functionName)
.forForm(@form)
.onFormSubmit()
.create()
@
###
* Translate form text
* @return {TSTranslateKhmer} this object for chaining
###
translateText: (from, to) ->
@form.setTitle(LanguageApp.translate(@form.getTitle(), from, to))
if @form.getDescription() and @form.getDescription() isnt ''
@form.setDescription(LanguageApp.translate(@form.getDescription(), from, to))
if @form.getConfirmationMessage() and @form.getConfirmationMessage() isnt ''
@form.setConfirmationMessage(LanguageApp.translate(@form.getConfirmationMessage(), from, to))
children = @form.getItems()
children.forEach (item) ->
if item.getTitle() and item.getTitle() isnt ''
item.setTitle(LanguageApp.translate(item.getTitle(), from, to))
if item.getHelpText() and item.getHelpText() isnt ''
item.setHelpText(LanguageApp.translate(item.getHelpText(), from, to))
null
@
# PRIVATE FUNCTIONS
###
* Remove form items
* @return {TSTranslateKhmer} this object for chaining
* @private
###
clearForm_: ->
children = @form.getItems()
children.forEach (item) =>
@form.deleteItem(item)
@
###
* Generate form response meta
* @return {TSTranslateKhmer} this object for chaining
* @private
###
generateFormResponseMeta_: ->
if @formResponse
meta = new Object()
meta.url = @form.getPublishedUrl()
meta.title = @form.getTitle()
if @form.collectsEmail()
meta.submitter = @formResponse.getRespondentEmail()
msgItems = @getFormResponseItemsByType_(@formResponse, FormApp.ItemType.PARAGRAPH_TEXT)
if msgItems.length > 0
meta.msg = msgItems[0].response
meta.msgtranslated = LanguageApp.translate(msgItems[0].response, @lang.from, @lang.to)
@meta = meta
else
throw new Error('Message form item missing in form submission!')
@
###
* Get response items by type
* @param {object} form response object
* @param {object} form response item type
* @return {array} array of form objects by type
* @private
###
getFormResponseItemsByType_: (response, type) ->
items = []
response.getItemResponses().forEach (ir) ->
item = ir.getItem()
if item.getType() is type
itemObj = new Object()
switch item.getType()
when FormApp.ItemType.CHECKBOX
submitType = true
itemObj.type = 'checkbox'
when FormApp.ItemType.DATE
submitType = true
itemObj.type = 'date'
when FormApp.ItemType.DATETIME
submitType = true
itemObj.type = 'datetime'
when FormApp.ItemType.DURATION
submitType = true
itemObj.type = 'duration'
when FormApp.ItemType.GRID
submitType = true
itemObj.type = 'grid'
when FormApp.ItemType.LIST
submitType = true
itemObj.type = 'list'
when FormApp.ItemType.MULTIPLE_CHOICE
submitType = true
itemObj.type = 'multiplechoice'
when FormApp.ItemType.PARAGRAPH_TEXT
submitType = true
itemObj.type = 'paragraph'
when FormApp.ItemType.SCALE
submitType = true
itemObj.type = 'scale'
when FormApp.ItemType.TEXT
submitType = true
itemObj.type = 'text'
when FormApp.ItemType.TIME
submitType = true
itemObj.type = 'time'
else
submitType = false
if submitType
itemObj.helptext = item.getHelpText()
itemObj.index = item.getIndex()
itemObj.id = item.getId()
itemObj.response = ir.getResponse()
itemObj.title = item.getTitle()
items.push itemObj
null
items
###
* Send email
* @return {TSTranslateKhmer} this object for chaining
* @private
###
sendEmail_: () ->
email = HtmlService.createTemplateFromFile(@email)
email.meta = @meta
params =
htmlBody: email.evaluate().getContent()
MailApp.sendEmail(Session.getEffectiveUser().getEmail(), @subjectline, "", params)
@
|
[
{
"context": "catchAll\n\t\t@user = Meteor.users.findOne {username: @name}, fields: username: 1\n\tloadAdapter: -> false\n\thea",
"end": 904,
"score": 0.9679121971130371,
"start": 899,
"tag": "USERNAME",
"value": "@name"
},
{
"context": "Meteor.call \"sendMessage\",\n\t\t\t\tu:\n\t\t\t\t\tusername: \"rocketbot\"\n\t\t\t\tto: \"#{envelope.user.id}\"\n\t\t\t\tmsg: string\n\t\t",
"end": 2923,
"score": 0.9992251992225647,
"start": 2914,
"tag": "USERNAME",
"value": "rocketbot"
},
{
"context": "er our nick\n\t# n = Meteor.call 'newNick', {name: 'rocketbot'}\n\t# Meteor.call 'setTag', {type:'nicks', object:",
"end": 9763,
"score": 0.9996277093887329,
"start": 9754,
"tag": "USERNAME",
"value": "rocketbot"
},
{
"context": "ll 'setTag', {type:'nicks', object:n._id, name:'Gravatar', value:'rocket@printf.net', who:n.canon}\n\t# # re",
"end": 9834,
"score": 0.8184471130371094,
"start": 9828,
"tag": "NAME",
"value": "avatar"
},
{
"context": "pe:'nicks', object:n._id, name:'Gravatar', value:'rocket@printf.net', who:n.canon}\n\t# # register our presence in gene",
"end": 9861,
"score": 0.9999217987060547,
"start": 9844,
"tag": "EMAIL",
"value": "rocket@printf.net"
},
{
"context": "Meteor.call 'setPresence',\n\t# \tu:\n\t# \t\tusername: 'rocketbot'\n\t# \trid: 'GENERAL'\n\t# \tpresent: true\n\t# \tforegro",
"end": 9997,
"score": 0.9996671676635742,
"start": 9988,
"tag": "USERNAME",
"value": "rocketbot"
},
{
"context": " if startup\n\t# \t\treturn if message.u.username is \"rocketbot\" or message.u.username is \"\"\n\t# \t\treturn if messa",
"end": 10357,
"score": 0.99962317943573,
"start": 10348,
"tag": "USERNAME",
"value": "rocketbot"
},
{
"context": "NERAL'\n\t# \tmsg: 'wakes up'\n\t# \tu:\n\t# \t\tusername: \"rocketbot\"\n\t# \taction: true\n",
"end": 11037,
"score": 0.9993524551391602,
"start": 11028,
"tag": "USERNAME",
"value": "rocketbot"
}
] | packages/rocketchat-hubot/hubot.coffee | hunterlive/seww | 0 | CoffeeScript = Npm.require('coffee-script')
CoffeeScript.register()
Hubot = Npm.require('hubot')
fs = Npm.require('fs')
path = Npm.require('path')
# Start a hubot, connected to our chat room.
# 'use strict'
# Log messages?
DEBUG = true
# Monkey-patch Hubot to support private messages
Hubot.Response::priv = (strings...) ->
@robot.adapter.priv @envelope, strings...
# More monkey-patching
Hubot.Robot::loadAdapter = -> # disable
# grrrr, Meteor.bindEnvironment doesn't preserve `this` apparently
bind = (f) ->
g = Meteor.bindEnvironment (self, args...) -> f.apply(self, args)
(args...) -> g @, args...
class Robot extends Hubot.Robot
constructor: (args...) ->
super args...
@hear = bind @hear
@respond = bind @respond
@enter = bind @enter
@leave = bind @leave
@topic = bind @topic
@error = bind @error
@catchAll = bind @catchAll
@user = Meteor.users.findOne {username: @name}, fields: username: 1
loadAdapter: -> false
hear: (regex, callback) -> super regex, Meteor.bindEnvironment callback
respond: (regex, callback) -> super regex, Meteor.bindEnvironment callback
enter: (callback) -> super Meteor.bindEnvironment(callback)
leave: (callback) -> super Meteor.bindEnvironment(callback)
topic: (callback) -> super Meteor.bindEnvironment(callback)
error: (callback) -> super Meteor.bindEnvironment(callback)
catchAll: (callback) -> super Meteor.bindEnvironment(callback)
class RocketChatAdapter extends Hubot.Adapter
# Public: Raw method for sending data back to the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
send: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> send'.blue
# console.log envelope, strings
sendHelper @robot, envelope, strings, (string) =>
console.log "send #{envelope.room}: #{string} (#{envelope.user.id})" if DEBUG
RocketChat.sendMessage RocketBot.user, { msg: string }, { _id: envelope.room }
# Public: Raw method for sending emote data back to the chat source.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
emote: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> emote'.blue
sendHelper @robot, envelope, strings, (string) =>
console.log "emote #{envelope.rid}: #{string} (#{envelope.u.username})" if DEBUG
return @priv envelope, "*** #{string} ***" if envelope.message.private
Meteor.call "sendMessage",
msg: string
rid: envelope.rid
action: true
# Priv: our extension -- send a PM to user
priv: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> priv'.blue
sendHelper @robot, envelope, strings, (string) ->
console.log "priv #{envelope.room}: #{string} (#{envelope.user.id})" if DEBUG
Meteor.call "sendMessage",
u:
username: "rocketbot"
to: "#{envelope.user.id}"
msg: string
rid: envelope.room
# Public: Raw method for building a reply and sending it back to the chat
# source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each reply to send.
#
# Returns nothing.
reply: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> reply'.blue
if envelope.message.private
@priv envelope, strings...
else
@send envelope, strings.map((str) -> "#{envelope.user.name}: #{str}")...
# Public: Raw method for setting a topic on the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One more more Strings to set as the topic.
#
# Returns nothing.
topic: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> topic'.blue
# Public: Raw method for playing a sound in the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more strings for each play message to send.
#
# Returns nothing
play: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> play'.blue
# Public: Raw method for invoking the bot to run. Extend this.
#
# Returns nothing.
run: ->
console.log 'ROCKETCHATADAPTER -> run'.blue
@robot.emit 'connected'
@robot.brain.mergeData {}
# @robot.brain.emit 'loaded'
# Public: Raw method for shutting the bot down. Extend this.
#
# Returns nothing.
close: ->
console.log 'ROCKETCHATADAPTER -> close'.blue
class RocketBotReceiver
constructor: (message) ->
console.log message
if message.u.username isnt RocketBot.name
RocketBotUser = new Hubot.User(message.u.username, room: message.rid)
RocketBotTextMessage = new Hubot.TextMessage(RocketBotUser, message.msg, message._id)
RocketBot.adapter.receive RocketBotTextMessage
return message
class HubotScripts
constructor: (robot) ->
modulesToLoad = [
'hubot-youtube/src/youtube.coffee'
'hubot-maps/src/maps.coffee'
'hubot-google-translate/src/google-translate.coffee'
'hubot-google-images/src/google-images.coffee'
'hubot-calculator/src/calculator.coffee'
'hubot-help/src/help.coffee'
]
for modulePath in modulesToLoad
try
Npm.require(modulePath)(robot)
robot.parseHelp __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/'+modulePath
console.log "Loaded #{modulePath}".green
catch e
console.log "can't load #{modulePath}".red
console.log e
# scriptFiles = fs.readdirSync(__meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts')
scriptsToLoad = [
'alot.coffee'
'applause.coffee'
'bang-bang.coffee'
'base58.coffee'
'base64.coffee'
'beerme.coffee'
'botsnack.coffee'
'brewerydb.coffee'
'calm-down.coffee'
'carlton.coffee'
'chuck-norris.coffee'
'commandlinefu.coffee'
'commitmessage.coffee'
'dealwithit.coffee'
'decide.coffee'
'dice.coffee'
'do-it.coffee'
'dribbble.coffee'
'encourage.coffee'
'excuse.coffee'
'factoid.coffee'
'futurama.coffee'
'go-for-it.coffee'
'gob.coffee'
'google.coffee'
'gorbypuff.coffee'
'hangout.coffee'
'hashing.coffee'
'hello.coffee'
'homer.coffee'
'httpcat.coffee'
'karma.coffee'
'megusta.coffee'
'nice.coffee'
'play.coffee'
'plus_one.coffee'
'polite.coffee'
'reddit-jokes.coffee'
'reload.coffee'
'sealab.coffee'
'sheits.coffee'
'shipit.coffee'
'talklikewarrenellis.coffee'
'url.coffee'
'wits.coffee'
'wordnik.coffee'
'yoda-pictures.coffee'
'yoda-quotes.coffee'
'zen.coffee'
'zombies.coffee'
]
for scriptFile in scriptsToLoad
try
Npm.require('hubot-scripts/src/scripts/'+scriptFile)(robot)
# robot.loadFile __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts', scriptFile
robot.parseHelp __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts/'+scriptFile
console.log "Loaded #{scriptFile}".green
catch e
console.log "can't load #{scriptFile}".red
console.log e
# console.log __meteor_bootstrap__.serverDir
# npm/rocketchat_hubot/node_modules
# packages/rocketchat_hubot.js
# # load all scripts in scripts/
# console.log path.resolve '.'
# scriptPath = path.resolve __dirname, 'scripts'
# console.log scriptPath
# for file in fs.readdirSync(scriptPath)
# continue unless /\.(coffee|js)$/.test(file)
# robot.loadFile scriptPath, file
# return
# # load all scripts from hubot-scripts
# scriptPath = path.resolve __dirname, 'node_modules', 'hubot-scripts', 'src', 'scripts'
# scripts = require './hubot-scripts.json'
# robot.loadHubotScripts scriptPath, scripts
# robot.parseHelp path.join scriptPath, 'meme_captain.coffee'
# # load all hubot-* modules from package.json
# packageJson = require './package.json'
# pkgs = (pkg for own pkg, version of packageJson.dependencies when !/^(coffee-script|hubot-scripts|hubot-help)$/.test(pkg))
# pkgs.forEach (p) -> (require p)(robot)
# # A special hack for hubot-help: ensure it replies via pm
# privRobot = Object.create robot
# privRobot.respond = (regex, cb) ->
# robot.respond regex, (resp) ->
# resp.message.private = true
# cb(resp)
# (require 'hubot-help')(privRobot)
# # A special hack for meme_captain: change its "respond" invocations to "hear" so that it memes everywhere.
# memecaptain = require './node_modules/hubot-scripts/src/scripts/meme_captain'
# memecaptain
# respond: (regex, cb) ->
# robot.hear regex, (msg) ->
# cb(msg) if msg.envelope.room is 'general/0' or /^\s*[@]?(rocket)?bot\b/i.test(msg.message.text)
sendHelper = Meteor.bindEnvironment (robot, envelope, strings, map) ->
while strings.length > 0
string = strings.shift()
if typeof(string) == 'function'
string()
else
try
map(string)
catch err
console.error "Hubot error: #{err}" if DEBUG
robot.logger.error "RocketChat send error: #{err}"
RocketBot = new Robot null, null, false, 'rocketbot'
RocketBot.alias = 'bot'
RocketBot.adapter = new RocketChatAdapter RocketBot
HubotScripts(RocketBot)
RocketBot.run()
RocketBot.hear /test/i, (res) ->
res.send "Test? TESTING? WE DON'T NEED NO TEST, EVERYTHING WORKS!"
RocketChat.callbacks.add 'afterSaveMessage', RocketBotReceiver, RocketChat.callbacks.priority.LOW
# Meteor.startup ->
# console.log RocketBot;
# # what's (the regexp for) my name?
# robot.respond /(?:)/, -> false
# mynameRE = robot.listeners.pop().regex
# # register scripts
# HubotScripts(robot)
# Object.keys(share.hubot).forEach (scriptName) ->
# console.log "Loading hubot script: #{scriptName}"
# share.hubot[scriptName](robot)
# # register our nick
# n = Meteor.call 'newNick', {name: 'rocketbot'}
# Meteor.call 'setTag', {type:'nicks', object:n._id, name:'Gravatar', value:'rocket@printf.net', who:n.canon}
# # register our presence in general chat
# keepalive = -> Meteor.call 'setPresence',
# u:
# username: 'rocketbot'
# rid: 'GENERAL'
# present: true
# foreground: true
# keepalive()
# Meteor.setInterval keepalive, 30*1000 # every 30s refresh presence
# # listen to the chat room, ignoring messages sent before we startup
# startup = true
# ChatMessage.find({}).observe
# added: (message) ->
# return if startup
# return if message.u.username is "rocketbot" or message.u.username is ""
# return if message.system or message.action or message.oplog or message.bodyIsHtml
# console.log "Received from #{message.u.username} in #{message.rid}: #{message.body}"\
# if DEBUG
# user = new Hubot.User(message.u.username, room: message.rid)
# tm = new Hubot.TextMessage(user, message.body, message._id)
# tm.private = message.to?
# # if private, ensure it's treated as a direct address
# if tm.private and not mynameRE.test(tm.text)
# tm.text = "#{robot.name} #{tm.text}"
# adapter.receive tm
# startup = false
# Meteor.call "sendMessage",
# rid: 'GENERAL'
# msg: 'wakes up'
# u:
# username: "rocketbot"
# action: true
| 200481 | CoffeeScript = Npm.require('coffee-script')
CoffeeScript.register()
Hubot = Npm.require('hubot')
fs = Npm.require('fs')
path = Npm.require('path')
# Start a hubot, connected to our chat room.
# 'use strict'
# Log messages?
DEBUG = true
# Monkey-patch Hubot to support private messages
Hubot.Response::priv = (strings...) ->
@robot.adapter.priv @envelope, strings...
# More monkey-patching
Hubot.Robot::loadAdapter = -> # disable
# grrrr, Meteor.bindEnvironment doesn't preserve `this` apparently
bind = (f) ->
g = Meteor.bindEnvironment (self, args...) -> f.apply(self, args)
(args...) -> g @, args...
class Robot extends Hubot.Robot
constructor: (args...) ->
super args...
@hear = bind @hear
@respond = bind @respond
@enter = bind @enter
@leave = bind @leave
@topic = bind @topic
@error = bind @error
@catchAll = bind @catchAll
@user = Meteor.users.findOne {username: @name}, fields: username: 1
loadAdapter: -> false
hear: (regex, callback) -> super regex, Meteor.bindEnvironment callback
respond: (regex, callback) -> super regex, Meteor.bindEnvironment callback
enter: (callback) -> super Meteor.bindEnvironment(callback)
leave: (callback) -> super Meteor.bindEnvironment(callback)
topic: (callback) -> super Meteor.bindEnvironment(callback)
error: (callback) -> super Meteor.bindEnvironment(callback)
catchAll: (callback) -> super Meteor.bindEnvironment(callback)
class RocketChatAdapter extends Hubot.Adapter
# Public: Raw method for sending data back to the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
send: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> send'.blue
# console.log envelope, strings
sendHelper @robot, envelope, strings, (string) =>
console.log "send #{envelope.room}: #{string} (#{envelope.user.id})" if DEBUG
RocketChat.sendMessage RocketBot.user, { msg: string }, { _id: envelope.room }
# Public: Raw method for sending emote data back to the chat source.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
emote: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> emote'.blue
sendHelper @robot, envelope, strings, (string) =>
console.log "emote #{envelope.rid}: #{string} (#{envelope.u.username})" if DEBUG
return @priv envelope, "*** #{string} ***" if envelope.message.private
Meteor.call "sendMessage",
msg: string
rid: envelope.rid
action: true
# Priv: our extension -- send a PM to user
priv: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> priv'.blue
sendHelper @robot, envelope, strings, (string) ->
console.log "priv #{envelope.room}: #{string} (#{envelope.user.id})" if DEBUG
Meteor.call "sendMessage",
u:
username: "rocketbot"
to: "#{envelope.user.id}"
msg: string
rid: envelope.room
# Public: Raw method for building a reply and sending it back to the chat
# source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each reply to send.
#
# Returns nothing.
reply: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> reply'.blue
if envelope.message.private
@priv envelope, strings...
else
@send envelope, strings.map((str) -> "#{envelope.user.name}: #{str}")...
# Public: Raw method for setting a topic on the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One more more Strings to set as the topic.
#
# Returns nothing.
topic: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> topic'.blue
# Public: Raw method for playing a sound in the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more strings for each play message to send.
#
# Returns nothing
play: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> play'.blue
# Public: Raw method for invoking the bot to run. Extend this.
#
# Returns nothing.
run: ->
console.log 'ROCKETCHATADAPTER -> run'.blue
@robot.emit 'connected'
@robot.brain.mergeData {}
# @robot.brain.emit 'loaded'
# Public: Raw method for shutting the bot down. Extend this.
#
# Returns nothing.
close: ->
console.log 'ROCKETCHATADAPTER -> close'.blue
class RocketBotReceiver
constructor: (message) ->
console.log message
if message.u.username isnt RocketBot.name
RocketBotUser = new Hubot.User(message.u.username, room: message.rid)
RocketBotTextMessage = new Hubot.TextMessage(RocketBotUser, message.msg, message._id)
RocketBot.adapter.receive RocketBotTextMessage
return message
class HubotScripts
constructor: (robot) ->
modulesToLoad = [
'hubot-youtube/src/youtube.coffee'
'hubot-maps/src/maps.coffee'
'hubot-google-translate/src/google-translate.coffee'
'hubot-google-images/src/google-images.coffee'
'hubot-calculator/src/calculator.coffee'
'hubot-help/src/help.coffee'
]
for modulePath in modulesToLoad
try
Npm.require(modulePath)(robot)
robot.parseHelp __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/'+modulePath
console.log "Loaded #{modulePath}".green
catch e
console.log "can't load #{modulePath}".red
console.log e
# scriptFiles = fs.readdirSync(__meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts')
scriptsToLoad = [
'alot.coffee'
'applause.coffee'
'bang-bang.coffee'
'base58.coffee'
'base64.coffee'
'beerme.coffee'
'botsnack.coffee'
'brewerydb.coffee'
'calm-down.coffee'
'carlton.coffee'
'chuck-norris.coffee'
'commandlinefu.coffee'
'commitmessage.coffee'
'dealwithit.coffee'
'decide.coffee'
'dice.coffee'
'do-it.coffee'
'dribbble.coffee'
'encourage.coffee'
'excuse.coffee'
'factoid.coffee'
'futurama.coffee'
'go-for-it.coffee'
'gob.coffee'
'google.coffee'
'gorbypuff.coffee'
'hangout.coffee'
'hashing.coffee'
'hello.coffee'
'homer.coffee'
'httpcat.coffee'
'karma.coffee'
'megusta.coffee'
'nice.coffee'
'play.coffee'
'plus_one.coffee'
'polite.coffee'
'reddit-jokes.coffee'
'reload.coffee'
'sealab.coffee'
'sheits.coffee'
'shipit.coffee'
'talklikewarrenellis.coffee'
'url.coffee'
'wits.coffee'
'wordnik.coffee'
'yoda-pictures.coffee'
'yoda-quotes.coffee'
'zen.coffee'
'zombies.coffee'
]
for scriptFile in scriptsToLoad
try
Npm.require('hubot-scripts/src/scripts/'+scriptFile)(robot)
# robot.loadFile __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts', scriptFile
robot.parseHelp __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts/'+scriptFile
console.log "Loaded #{scriptFile}".green
catch e
console.log "can't load #{scriptFile}".red
console.log e
# console.log __meteor_bootstrap__.serverDir
# npm/rocketchat_hubot/node_modules
# packages/rocketchat_hubot.js
# # load all scripts in scripts/
# console.log path.resolve '.'
# scriptPath = path.resolve __dirname, 'scripts'
# console.log scriptPath
# for file in fs.readdirSync(scriptPath)
# continue unless /\.(coffee|js)$/.test(file)
# robot.loadFile scriptPath, file
# return
# # load all scripts from hubot-scripts
# scriptPath = path.resolve __dirname, 'node_modules', 'hubot-scripts', 'src', 'scripts'
# scripts = require './hubot-scripts.json'
# robot.loadHubotScripts scriptPath, scripts
# robot.parseHelp path.join scriptPath, 'meme_captain.coffee'
# # load all hubot-* modules from package.json
# packageJson = require './package.json'
# pkgs = (pkg for own pkg, version of packageJson.dependencies when !/^(coffee-script|hubot-scripts|hubot-help)$/.test(pkg))
# pkgs.forEach (p) -> (require p)(robot)
# # A special hack for hubot-help: ensure it replies via pm
# privRobot = Object.create robot
# privRobot.respond = (regex, cb) ->
# robot.respond regex, (resp) ->
# resp.message.private = true
# cb(resp)
# (require 'hubot-help')(privRobot)
# # A special hack for meme_captain: change its "respond" invocations to "hear" so that it memes everywhere.
# memecaptain = require './node_modules/hubot-scripts/src/scripts/meme_captain'
# memecaptain
# respond: (regex, cb) ->
# robot.hear regex, (msg) ->
# cb(msg) if msg.envelope.room is 'general/0' or /^\s*[@]?(rocket)?bot\b/i.test(msg.message.text)
sendHelper = Meteor.bindEnvironment (robot, envelope, strings, map) ->
while strings.length > 0
string = strings.shift()
if typeof(string) == 'function'
string()
else
try
map(string)
catch err
console.error "Hubot error: #{err}" if DEBUG
robot.logger.error "RocketChat send error: #{err}"
RocketBot = new Robot null, null, false, 'rocketbot'
RocketBot.alias = 'bot'
RocketBot.adapter = new RocketChatAdapter RocketBot
HubotScripts(RocketBot)
RocketBot.run()
RocketBot.hear /test/i, (res) ->
res.send "Test? TESTING? WE DON'T NEED NO TEST, EVERYTHING WORKS!"
RocketChat.callbacks.add 'afterSaveMessage', RocketBotReceiver, RocketChat.callbacks.priority.LOW
# Meteor.startup ->
# console.log RocketBot;
# # what's (the regexp for) my name?
# robot.respond /(?:)/, -> false
# mynameRE = robot.listeners.pop().regex
# # register scripts
# HubotScripts(robot)
# Object.keys(share.hubot).forEach (scriptName) ->
# console.log "Loading hubot script: #{scriptName}"
# share.hubot[scriptName](robot)
# # register our nick
# n = Meteor.call 'newNick', {name: 'rocketbot'}
# Meteor.call 'setTag', {type:'nicks', object:n._id, name:'Gr<NAME>', value:'<EMAIL>', who:n.canon}
# # register our presence in general chat
# keepalive = -> Meteor.call 'setPresence',
# u:
# username: 'rocketbot'
# rid: 'GENERAL'
# present: true
# foreground: true
# keepalive()
# Meteor.setInterval keepalive, 30*1000 # every 30s refresh presence
# # listen to the chat room, ignoring messages sent before we startup
# startup = true
# ChatMessage.find({}).observe
# added: (message) ->
# return if startup
# return if message.u.username is "rocketbot" or message.u.username is ""
# return if message.system or message.action or message.oplog or message.bodyIsHtml
# console.log "Received from #{message.u.username} in #{message.rid}: #{message.body}"\
# if DEBUG
# user = new Hubot.User(message.u.username, room: message.rid)
# tm = new Hubot.TextMessage(user, message.body, message._id)
# tm.private = message.to?
# # if private, ensure it's treated as a direct address
# if tm.private and not mynameRE.test(tm.text)
# tm.text = "#{robot.name} #{tm.text}"
# adapter.receive tm
# startup = false
# Meteor.call "sendMessage",
# rid: 'GENERAL'
# msg: 'wakes up'
# u:
# username: "rocketbot"
# action: true
| true | CoffeeScript = Npm.require('coffee-script')
CoffeeScript.register()
Hubot = Npm.require('hubot')
fs = Npm.require('fs')
path = Npm.require('path')
# Start a hubot, connected to our chat room.
# 'use strict'
# Log messages?
DEBUG = true
# Monkey-patch Hubot to support private messages
Hubot.Response::priv = (strings...) ->
@robot.adapter.priv @envelope, strings...
# More monkey-patching
Hubot.Robot::loadAdapter = -> # disable
# grrrr, Meteor.bindEnvironment doesn't preserve `this` apparently
bind = (f) ->
g = Meteor.bindEnvironment (self, args...) -> f.apply(self, args)
(args...) -> g @, args...
class Robot extends Hubot.Robot
constructor: (args...) ->
super args...
@hear = bind @hear
@respond = bind @respond
@enter = bind @enter
@leave = bind @leave
@topic = bind @topic
@error = bind @error
@catchAll = bind @catchAll
@user = Meteor.users.findOne {username: @name}, fields: username: 1
loadAdapter: -> false
hear: (regex, callback) -> super regex, Meteor.bindEnvironment callback
respond: (regex, callback) -> super regex, Meteor.bindEnvironment callback
enter: (callback) -> super Meteor.bindEnvironment(callback)
leave: (callback) -> super Meteor.bindEnvironment(callback)
topic: (callback) -> super Meteor.bindEnvironment(callback)
error: (callback) -> super Meteor.bindEnvironment(callback)
catchAll: (callback) -> super Meteor.bindEnvironment(callback)
class RocketChatAdapter extends Hubot.Adapter
# Public: Raw method for sending data back to the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
send: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> send'.blue
# console.log envelope, strings
sendHelper @robot, envelope, strings, (string) =>
console.log "send #{envelope.room}: #{string} (#{envelope.user.id})" if DEBUG
RocketChat.sendMessage RocketBot.user, { msg: string }, { _id: envelope.room }
# Public: Raw method for sending emote data back to the chat source.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each message to send.
#
# Returns nothing.
emote: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> emote'.blue
sendHelper @robot, envelope, strings, (string) =>
console.log "emote #{envelope.rid}: #{string} (#{envelope.u.username})" if DEBUG
return @priv envelope, "*** #{string} ***" if envelope.message.private
Meteor.call "sendMessage",
msg: string
rid: envelope.rid
action: true
# Priv: our extension -- send a PM to user
priv: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> priv'.blue
sendHelper @robot, envelope, strings, (string) ->
console.log "priv #{envelope.room}: #{string} (#{envelope.user.id})" if DEBUG
Meteor.call "sendMessage",
u:
username: "rocketbot"
to: "#{envelope.user.id}"
msg: string
rid: envelope.room
# Public: Raw method for building a reply and sending it back to the chat
# source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more Strings for each reply to send.
#
# Returns nothing.
reply: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> reply'.blue
if envelope.message.private
@priv envelope, strings...
else
@send envelope, strings.map((str) -> "#{envelope.user.name}: #{str}")...
# Public: Raw method for setting a topic on the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One more more Strings to set as the topic.
#
# Returns nothing.
topic: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> topic'.blue
# Public: Raw method for playing a sound in the chat source. Extend this.
#
# envelope - A Object with message, room and user details.
# strings - One or more strings for each play message to send.
#
# Returns nothing
play: (envelope, strings...) ->
console.log 'ROCKETCHATADAPTER -> play'.blue
# Public: Raw method for invoking the bot to run. Extend this.
#
# Returns nothing.
run: ->
console.log 'ROCKETCHATADAPTER -> run'.blue
@robot.emit 'connected'
@robot.brain.mergeData {}
# @robot.brain.emit 'loaded'
# Public: Raw method for shutting the bot down. Extend this.
#
# Returns nothing.
close: ->
console.log 'ROCKETCHATADAPTER -> close'.blue
class RocketBotReceiver
constructor: (message) ->
console.log message
if message.u.username isnt RocketBot.name
RocketBotUser = new Hubot.User(message.u.username, room: message.rid)
RocketBotTextMessage = new Hubot.TextMessage(RocketBotUser, message.msg, message._id)
RocketBot.adapter.receive RocketBotTextMessage
return message
class HubotScripts
constructor: (robot) ->
modulesToLoad = [
'hubot-youtube/src/youtube.coffee'
'hubot-maps/src/maps.coffee'
'hubot-google-translate/src/google-translate.coffee'
'hubot-google-images/src/google-images.coffee'
'hubot-calculator/src/calculator.coffee'
'hubot-help/src/help.coffee'
]
for modulePath in modulesToLoad
try
Npm.require(modulePath)(robot)
robot.parseHelp __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/'+modulePath
console.log "Loaded #{modulePath}".green
catch e
console.log "can't load #{modulePath}".red
console.log e
# scriptFiles = fs.readdirSync(__meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts')
scriptsToLoad = [
'alot.coffee'
'applause.coffee'
'bang-bang.coffee'
'base58.coffee'
'base64.coffee'
'beerme.coffee'
'botsnack.coffee'
'brewerydb.coffee'
'calm-down.coffee'
'carlton.coffee'
'chuck-norris.coffee'
'commandlinefu.coffee'
'commitmessage.coffee'
'dealwithit.coffee'
'decide.coffee'
'dice.coffee'
'do-it.coffee'
'dribbble.coffee'
'encourage.coffee'
'excuse.coffee'
'factoid.coffee'
'futurama.coffee'
'go-for-it.coffee'
'gob.coffee'
'google.coffee'
'gorbypuff.coffee'
'hangout.coffee'
'hashing.coffee'
'hello.coffee'
'homer.coffee'
'httpcat.coffee'
'karma.coffee'
'megusta.coffee'
'nice.coffee'
'play.coffee'
'plus_one.coffee'
'polite.coffee'
'reddit-jokes.coffee'
'reload.coffee'
'sealab.coffee'
'sheits.coffee'
'shipit.coffee'
'talklikewarrenellis.coffee'
'url.coffee'
'wits.coffee'
'wordnik.coffee'
'yoda-pictures.coffee'
'yoda-quotes.coffee'
'zen.coffee'
'zombies.coffee'
]
for scriptFile in scriptsToLoad
try
Npm.require('hubot-scripts/src/scripts/'+scriptFile)(robot)
# robot.loadFile __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts', scriptFile
robot.parseHelp __meteor_bootstrap__.serverDir+'/npm/rocketchat_hubot/node_modules/hubot-scripts/src/scripts/'+scriptFile
console.log "Loaded #{scriptFile}".green
catch e
console.log "can't load #{scriptFile}".red
console.log e
# console.log __meteor_bootstrap__.serverDir
# npm/rocketchat_hubot/node_modules
# packages/rocketchat_hubot.js
# # load all scripts in scripts/
# console.log path.resolve '.'
# scriptPath = path.resolve __dirname, 'scripts'
# console.log scriptPath
# for file in fs.readdirSync(scriptPath)
# continue unless /\.(coffee|js)$/.test(file)
# robot.loadFile scriptPath, file
# return
# # load all scripts from hubot-scripts
# scriptPath = path.resolve __dirname, 'node_modules', 'hubot-scripts', 'src', 'scripts'
# scripts = require './hubot-scripts.json'
# robot.loadHubotScripts scriptPath, scripts
# robot.parseHelp path.join scriptPath, 'meme_captain.coffee'
# # load all hubot-* modules from package.json
# packageJson = require './package.json'
# pkgs = (pkg for own pkg, version of packageJson.dependencies when !/^(coffee-script|hubot-scripts|hubot-help)$/.test(pkg))
# pkgs.forEach (p) -> (require p)(robot)
# # A special hack for hubot-help: ensure it replies via pm
# privRobot = Object.create robot
# privRobot.respond = (regex, cb) ->
# robot.respond regex, (resp) ->
# resp.message.private = true
# cb(resp)
# (require 'hubot-help')(privRobot)
# # A special hack for meme_captain: change its "respond" invocations to "hear" so that it memes everywhere.
# memecaptain = require './node_modules/hubot-scripts/src/scripts/meme_captain'
# memecaptain
# respond: (regex, cb) ->
# robot.hear regex, (msg) ->
# cb(msg) if msg.envelope.room is 'general/0' or /^\s*[@]?(rocket)?bot\b/i.test(msg.message.text)
sendHelper = Meteor.bindEnvironment (robot, envelope, strings, map) ->
while strings.length > 0
string = strings.shift()
if typeof(string) == 'function'
string()
else
try
map(string)
catch err
console.error "Hubot error: #{err}" if DEBUG
robot.logger.error "RocketChat send error: #{err}"
RocketBot = new Robot null, null, false, 'rocketbot'
RocketBot.alias = 'bot'
RocketBot.adapter = new RocketChatAdapter RocketBot
HubotScripts(RocketBot)
RocketBot.run()
RocketBot.hear /test/i, (res) ->
res.send "Test? TESTING? WE DON'T NEED NO TEST, EVERYTHING WORKS!"
RocketChat.callbacks.add 'afterSaveMessage', RocketBotReceiver, RocketChat.callbacks.priority.LOW
# Meteor.startup ->
# console.log RocketBot;
# # what's (the regexp for) my name?
# robot.respond /(?:)/, -> false
# mynameRE = robot.listeners.pop().regex
# # register scripts
# HubotScripts(robot)
# Object.keys(share.hubot).forEach (scriptName) ->
# console.log "Loading hubot script: #{scriptName}"
# share.hubot[scriptName](robot)
# # register our nick
# n = Meteor.call 'newNick', {name: 'rocketbot'}
# Meteor.call 'setTag', {type:'nicks', object:n._id, name:'GrPI:NAME:<NAME>END_PI', value:'PI:EMAIL:<EMAIL>END_PI', who:n.canon}
# # register our presence in general chat
# keepalive = -> Meteor.call 'setPresence',
# u:
# username: 'rocketbot'
# rid: 'GENERAL'
# present: true
# foreground: true
# keepalive()
# Meteor.setInterval keepalive, 30*1000 # every 30s refresh presence
# # listen to the chat room, ignoring messages sent before we startup
# startup = true
# ChatMessage.find({}).observe
# added: (message) ->
# return if startup
# return if message.u.username is "rocketbot" or message.u.username is ""
# return if message.system or message.action or message.oplog or message.bodyIsHtml
# console.log "Received from #{message.u.username} in #{message.rid}: #{message.body}"\
# if DEBUG
# user = new Hubot.User(message.u.username, room: message.rid)
# tm = new Hubot.TextMessage(user, message.body, message._id)
# tm.private = message.to?
# # if private, ensure it's treated as a direct address
# if tm.private and not mynameRE.test(tm.text)
# tm.text = "#{robot.name} #{tm.text}"
# adapter.receive tm
# startup = false
# Meteor.call "sendMessage",
# rid: 'GENERAL'
# msg: 'wakes up'
# u:
# username: "rocketbot"
# action: true
|
[
{
"context": "orizontal: false\n\n\n#Change title here\n(titles = [\"Bobby Drake\", \"Scott Summers\",\"Jean Grey\", \"Warren Worthingto",
"end": 327,
"score": 0.999894380569458,
"start": 316,
"tag": "NAME",
"value": "Bobby Drake"
},
{
"context": "e\n\n\n#Change title here\n(titles = [\"Bobby Drake\", \"Scott Summers\",\"Jean Grey\", \"Warren Worthington III\", \"Hank McC",
"end": 344,
"score": 0.9998869299888611,
"start": 331,
"tag": "NAME",
"value": "Scott Summers"
},
{
"context": "e here\n(titles = [\"Bobby Drake\", \"Scott Summers\",\"Jean Grey\", \"Warren Worthington III\", \"Hank McCoy\", \"Kurt W",
"end": 356,
"score": 0.9998912811279297,
"start": 347,
"tag": "NAME",
"value": "Jean Grey"
},
{
"context": "s = [\"Bobby Drake\", \"Scott Summers\",\"Jean Grey\", \"Warren Worthington III\", \"Hank McCoy\", \"Kurt Wagner\", \"Lorna Dane\", \"Kev",
"end": 382,
"score": 0.999819815158844,
"start": 360,
"tag": "NAME",
"value": "Warren Worthington III"
},
{
"context": " Summers\",\"Jean Grey\", \"Warren Worthington III\", \"Hank McCoy\", \"Kurt Wagner\", \"Lorna Dane\", \"Kevin Sydney\", \"A",
"end": 396,
"score": 0.9998943209648132,
"start": 386,
"tag": "NAME",
"value": "Hank McCoy"
},
{
"context": "n Grey\", \"Warren Worthington III\", \"Hank McCoy\", \"Kurt Wagner\", \"Lorna Dane\", \"Kevin Sydney\", \"Armando Muñoz\"])",
"end": 411,
"score": 0.9998943209648132,
"start": 400,
"tag": "NAME",
"value": "Kurt Wagner"
},
{
"context": "n Worthington III\", \"Hank McCoy\", \"Kurt Wagner\", \"Lorna Dane\", \"Kevin Sydney\", \"Armando Muñoz\"])\n\n#Change SubB",
"end": 425,
"score": 0.9998915195465088,
"start": 415,
"tag": "NAME",
"value": "Lorna Dane"
},
{
"context": "III\", \"Hank McCoy\", \"Kurt Wagner\", \"Lorna Dane\", \"Kevin Sydney\", \"Armando Muñoz\"])\n\n#Change SubBelow text here\n(",
"end": 441,
"score": 0.9998974800109863,
"start": 429,
"tag": "NAME",
"value": "Kevin Sydney"
},
{
"context": "y\", \"Kurt Wagner\", \"Lorna Dane\", \"Kevin Sydney\", \"Armando Muñoz\"])\n\n#Change SubBelow text here\n(subbelow = [\"123 ",
"end": 458,
"score": 0.9998900294303894,
"start": 445,
"tag": "NAME",
"value": "Armando Muñoz"
}
] | Android-Components/Lists/List_SubBelow.coffee | iamkeeler/UXTOOLTIME-Framer | 4 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#List_SubBelow
# Create the draggable layer
scrollpanel = new ScrollComponent
width: Screen.width
height: Screen.height - 80
x: Align.center
y: Align.bottom
backgroundColor: "#F2F2F2"
scrollHorizontal: false
#Change title here
(titles = ["Bobby Drake", "Scott Summers","Jean Grey", "Warren Worthington III", "Hank McCoy", "Kurt Wagner", "Lorna Dane", "Kevin Sydney", "Armando Muñoz"])
#Change SubBelow text here
(subbelow = ["123 Oak Street","345 Elm Street","456 Spruce Street","567 Pine Avenue",
"678 Birch Street","789 Sycamore Road","123 Maple Court","345 Willow Court","678 Cedar Street"])
#Change SubRight text here
(subright = ["2", "10", "3", "1", "0", "0", "12", "5", "4"])
Items = []
for i in [0...8]
LineItem = new Layer
height: 72
width: Screen.width
backgroundColor: "#fff"
y: i *72
#y: Align.top 80
x: Align.center
z: 1
name: [i]
parent: scrollpanel.content
Title = new TextLayer
text: titles[i]
fontFamily: "Roboto"
fontSize: 16
fontWeight: 400
color: "#2F2F2F"
x: 16
y: 16
parent: LineItem
SubBelow = new TextLayer
text: subbelow[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 400
color: "#000000"
opacity: 0.54
x: 16
y: 38
lineHeight: 1.0
parent: LineItem
#Uncomment to show SubRight
# SubRight = new TextLayer
# text: subright[i]
# fontFamily: "Roboto"
# fontSize: 14
# fontWeight: 500
# color: "#626161"
# y: Align.center
# x: Align.right
# padding: right: 20
# parent: LineItem
Divider = new Layer
width: Screen.width
height: 1
y: Align.bottom
x: Align.right
parent: LineItem
backgroundColor: "rgba(0,0,0,0.12)"
# </fold>
"""
| 1782 | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#List_SubBelow
# Create the draggable layer
scrollpanel = new ScrollComponent
width: Screen.width
height: Screen.height - 80
x: Align.center
y: Align.bottom
backgroundColor: "#F2F2F2"
scrollHorizontal: false
#Change title here
(titles = ["<NAME>", "<NAME>","<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"])
#Change SubBelow text here
(subbelow = ["123 Oak Street","345 Elm Street","456 Spruce Street","567 Pine Avenue",
"678 Birch Street","789 Sycamore Road","123 Maple Court","345 Willow Court","678 Cedar Street"])
#Change SubRight text here
(subright = ["2", "10", "3", "1", "0", "0", "12", "5", "4"])
Items = []
for i in [0...8]
LineItem = new Layer
height: 72
width: Screen.width
backgroundColor: "#fff"
y: i *72
#y: Align.top 80
x: Align.center
z: 1
name: [i]
parent: scrollpanel.content
Title = new TextLayer
text: titles[i]
fontFamily: "Roboto"
fontSize: 16
fontWeight: 400
color: "#2F2F2F"
x: 16
y: 16
parent: LineItem
SubBelow = new TextLayer
text: subbelow[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 400
color: "#000000"
opacity: 0.54
x: 16
y: 38
lineHeight: 1.0
parent: LineItem
#Uncomment to show SubRight
# SubRight = new TextLayer
# text: subright[i]
# fontFamily: "Roboto"
# fontSize: 14
# fontWeight: 500
# color: "#626161"
# y: Align.center
# x: Align.right
# padding: right: 20
# parent: LineItem
Divider = new Layer
width: Screen.width
height: 1
y: Align.bottom
x: Align.right
parent: LineItem
backgroundColor: "rgba(0,0,0,0.12)"
# </fold>
"""
| true | plugin.run = (contents, options) ->
"""
#{contents}
# <fold>
#List_SubBelow
# Create the draggable layer
scrollpanel = new ScrollComponent
width: Screen.width
height: Screen.height - 80
x: Align.center
y: Align.bottom
backgroundColor: "#F2F2F2"
scrollHorizontal: false
#Change title here
(titles = ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"])
#Change SubBelow text here
(subbelow = ["123 Oak Street","345 Elm Street","456 Spruce Street","567 Pine Avenue",
"678 Birch Street","789 Sycamore Road","123 Maple Court","345 Willow Court","678 Cedar Street"])
#Change SubRight text here
(subright = ["2", "10", "3", "1", "0", "0", "12", "5", "4"])
Items = []
for i in [0...8]
LineItem = new Layer
height: 72
width: Screen.width
backgroundColor: "#fff"
y: i *72
#y: Align.top 80
x: Align.center
z: 1
name: [i]
parent: scrollpanel.content
Title = new TextLayer
text: titles[i]
fontFamily: "Roboto"
fontSize: 16
fontWeight: 400
color: "#2F2F2F"
x: 16
y: 16
parent: LineItem
SubBelow = new TextLayer
text: subbelow[i]
fontFamily: "Roboto"
fontSize: 14
fontWeight: 400
color: "#000000"
opacity: 0.54
x: 16
y: 38
lineHeight: 1.0
parent: LineItem
#Uncomment to show SubRight
# SubRight = new TextLayer
# text: subright[i]
# fontFamily: "Roboto"
# fontSize: 14
# fontWeight: 500
# color: "#626161"
# y: Align.center
# x: Align.right
# padding: right: 20
# parent: LineItem
Divider = new Layer
width: Screen.width
height: 1
y: Align.bottom
x: Align.right
parent: LineItem
backgroundColor: "rgba(0,0,0,0.12)"
# </fold>
"""
|
[
{
"context": "ser = robot.brain.userForId '1', {\n name: 'ngs'\n room: '#mocha'\n }\n user2 = rob",
"end": 2479,
"score": 0.6208128333091736,
"start": 2476,
"tag": "NAME",
"value": "ngs"
},
{
"context": "er2 = robot.brain.userForId '2', {\n name: 'pyc'\n room: '#mocha'\n }\n adapter = r",
"end": 2573,
"score": 0.907857358455658,
"start": 2570,
"tag": "NAME",
"value": "pyc"
}
] | spec/suncalc_spec.coffee | ngs/hubot-suncalc | 1 | path = require 'path'
fs = require 'fs'
Robot = require("hubot/src/robot")
TextMessage = require("hubot/src/message").TextMessage
nock = require 'nock'
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
{ expect } = chai
describe 'hubot-suncalc', ->
robot = null
user = null
user2 = null
adapter = null
nockScope = null
clock = null
ginzaCandidates = """
Found 12 locations for "ginza".
Answer leading index number:
1. Ginza, Chūō, Tokyo, Japan
2. Ginza, Kumagaya, Saitama Prefecture, Japan
3. Ginza, Honjo, Saitama Prefecture, Japan
4. Ginza, Shimizu Ward, Shizuoka, Shizuoka Prefecture, Japan
5. Ginza, Shunan, Yamaguchi Prefecture, Japan
6. Ginza, Okaya, Nagano Prefecture, Japan
7. Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan
8. Ginza, Iida, Nagano Prefecture, Japan
9. Ginza, Kariya, Aichi Prefecture, Japan
10. Ginza, Tokushima, Tokushima Prefecture, Japan
11. Ginza, Kanuma, Tochigi Prefecture, Japan
12. Ginza, Angola
"""
mockResult = (query, filename)->
nock.disableNetConnect()
nockScope = nock('https://maps.googleapis.com')
nockScope
.get("/maps/api/geocode/json?language=en&address=#{query}&key=fake-key")
.replyWithFile 200, "#{__dirname}/fixtures/#{filename}.json"
tz = if query is 'taipei' then 'tst' else 'jst'
loc = {
tst: '25.091075,121.5598345'
jst: '33.8983681,130.8189646'
}[tz]
nockScope
.get("/maps/api/timezone/json?language=en&location=#{encodeURIComponent loc}×tamp=1407628800&key=fake-key")
.replyWithFile 200, "#{__dirname}/fixtures/#{tz}.json"
adapterEvent = (event, done, example)->
adapter.once event, ->
try
example.apply this, arguments
catch e
done e
beforeEach (done)->
process.env.HUBOT_GOOGLE_API_KEY = 'fake-key'
robot = new Robot null, 'mock-adapter', yes, 'TestHubot'
robot.adapter.on 'connected', ->
robot.loadFile path.resolve('.', 'src', 'scripts'), 'suncalc.coffee'
hubotScripts = path.resolve 'node_modules', 'hubot', 'src', 'scripts'
robot.loadFile hubotScripts, 'help.coffee'
user = robot.brain.userForId '1', {
name: 'ngs'
room: '#mocha'
}
user2 = robot.brain.userForId '2', {
name: 'pyc'
room: '#mocha'
}
adapter = robot.adapter
waitForHelp = ->
if robot.helpCommands().length > 0
do done
else
setTimeout waitForHelp, 100
do waitForHelp
do robot.run
afterEach ->
clock?.restore()
clock = null
nock.cleanAll()
robot.server.close()
robot.shutdown()
robot.cloudfront?.watcher.stop()
process.removeAllListeners 'uncaughtException'
process.env.HUBOT_GOOGLE_API_KEY = null
describe 'help', ->
it 'should have 5', (done)->
expect(robot.helpCommands()).to.have.length 5
do done
it 'should parse help', (done)->
adapterEvent 'send', done, (envelope, strings)->
expect(strings).to.deep.equal ["""
TestHubot help - Displays all of the help commands that TestHubot knows about.
TestHubot help <query> - Displays all help commands that match <query>.
TestHubot moonphase - Replies moonphase of the date.
TestHubot sunrise <location> - Replies sunrise of the date.
TestHubot sunset <location> - Replies sunset of the date.
"""]
do done
adapter.receive new TextMessage user, 'TestHubot help'
describe 'suncalc', ->
beforeEach ->
clock = sinon.useFakeTimers new Date('Sun, 10 Aug 2014 00:00:00 GMT').getTime(), 'Date'
describe 'sunrise', ->
it 'replies time if found 1 location', (done)->
mockResult 'taipei', 'single'
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['Sunrise in Taipei City, Taiwan is 05:26 AM']
do done
adapter.receive new TextMessage user, 'testhubot sunrise taipei '
it 'ask selection if found multiple locations', (done)->
mockResult 'ginza', 'multiple'
adapterEvent 'reply', done, (envelope, strings)->
expect(robot.listeners).to.have.length 5
expect(envelope).not.to.be.null
expect(strings).to.deep.equal [ginzaCandidates]
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(robot.listeners).to.have.length 4
expect(strings).to.deep.equal ['Sunrise in Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan is 05:35 AM']
do done
adapter.receive new TextMessage user2, ' 5 '
expect(robot.listeners).to.have.length 5
adapter.receive new TextMessage user, ' 7 '
expect(robot.listeners).to.have.length 4
adapter.receive new TextMessage user, 'testhubot sunrise ginza '
describe 'sunset', ->
it 'replies time if found 1 location', (done)->
mockResult 'taipei', 'single'
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['Sunset in Taipei City, Taiwan is 06:34 PM']
do done
adapter.receive new TextMessage user, 'testhubot sunset taipei '
it 'ask selection if found multiple locations', (done)->
mockResult 'ginza', 'multiple'
adapterEvent 'reply', done, (envelope, strings)->
expect(robot.listeners).to.have.length 5
expect(envelope).not.to.be.null
expect(strings).to.deep.equal [ginzaCandidates]
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(robot.listeners).to.have.length 4
expect(strings).to.deep.equal ['Sunset in Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan is 07:11 PM']
do done
adapter.receive new TextMessage user2, ' 5 '
expect(robot.listeners).to.have.length 5
adapter.receive new TextMessage user, ' 7 '
expect(robot.listeners).to.have.length 4
adapter.receive new TextMessage user, 'testhubot sunset ginza '
describe 'moonphase', ->
it 'replies moonphase', (done)->
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['🌕 46.83%']
do done
adapter.receive new TextMessage user, 'testhubot moonphase '
| 6863 | path = require 'path'
fs = require 'fs'
Robot = require("hubot/src/robot")
TextMessage = require("hubot/src/message").TextMessage
nock = require 'nock'
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
{ expect } = chai
describe 'hubot-suncalc', ->
robot = null
user = null
user2 = null
adapter = null
nockScope = null
clock = null
ginzaCandidates = """
Found 12 locations for "ginza".
Answer leading index number:
1. Ginza, Chūō, Tokyo, Japan
2. Ginza, Kumagaya, Saitama Prefecture, Japan
3. Ginza, Honjo, Saitama Prefecture, Japan
4. Ginza, Shimizu Ward, Shizuoka, Shizuoka Prefecture, Japan
5. Ginza, Shunan, Yamaguchi Prefecture, Japan
6. Ginza, Okaya, Nagano Prefecture, Japan
7. Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan
8. Ginza, Iida, Nagano Prefecture, Japan
9. Ginza, Kariya, Aichi Prefecture, Japan
10. Ginza, Tokushima, Tokushima Prefecture, Japan
11. Ginza, Kanuma, Tochigi Prefecture, Japan
12. Ginza, Angola
"""
mockResult = (query, filename)->
nock.disableNetConnect()
nockScope = nock('https://maps.googleapis.com')
nockScope
.get("/maps/api/geocode/json?language=en&address=#{query}&key=fake-key")
.replyWithFile 200, "#{__dirname}/fixtures/#{filename}.json"
tz = if query is 'taipei' then 'tst' else 'jst'
loc = {
tst: '25.091075,121.5598345'
jst: '33.8983681,130.8189646'
}[tz]
nockScope
.get("/maps/api/timezone/json?language=en&location=#{encodeURIComponent loc}×tamp=1407628800&key=fake-key")
.replyWithFile 200, "#{__dirname}/fixtures/#{tz}.json"
adapterEvent = (event, done, example)->
adapter.once event, ->
try
example.apply this, arguments
catch e
done e
beforeEach (done)->
process.env.HUBOT_GOOGLE_API_KEY = 'fake-key'
robot = new Robot null, 'mock-adapter', yes, 'TestHubot'
robot.adapter.on 'connected', ->
robot.loadFile path.resolve('.', 'src', 'scripts'), 'suncalc.coffee'
hubotScripts = path.resolve 'node_modules', 'hubot', 'src', 'scripts'
robot.loadFile hubotScripts, 'help.coffee'
user = robot.brain.userForId '1', {
name: '<NAME>'
room: '#mocha'
}
user2 = robot.brain.userForId '2', {
name: '<NAME>'
room: '#mocha'
}
adapter = robot.adapter
waitForHelp = ->
if robot.helpCommands().length > 0
do done
else
setTimeout waitForHelp, 100
do waitForHelp
do robot.run
afterEach ->
clock?.restore()
clock = null
nock.cleanAll()
robot.server.close()
robot.shutdown()
robot.cloudfront?.watcher.stop()
process.removeAllListeners 'uncaughtException'
process.env.HUBOT_GOOGLE_API_KEY = null
describe 'help', ->
it 'should have 5', (done)->
expect(robot.helpCommands()).to.have.length 5
do done
it 'should parse help', (done)->
adapterEvent 'send', done, (envelope, strings)->
expect(strings).to.deep.equal ["""
TestHubot help - Displays all of the help commands that TestHubot knows about.
TestHubot help <query> - Displays all help commands that match <query>.
TestHubot moonphase - Replies moonphase of the date.
TestHubot sunrise <location> - Replies sunrise of the date.
TestHubot sunset <location> - Replies sunset of the date.
"""]
do done
adapter.receive new TextMessage user, 'TestHubot help'
describe 'suncalc', ->
beforeEach ->
clock = sinon.useFakeTimers new Date('Sun, 10 Aug 2014 00:00:00 GMT').getTime(), 'Date'
describe 'sunrise', ->
it 'replies time if found 1 location', (done)->
mockResult 'taipei', 'single'
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['Sunrise in Taipei City, Taiwan is 05:26 AM']
do done
adapter.receive new TextMessage user, 'testhubot sunrise taipei '
it 'ask selection if found multiple locations', (done)->
mockResult 'ginza', 'multiple'
adapterEvent 'reply', done, (envelope, strings)->
expect(robot.listeners).to.have.length 5
expect(envelope).not.to.be.null
expect(strings).to.deep.equal [ginzaCandidates]
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(robot.listeners).to.have.length 4
expect(strings).to.deep.equal ['Sunrise in Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan is 05:35 AM']
do done
adapter.receive new TextMessage user2, ' 5 '
expect(robot.listeners).to.have.length 5
adapter.receive new TextMessage user, ' 7 '
expect(robot.listeners).to.have.length 4
adapter.receive new TextMessage user, 'testhubot sunrise ginza '
describe 'sunset', ->
it 'replies time if found 1 location', (done)->
mockResult 'taipei', 'single'
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['Sunset in Taipei City, Taiwan is 06:34 PM']
do done
adapter.receive new TextMessage user, 'testhubot sunset taipei '
it 'ask selection if found multiple locations', (done)->
mockResult 'ginza', 'multiple'
adapterEvent 'reply', done, (envelope, strings)->
expect(robot.listeners).to.have.length 5
expect(envelope).not.to.be.null
expect(strings).to.deep.equal [ginzaCandidates]
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(robot.listeners).to.have.length 4
expect(strings).to.deep.equal ['Sunset in Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan is 07:11 PM']
do done
adapter.receive new TextMessage user2, ' 5 '
expect(robot.listeners).to.have.length 5
adapter.receive new TextMessage user, ' 7 '
expect(robot.listeners).to.have.length 4
adapter.receive new TextMessage user, 'testhubot sunset ginza '
describe 'moonphase', ->
it 'replies moonphase', (done)->
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['🌕 46.83%']
do done
adapter.receive new TextMessage user, 'testhubot moonphase '
| true | path = require 'path'
fs = require 'fs'
Robot = require("hubot/src/robot")
TextMessage = require("hubot/src/message").TextMessage
nock = require 'nock'
chai = require 'chai'
sinon = require 'sinon'
chai.use require 'sinon-chai'
{ expect } = chai
describe 'hubot-suncalc', ->
robot = null
user = null
user2 = null
adapter = null
nockScope = null
clock = null
ginzaCandidates = """
Found 12 locations for "ginza".
Answer leading index number:
1. Ginza, Chūō, Tokyo, Japan
2. Ginza, Kumagaya, Saitama Prefecture, Japan
3. Ginza, Honjo, Saitama Prefecture, Japan
4. Ginza, Shimizu Ward, Shizuoka, Shizuoka Prefecture, Japan
5. Ginza, Shunan, Yamaguchi Prefecture, Japan
6. Ginza, Okaya, Nagano Prefecture, Japan
7. Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan
8. Ginza, Iida, Nagano Prefecture, Japan
9. Ginza, Kariya, Aichi Prefecture, Japan
10. Ginza, Tokushima, Tokushima Prefecture, Japan
11. Ginza, Kanuma, Tochigi Prefecture, Japan
12. Ginza, Angola
"""
mockResult = (query, filename)->
nock.disableNetConnect()
nockScope = nock('https://maps.googleapis.com')
nockScope
.get("/maps/api/geocode/json?language=en&address=#{query}&key=fake-key")
.replyWithFile 200, "#{__dirname}/fixtures/#{filename}.json"
tz = if query is 'taipei' then 'tst' else 'jst'
loc = {
tst: '25.091075,121.5598345'
jst: '33.8983681,130.8189646'
}[tz]
nockScope
.get("/maps/api/timezone/json?language=en&location=#{encodeURIComponent loc}×tamp=1407628800&key=fake-key")
.replyWithFile 200, "#{__dirname}/fixtures/#{tz}.json"
adapterEvent = (event, done, example)->
adapter.once event, ->
try
example.apply this, arguments
catch e
done e
beforeEach (done)->
process.env.HUBOT_GOOGLE_API_KEY = 'fake-key'
robot = new Robot null, 'mock-adapter', yes, 'TestHubot'
robot.adapter.on 'connected', ->
robot.loadFile path.resolve('.', 'src', 'scripts'), 'suncalc.coffee'
hubotScripts = path.resolve 'node_modules', 'hubot', 'src', 'scripts'
robot.loadFile hubotScripts, 'help.coffee'
user = robot.brain.userForId '1', {
name: 'PI:NAME:<NAME>END_PI'
room: '#mocha'
}
user2 = robot.brain.userForId '2', {
name: 'PI:NAME:<NAME>END_PI'
room: '#mocha'
}
adapter = robot.adapter
waitForHelp = ->
if robot.helpCommands().length > 0
do done
else
setTimeout waitForHelp, 100
do waitForHelp
do robot.run
afterEach ->
clock?.restore()
clock = null
nock.cleanAll()
robot.server.close()
robot.shutdown()
robot.cloudfront?.watcher.stop()
process.removeAllListeners 'uncaughtException'
process.env.HUBOT_GOOGLE_API_KEY = null
describe 'help', ->
it 'should have 5', (done)->
expect(robot.helpCommands()).to.have.length 5
do done
it 'should parse help', (done)->
adapterEvent 'send', done, (envelope, strings)->
expect(strings).to.deep.equal ["""
TestHubot help - Displays all of the help commands that TestHubot knows about.
TestHubot help <query> - Displays all help commands that match <query>.
TestHubot moonphase - Replies moonphase of the date.
TestHubot sunrise <location> - Replies sunrise of the date.
TestHubot sunset <location> - Replies sunset of the date.
"""]
do done
adapter.receive new TextMessage user, 'TestHubot help'
describe 'suncalc', ->
beforeEach ->
clock = sinon.useFakeTimers new Date('Sun, 10 Aug 2014 00:00:00 GMT').getTime(), 'Date'
describe 'sunrise', ->
it 'replies time if found 1 location', (done)->
mockResult 'taipei', 'single'
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['Sunrise in Taipei City, Taiwan is 05:26 AM']
do done
adapter.receive new TextMessage user, 'testhubot sunrise taipei '
it 'ask selection if found multiple locations', (done)->
mockResult 'ginza', 'multiple'
adapterEvent 'reply', done, (envelope, strings)->
expect(robot.listeners).to.have.length 5
expect(envelope).not.to.be.null
expect(strings).to.deep.equal [ginzaCandidates]
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(robot.listeners).to.have.length 4
expect(strings).to.deep.equal ['Sunrise in Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan is 05:35 AM']
do done
adapter.receive new TextMessage user2, ' 5 '
expect(robot.listeners).to.have.length 5
adapter.receive new TextMessage user, ' 7 '
expect(robot.listeners).to.have.length 4
adapter.receive new TextMessage user, 'testhubot sunrise ginza '
describe 'sunset', ->
it 'replies time if found 1 location', (done)->
mockResult 'taipei', 'single'
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['Sunset in Taipei City, Taiwan is 06:34 PM']
do done
adapter.receive new TextMessage user, 'testhubot sunset taipei '
it 'ask selection if found multiple locations', (done)->
mockResult 'ginza', 'multiple'
adapterEvent 'reply', done, (envelope, strings)->
expect(robot.listeners).to.have.length 5
expect(envelope).not.to.be.null
expect(strings).to.deep.equal [ginzaCandidates]
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(robot.listeners).to.have.length 4
expect(strings).to.deep.equal ['Sunset in Ginza, Tobata Ward, Kitakyushu, Fukuoka Prefecture, Japan is 07:11 PM']
do done
adapter.receive new TextMessage user2, ' 5 '
expect(robot.listeners).to.have.length 5
adapter.receive new TextMessage user, ' 7 '
expect(robot.listeners).to.have.length 4
adapter.receive new TextMessage user, 'testhubot sunset ginza '
describe 'moonphase', ->
it 'replies moonphase', (done)->
adapterEvent 'reply', done, (envelope, strings)->
done strings[0]
adapterEvent 'send', done, (envelope, strings)->
expect(envelope).not.to.be.null
expect(strings).to.deep.equal ['🌕 46.83%']
do done
adapter.receive new TextMessage user, 'testhubot moonphase '
|
[
{
"context": ") \n \n # Code based on Polymaps example from Mike Bostock http://bl.ocks.org/899670\n polymaps = or",
"end": 2384,
"score": 0.55869460105896,
"start": 2381,
"tag": "NAME",
"value": "ike"
},
{
"context": " \n # Code based on Polymaps example from Mike Bostock http://bl.ocks.org/899670\n polymaps = org.polyma",
"end": 2392,
"score": 0.6720892190933228,
"start": 2386,
"tag": "NAME",
"value": "ostock"
}
] | breeze-ui.coffee | jrstarke/breeze | 1 | rentalSize = if Modernizr.touch then 12 else 8
busSize = 3.5
busClusterSize = 5
injectLocations = (stops,points) ->
stops.forEach((stop) ->
location = points[stop.p]
stop.lat = location.lat
stop.lon = location.lon
)
trackEvent = (name, values, callback = null) ->
mixpanel.track name, values
if callback
callback()
recordOutboundLink = (link, name, values) ->
recordEvent name, values.source, values.url
trackEvent name, values, () -> window.open(link.href,"_blank")
window.recordOutboundLink = recordOutboundLink
recordEvent = (category, action, label) ->
_gat._getTrackerByName()._trackEvent category, action, label
window.recordEvent = recordEvent
setVariable = (index, name, value) ->
# This custom var is set to slot #1. Required parameter.
# The name acts as a kind of category for the user activity. Required parameter.
# This value of the custom variable. Required parameter.
_gaq.push ["_setCustomVar", index, name, value, 2] # Sets the scope to session-level. Optional parameter.
window.setVariable = setVariable
if Modernizr.svg and Modernizr.inlinesvg
if $(window).height() < 500 or $(window).width() < 500
$(".desktop").hide()
if !($(window).width() < 600 or $.cookie("survey-closed") or $.cookie("survey-visited"))
$(".message").show()
if Modernizr.touch
$(".github").hide()
$(".header").show()
headerToggle = (element) ->
if $("#standard-options").is(":visible")
$("#standard-options").hide "slow"
$(element).button "option", "icons",
primary: "ui-icon-triangle-1-s"
trackEvent 'hid options'
else
$("#standard-options").show "slow"
$(element).button "option", "icons",
primary: "ui-icon-triangle-1-n"
trackEvent 'show options'
$(".header-expand").button(
icons:
primary: "ui-icon ui-icon-triangle-1-n"
text: false
).click ->
headerToggle this
toggleAdditional = ->
if $("#additional-notices").is(":visible")
$("#additional-notices").hide "slow"
$("a#additional-expand").text "additional notices"
trackEvent 'hid notices'
else
$("#additional-notices").show "slow"
$("a#additional-expand").text "less notices"
trackEvent 'show notices'
$("a#additional-expand").click ->
toggleAdditional()
# Code based on Polymaps example from Mike Bostock http://bl.ocks.org/899670
polymaps = org.polymaps
map = polymaps.map().container(d3.select("#map").append("svg:svg").attr("width", "100%").attr("height", "100%").node())
.zoom(13)
.center({lat: 48.455164, lon: -123.351059})# Victoria BC west of Cedar Hill Golf Course
.add(polymaps.drag())
.add(polymaps.wheel().smooth(false))
.add(polymaps.dblclick())
.add(polymaps.arrow())
.add(polymaps.touch())
# Stamen toner tiles http://maps.stamen.com
map.add(polymaps.image().url(polymaps.url("http://tile.stamen.com/toner/{Z}/{X}/{Y}.png")))
# Classes
class Layer
zoomLevel: -> @map.zoom()
@prevZoom = 13
@distance = 0
pixelDistance: ->
p0 = @map.pointLocation({x: 0, y: 0})
p1 = @map.pointLocation({x: 1, y: 1})
@distance = {lat:Math.abs(p0.lat - p1.lat),lon:Math.abs(p0.lon - p1.lon)}
@distance
constructor: (@map) ->
@selector = d3.select("#map svg").insert("svg:g")
@map.on "move", => @update()
@map.on "resize", => @update()
# Lat/Lng transform function
transform: (location) =>
d = @map.locationPoint(location)
"translate(" + d.x + "," + d.y + ")"
cluster: (elements, distance) ->
currentElements = elements.slice(0)
pixelDistance = @pixelDistance()
distLat = distance * pixelDistance.lat
distLon = distance * pixelDistance.lon
clustered = []
while currentElements.length > 0
stop = currentElements.shift()
cluster = []
cluster.push stop
i = 0
while i < currentElements.length
if Math.abs(currentElements[i].lat - stop.lat) < distLat and Math.abs(currentElements[i].lon - stop.lon) < distLon
aStop = currentElements.splice i,1
cluster.push aStop[0]
i--
i++
clustered.push cluster
clustered
filter: (clusters, distance) ->
tLeft = @map.pointLocation({x:0-distance,y:0-distance})
bRight = @map.pointLocation({x: $(window).width()+distance, y: $(window).height()+distance})
output = (cluster for cluster in clusters when bRight.lat <= cluster[0].lat and cluster[0].lat <= tLeft.lat and tLeft.lon <= cluster[0].lon and cluster[0].lon <= bRight.lon)
output
class DistanceLayer extends Layer
stops = []
clusters = []
prevLocalClusters = []
update: ->
if @zoomLevel() != @prevZoom or (@stops and @prevNumStops != @stops.length)
@prevNumStops = @stops.length
@prevZoom = @zoomLevel()
# We clustered the stops if they're within 10 pixels, do the same for the stop layer
@clusters = @cluster(@stops,10)
@localClusters = @filter(@clusters,@distanceInPixels())
if (not @prevLocalClusters) or @prevLocalClusters != @localClusters
@prevLocalClusters = @localClusters
# Add new incoming circles
marker = @selector.selectAll("g").data(@localClusters)
marker.enter().append("g")
.append("circle").attr("class", "reach").attr('r', @distanceInPixels())
# Remove old circles
marker.exit().remove()
#Do this to all remaining circles
@updateCircleRadius()
@selector.selectAll("g").attr("transform", (cluster) => @transform cluster[0])
distanceInMeters = (if $.cookie("distance") then $.cookie("distance") else 500) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
distanceInMeters: () ->
if arguments.length == 0
distanceInMeters
else
distanceInMeters = arguments[0]
$.cookie("distance",distanceInMeters, { expires: 30 })
setVariable(1,"Distance",distanceInMeters.toString())
@updateCircleRadius()
this
distanceInPixels: () ->
# Calculates pixel for 1km distance
# http://jan.ucc.nau.edu/~cvm/latlongdist.html with 0N 0W to 0N 0.008983W is 1km
pixelsPerKm = @map.locationPoint({ lat: 0, lon: 0.008983 }).x - @map.locationPoint({ lat: 0, lon: 0 }).x
@distanceInMeters() / 1000 * pixelsPerKm
updateCircleRadius: ->
@selector.selectAll("circle.reach").attr('r', @distanceInPixels())
addStops: (stops) ->
stops.sort((a,b) -> a.lat-b.lat)
@stops = stops
# TODO just have a single g element that is transformed
#marker = @selector.selectAll("g").data(stops).enter().append("g").attr("transform", @transform)
#marker.append("circle").attr("class", "reach").attr('r', @distanceInPixels())
@update()
class BusRouteLayer extends Layer
svgLine = d3.svg.line().x((d) -> d.x).y((d) -> d.y).interpolate("linear")
update: () -> @selector.selectAll("path").attr("d", (d) => @line(d))
addRoutes: (routes,points) ->
# TODO prevent overplotting by intelligently selecting route segments between stops
# map stops by their id
@line = (route) -> svgLine(route.map((routePoint) => @map.locationPoint(points[routePoint])))
@selector.selectAll("g").data(routes).enter().append("path").attr("class", "route").attr("d", (d) => @line(d))
class BusStopLayer extends Layer
clusters = []
stops = []
prevNumStops = 0
prevLocalClusters = []
update: ->
# If the zoom level changed, re cluster the stops
if @zoomLevel() != @prevZoom or (@stops and @prevNumStops != @stops.length)
if @prevZoom and @zoomLevel() != @prevZoom
trackEvent 'Zoom level changed', {'Zoom level':@zoomLevel()}
@prevNumStops = @stops.length
@prevZoom = @zoomLevel()
@clusters = @cluster(@stops,10)
# Filter out any stops not within an acceptable region of the screen. We'll add them as needed
@localClusters = @filter(@clusters,10)
if (not @prevLocalClusters) or @localClusters != @prevLocalClusters
marker = @selector.selectAll("g").data(@localClusters)
# retained markers are updated
marker.select('circle')
.attr('r', (cluster) -> if cluster.length > 1 then busClusterSize else busSize)
.attr("text", @representCluster)
# new markers are added
marker.enter().append("g")
.append("circle")
.attr("class", "stop no-tip")
.attr('r', (cluster) -> if cluster.length > 1 then busClusterSize else busSize)
.attr("text", @representCluster)
# old markers are removed
marker.exit().remove()
# TODO just have a single g element that is transformed
@selector.selectAll("g")
.attr("transform", (cluster) => @transform cluster[0])
representCluster: (cluster) ->
routes = []
for stop in cluster
for route in stop.routes
routes.push route
# This next two lines should remove duplicates
routes = routes.sort()
routes = (route for route, i in routes when i=0 or route != routes[i-1])
# Now we sort by the numeric route value
routes = routes.sort((a,b) -> parseInt(a.match(/^\d+/)[0]) - parseInt(b.match(/^\d+/)[0]))
# Now layout the sorted routes
"<ul>" + (("<li>" + route + "</li>") for route in routes).join("") + "</ul>"
addStops: (stops) ->
stops.sort((a,b) -> a.lat-b.lat)
@stops = stops
if (not Modernizr.touch)
$(".stop").live("mouseover", (event) ->
$(this).qtip(
overwrite: false
content:
attr: 'text'
show:
event: event.type,
ready: true
hide: 'mouseout'
, event)
)
@update()
#$.cookie("viewed-listings") then JSON.parse($.cookie("viewed-listings")
class RentalsLayer extends Layer
viewedIndices: (if $.cookie("viewed-listings") then JSON.parse($.cookie("viewed-listings")) else new Object())
rentalClass: (rental, i) =>
if (@viewedIndices.hasOwnProperty(rental.id))
if (rental.updated_at > @viewedIndices[rental.id])
delete @viewedIndices[rental.id]
"rental"
else "rental rental-viewed"
else "rental"
priceRange = (if $.cookie("priceLow") and $.cookie("priceHigh") then [$.cookie("priceLow"),$.cookie("priceHigh")] else [0,3000]) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
priceRange: () ->
if arguments.length == 0
priceRange
else
priceRange = arguments[0]
$.cookie("priceLow",priceRange[0], { expires: 30 })
$.cookie("priceHigh",priceRange[1], { expires: 30 })
setVariable(2,"Price Low",priceRange[0].toString())
setVariable(3,"Price High",priceRange[1].toString())
@updateVisibility()
this
roomsRange = (if $.cookie("roomsLow") and $.cookie("roomsHigh") then [$.cookie("roomsLow"),$.cookie("roomsHigh")] else [0,5]) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
roomsRange: () ->
if arguments.length == 0
roomsRange
else
roomsRange = arguments[0]
$.cookie("roomsLow",roomsRange[0], { expires: 30 })
$.cookie("roomsHigh",roomsRange[1], { expires: 30 })
setVariable(4,"Min Rooms", roomsRange[0].toString())
setVariable(5,"Max Rooms", roomsRange[1].toString())
@updateVisibility()
this
allowShared = (if $.cookie("showShared") then $.cookie("showShared") == "true" else false) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
allowShared: () ->
if arguments.length == 0
allowShared
else
allowShared = arguments[0]
$.cookie("showShared",allowShared, { expires: 30 })
@updateVisibility()
this
isNotSharedOrAllowed: (rental) ->
match = /shared|room/i.test(rental.type)
if match
allowShared
else
true
updateVisibility: ->
@selector.selectAll("rect").attr('visibility', (rentals) =>
suites = (suite for suite in rentals.availabilities when suite && priceRange[0] <= suite.price <= priceRange[1] && roomsRange[0] <= suite.bedrooms <= roomsRange[1] )
if suites.length > 0
if @isNotSharedOrAllowed(rentals) then 'visible' else 'hidden'
else
'hidden'
)
update: ->
@selector.selectAll("g").attr("transform", @transform)
$(".rental").qtip('reposition')
convertDateToUTC: (date) ->
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())
setListingDisplay: (rental) ->
listings = (("<li>" + (if suite.bedrooms or suite.bedrooms == 0 then suite.bedrooms else "unknown") + " bedroom: " + (if suite.price > 0 then "$" + suite.price else "Unknown") + "</li>" ) for suite in rental.availabilities)
output = ""
if rental.image_url
output = output + "<a href=\"" + rental.url + "\" target=\"_blank\" onClick=\"recordOutboundLink(this, 'Outbound Links', {\"source\":\"" + rental.source + "\", \"url\":\"" + rental.url + "\", \"price\":\"" + rental.url + "\", \"bedrooms\":\"" + rental.bedrooms + "\"})\"><img class=\"rental-img\" src=\""+ rental.image_url + "\"></a>"
output = output + rental.source + ", " + rental.type + " <br/><ul>" + listings.join("") + "</ul><br /><a href=\"" + rental.url + "\" target=\"_blank\" onClick=\"recordOutboundLink(this, 'Outbound Links', {'source':'" + rental.source + "', 'url':'" + rental.url + "'});return false;\">View Original Listing</a>"
output
addRentals: (rentals) ->
# TODO just have a single g element that is transformed
marker = @selector.selectAll("g").data(rentals).enter().append("g").attr("transform", @transform)
marker.append("rect")
.attr("class", @rentalClass)
.attr("x", -1 * rentalSize /2)
.attr("y", -1 * rentalSize /2)
.attr('height', rentalSize)
.attr('width', rentalSize)
.attr("text", (rental) =>
@setListingDisplay(rental)
)
@updateVisibility()
marker.on("click", (rental, i) =>
@viewedIndices[rental.id] = new Date()*1
$.cookie("viewed-listings", JSON.stringify(@viewedIndices), { expires: 30 })
@selector.selectAll("g").select("rect").attr("class", @rentalClass)
recordEvent('Rental View',rental.source,rental.url)
trackEvent('Rental View',
"Rental Source":rental.source
"url":rental.url
"price":rental.price
"bedrooms":rental.bedrooms
"min price":priceRange[0]
"max price":priceRange[1]
"min rooms":roomsRange[0]
"max rooms":roomsRange[1]
"shared allowed":allowShared
"zoom level":@zoomLevel()
)
)
$(".rental").qtip(
content:
attr: 'text'
title:
text: 'Rental Details'
button: true
show: 'mousedown'
hide: false
position:
my: 'bottom center'
at: 'top center'
style: 'ui-tooltip-tipped'
)
# create layers - order of layers important because of SVG drawing
distanceLayer = new DistanceLayer map
busRouteLayer = new BusRouteLayer map
busStopLayer = new BusStopLayer map
rentalLayer = new RentalsLayer map
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupDistanceSlider = () ->
# TODO support multiple event listers
sliderChanged = (value) ->
$( "#slider-distance > .value" ).html( value + "m" )
distanceLayer.distanceInMeters(value)
$("#slider-distance-element").slider(
range: "min"
value: distanceLayer.distanceInMeters()
step: 10
min: 0
max: 2500
slide: (event, ui) -> sliderChanged(ui.value)
stop: (event, ui) -> trackEvent 'distance changed'
distance: distanceLayer.distanceInMeters()
)
sliderChanged($("#slider-distance-element").slider("value"))
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupPriceSlider = () ->
# TODO support multiple event listers
sliderChanged = (values) ->
$( "#slider-price > .value" ).html( "$" + values[0] + " - " + values[1] )
rentalLayer.priceRange(values)
$("#slider-price-element").slider(
range: true
values: rentalLayer.priceRange()
step: 50
min: 0
max: 3000
slide: (event, ui) -> sliderChanged(ui.values)
stop: (event, ui) -> trackEvent 'price changed'
'low price': rentalLayer.priceRange()[0]
'high price': rentalLayer.priceRange()[1]
)
sliderChanged($("#slider-price-element").slider("values"))
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupRoomsSlider = () ->
# TODO support multiple event listers
sliderChanged = (values) ->
$( "#slider-rooms > .value" ).html( values[0] + " - " + values[1] + " rooms" )
rentalLayer.roomsRange(values)
$("#slider-rooms-element").slider(
range: true
values: rentalLayer.roomsRange()
min: 0
max: 5
slide: (event, ui) -> sliderChanged(ui.values)
stop: (event, ui) -> trackEvent '# rooms changed'
'min rooms': rentalLayer.roomsRange()[0]
'max rooms': rentalLayer.roomsRange()[1]
)
sliderChanged($("#slider-rooms-element").slider("values"))
setupSharedCheckbox = () ->
$("#show-shared").attr 'checked', rentalLayer.allowShared()
$("#show-shared").click ->
rentalLayer.allowShared(this.checked)
if this.checked
trackEvent 'shared selected'
else
trackEvent 'private selected'
loadBusRoutes = () ->
d3.json 'data/uvic_transit.json', (json) ->
points = {}
json.points.forEach((point) ->
points[point.id] = point
)
injectLocations json.stops,points
distanceLayer.addStops json.stops
busRouteLayer.addRoutes json.routes,points
busStopLayer.addStops json.stops
loadRentals = () ->
d3.json 'data/rentals.json', (json) ->
rentalLayer.addRentals json
do ->
setupDistanceSlider()
setupPriceSlider()
setupRoomsSlider()
setupSharedCheckbox()
loadBusRoutes()
loadRentals()
trackEvent('RentalMap loaded')
$(window).unload( () ->
trackEvent('RentalMap closed')
)
$(".message .close").on("click", () ->
$(".message").hide()
$.cookie("survey-closed",true, { expires: 5 })
trackEvent('Survey Closed')
)
$(window).on("resize", () ->
if $(window).width() < 600
$(".message").hide()
else
$(".message").show()
)
addthis.addEventListener('addthis.menu.share', (evt) ->
trackEvent 'AddThis', evt.data
);
# Set to track outbound links from the site
$("a[rel*='external']").click(->
link = $(this)
recordEvent('External Link',link.text(),link.attr('href'))
trackEvent('External Link',{"Link Text":link.text(),"url":link.attr('href')})
)
# Hide the default loading dialog, in case it hasn't been covered yet
$("#loading").hide()
else
$('#unsupportedBrowser').show()
$('.regular').hide()
recordEvent('Unsupported Browser','No SVG' ,navigator.userAgent)
trackEvent('Unsupported Browser',{"Browser":navigator.userAgent})
| 71688 | rentalSize = if Modernizr.touch then 12 else 8
busSize = 3.5
busClusterSize = 5
injectLocations = (stops,points) ->
stops.forEach((stop) ->
location = points[stop.p]
stop.lat = location.lat
stop.lon = location.lon
)
trackEvent = (name, values, callback = null) ->
mixpanel.track name, values
if callback
callback()
recordOutboundLink = (link, name, values) ->
recordEvent name, values.source, values.url
trackEvent name, values, () -> window.open(link.href,"_blank")
window.recordOutboundLink = recordOutboundLink
recordEvent = (category, action, label) ->
_gat._getTrackerByName()._trackEvent category, action, label
window.recordEvent = recordEvent
setVariable = (index, name, value) ->
# This custom var is set to slot #1. Required parameter.
# The name acts as a kind of category for the user activity. Required parameter.
# This value of the custom variable. Required parameter.
_gaq.push ["_setCustomVar", index, name, value, 2] # Sets the scope to session-level. Optional parameter.
window.setVariable = setVariable
if Modernizr.svg and Modernizr.inlinesvg
if $(window).height() < 500 or $(window).width() < 500
$(".desktop").hide()
if !($(window).width() < 600 or $.cookie("survey-closed") or $.cookie("survey-visited"))
$(".message").show()
if Modernizr.touch
$(".github").hide()
$(".header").show()
headerToggle = (element) ->
if $("#standard-options").is(":visible")
$("#standard-options").hide "slow"
$(element).button "option", "icons",
primary: "ui-icon-triangle-1-s"
trackEvent 'hid options'
else
$("#standard-options").show "slow"
$(element).button "option", "icons",
primary: "ui-icon-triangle-1-n"
trackEvent 'show options'
$(".header-expand").button(
icons:
primary: "ui-icon ui-icon-triangle-1-n"
text: false
).click ->
headerToggle this
toggleAdditional = ->
if $("#additional-notices").is(":visible")
$("#additional-notices").hide "slow"
$("a#additional-expand").text "additional notices"
trackEvent 'hid notices'
else
$("#additional-notices").show "slow"
$("a#additional-expand").text "less notices"
trackEvent 'show notices'
$("a#additional-expand").click ->
toggleAdditional()
# Code based on Polymaps example from M<NAME> B<NAME> http://bl.ocks.org/899670
polymaps = org.polymaps
map = polymaps.map().container(d3.select("#map").append("svg:svg").attr("width", "100%").attr("height", "100%").node())
.zoom(13)
.center({lat: 48.455164, lon: -123.351059})# Victoria BC west of Cedar Hill Golf Course
.add(polymaps.drag())
.add(polymaps.wheel().smooth(false))
.add(polymaps.dblclick())
.add(polymaps.arrow())
.add(polymaps.touch())
# Stamen toner tiles http://maps.stamen.com
map.add(polymaps.image().url(polymaps.url("http://tile.stamen.com/toner/{Z}/{X}/{Y}.png")))
# Classes
class Layer
zoomLevel: -> @map.zoom()
@prevZoom = 13
@distance = 0
pixelDistance: ->
p0 = @map.pointLocation({x: 0, y: 0})
p1 = @map.pointLocation({x: 1, y: 1})
@distance = {lat:Math.abs(p0.lat - p1.lat),lon:Math.abs(p0.lon - p1.lon)}
@distance
constructor: (@map) ->
@selector = d3.select("#map svg").insert("svg:g")
@map.on "move", => @update()
@map.on "resize", => @update()
# Lat/Lng transform function
transform: (location) =>
d = @map.locationPoint(location)
"translate(" + d.x + "," + d.y + ")"
cluster: (elements, distance) ->
currentElements = elements.slice(0)
pixelDistance = @pixelDistance()
distLat = distance * pixelDistance.lat
distLon = distance * pixelDistance.lon
clustered = []
while currentElements.length > 0
stop = currentElements.shift()
cluster = []
cluster.push stop
i = 0
while i < currentElements.length
if Math.abs(currentElements[i].lat - stop.lat) < distLat and Math.abs(currentElements[i].lon - stop.lon) < distLon
aStop = currentElements.splice i,1
cluster.push aStop[0]
i--
i++
clustered.push cluster
clustered
filter: (clusters, distance) ->
tLeft = @map.pointLocation({x:0-distance,y:0-distance})
bRight = @map.pointLocation({x: $(window).width()+distance, y: $(window).height()+distance})
output = (cluster for cluster in clusters when bRight.lat <= cluster[0].lat and cluster[0].lat <= tLeft.lat and tLeft.lon <= cluster[0].lon and cluster[0].lon <= bRight.lon)
output
class DistanceLayer extends Layer
stops = []
clusters = []
prevLocalClusters = []
update: ->
if @zoomLevel() != @prevZoom or (@stops and @prevNumStops != @stops.length)
@prevNumStops = @stops.length
@prevZoom = @zoomLevel()
# We clustered the stops if they're within 10 pixels, do the same for the stop layer
@clusters = @cluster(@stops,10)
@localClusters = @filter(@clusters,@distanceInPixels())
if (not @prevLocalClusters) or @prevLocalClusters != @localClusters
@prevLocalClusters = @localClusters
# Add new incoming circles
marker = @selector.selectAll("g").data(@localClusters)
marker.enter().append("g")
.append("circle").attr("class", "reach").attr('r', @distanceInPixels())
# Remove old circles
marker.exit().remove()
#Do this to all remaining circles
@updateCircleRadius()
@selector.selectAll("g").attr("transform", (cluster) => @transform cluster[0])
distanceInMeters = (if $.cookie("distance") then $.cookie("distance") else 500) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
distanceInMeters: () ->
if arguments.length == 0
distanceInMeters
else
distanceInMeters = arguments[0]
$.cookie("distance",distanceInMeters, { expires: 30 })
setVariable(1,"Distance",distanceInMeters.toString())
@updateCircleRadius()
this
distanceInPixels: () ->
# Calculates pixel for 1km distance
# http://jan.ucc.nau.edu/~cvm/latlongdist.html with 0N 0W to 0N 0.008983W is 1km
pixelsPerKm = @map.locationPoint({ lat: 0, lon: 0.008983 }).x - @map.locationPoint({ lat: 0, lon: 0 }).x
@distanceInMeters() / 1000 * pixelsPerKm
updateCircleRadius: ->
@selector.selectAll("circle.reach").attr('r', @distanceInPixels())
addStops: (stops) ->
stops.sort((a,b) -> a.lat-b.lat)
@stops = stops
# TODO just have a single g element that is transformed
#marker = @selector.selectAll("g").data(stops).enter().append("g").attr("transform", @transform)
#marker.append("circle").attr("class", "reach").attr('r', @distanceInPixels())
@update()
class BusRouteLayer extends Layer
svgLine = d3.svg.line().x((d) -> d.x).y((d) -> d.y).interpolate("linear")
update: () -> @selector.selectAll("path").attr("d", (d) => @line(d))
addRoutes: (routes,points) ->
# TODO prevent overplotting by intelligently selecting route segments between stops
# map stops by their id
@line = (route) -> svgLine(route.map((routePoint) => @map.locationPoint(points[routePoint])))
@selector.selectAll("g").data(routes).enter().append("path").attr("class", "route").attr("d", (d) => @line(d))
class BusStopLayer extends Layer
clusters = []
stops = []
prevNumStops = 0
prevLocalClusters = []
update: ->
# If the zoom level changed, re cluster the stops
if @zoomLevel() != @prevZoom or (@stops and @prevNumStops != @stops.length)
if @prevZoom and @zoomLevel() != @prevZoom
trackEvent 'Zoom level changed', {'Zoom level':@zoomLevel()}
@prevNumStops = @stops.length
@prevZoom = @zoomLevel()
@clusters = @cluster(@stops,10)
# Filter out any stops not within an acceptable region of the screen. We'll add them as needed
@localClusters = @filter(@clusters,10)
if (not @prevLocalClusters) or @localClusters != @prevLocalClusters
marker = @selector.selectAll("g").data(@localClusters)
# retained markers are updated
marker.select('circle')
.attr('r', (cluster) -> if cluster.length > 1 then busClusterSize else busSize)
.attr("text", @representCluster)
# new markers are added
marker.enter().append("g")
.append("circle")
.attr("class", "stop no-tip")
.attr('r', (cluster) -> if cluster.length > 1 then busClusterSize else busSize)
.attr("text", @representCluster)
# old markers are removed
marker.exit().remove()
# TODO just have a single g element that is transformed
@selector.selectAll("g")
.attr("transform", (cluster) => @transform cluster[0])
representCluster: (cluster) ->
routes = []
for stop in cluster
for route in stop.routes
routes.push route
# This next two lines should remove duplicates
routes = routes.sort()
routes = (route for route, i in routes when i=0 or route != routes[i-1])
# Now we sort by the numeric route value
routes = routes.sort((a,b) -> parseInt(a.match(/^\d+/)[0]) - parseInt(b.match(/^\d+/)[0]))
# Now layout the sorted routes
"<ul>" + (("<li>" + route + "</li>") for route in routes).join("") + "</ul>"
addStops: (stops) ->
stops.sort((a,b) -> a.lat-b.lat)
@stops = stops
if (not Modernizr.touch)
$(".stop").live("mouseover", (event) ->
$(this).qtip(
overwrite: false
content:
attr: 'text'
show:
event: event.type,
ready: true
hide: 'mouseout'
, event)
)
@update()
#$.cookie("viewed-listings") then JSON.parse($.cookie("viewed-listings")
class RentalsLayer extends Layer
viewedIndices: (if $.cookie("viewed-listings") then JSON.parse($.cookie("viewed-listings")) else new Object())
rentalClass: (rental, i) =>
if (@viewedIndices.hasOwnProperty(rental.id))
if (rental.updated_at > @viewedIndices[rental.id])
delete @viewedIndices[rental.id]
"rental"
else "rental rental-viewed"
else "rental"
priceRange = (if $.cookie("priceLow") and $.cookie("priceHigh") then [$.cookie("priceLow"),$.cookie("priceHigh")] else [0,3000]) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
priceRange: () ->
if arguments.length == 0
priceRange
else
priceRange = arguments[0]
$.cookie("priceLow",priceRange[0], { expires: 30 })
$.cookie("priceHigh",priceRange[1], { expires: 30 })
setVariable(2,"Price Low",priceRange[0].toString())
setVariable(3,"Price High",priceRange[1].toString())
@updateVisibility()
this
roomsRange = (if $.cookie("roomsLow") and $.cookie("roomsHigh") then [$.cookie("roomsLow"),$.cookie("roomsHigh")] else [0,5]) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
roomsRange: () ->
if arguments.length == 0
roomsRange
else
roomsRange = arguments[0]
$.cookie("roomsLow",roomsRange[0], { expires: 30 })
$.cookie("roomsHigh",roomsRange[1], { expires: 30 })
setVariable(4,"Min Rooms", roomsRange[0].toString())
setVariable(5,"Max Rooms", roomsRange[1].toString())
@updateVisibility()
this
allowShared = (if $.cookie("showShared") then $.cookie("showShared") == "true" else false) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
allowShared: () ->
if arguments.length == 0
allowShared
else
allowShared = arguments[0]
$.cookie("showShared",allowShared, { expires: 30 })
@updateVisibility()
this
isNotSharedOrAllowed: (rental) ->
match = /shared|room/i.test(rental.type)
if match
allowShared
else
true
updateVisibility: ->
@selector.selectAll("rect").attr('visibility', (rentals) =>
suites = (suite for suite in rentals.availabilities when suite && priceRange[0] <= suite.price <= priceRange[1] && roomsRange[0] <= suite.bedrooms <= roomsRange[1] )
if suites.length > 0
if @isNotSharedOrAllowed(rentals) then 'visible' else 'hidden'
else
'hidden'
)
update: ->
@selector.selectAll("g").attr("transform", @transform)
$(".rental").qtip('reposition')
convertDateToUTC: (date) ->
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())
setListingDisplay: (rental) ->
listings = (("<li>" + (if suite.bedrooms or suite.bedrooms == 0 then suite.bedrooms else "unknown") + " bedroom: " + (if suite.price > 0 then "$" + suite.price else "Unknown") + "</li>" ) for suite in rental.availabilities)
output = ""
if rental.image_url
output = output + "<a href=\"" + rental.url + "\" target=\"_blank\" onClick=\"recordOutboundLink(this, 'Outbound Links', {\"source\":\"" + rental.source + "\", \"url\":\"" + rental.url + "\", \"price\":\"" + rental.url + "\", \"bedrooms\":\"" + rental.bedrooms + "\"})\"><img class=\"rental-img\" src=\""+ rental.image_url + "\"></a>"
output = output + rental.source + ", " + rental.type + " <br/><ul>" + listings.join("") + "</ul><br /><a href=\"" + rental.url + "\" target=\"_blank\" onClick=\"recordOutboundLink(this, 'Outbound Links', {'source':'" + rental.source + "', 'url':'" + rental.url + "'});return false;\">View Original Listing</a>"
output
addRentals: (rentals) ->
# TODO just have a single g element that is transformed
marker = @selector.selectAll("g").data(rentals).enter().append("g").attr("transform", @transform)
marker.append("rect")
.attr("class", @rentalClass)
.attr("x", -1 * rentalSize /2)
.attr("y", -1 * rentalSize /2)
.attr('height', rentalSize)
.attr('width', rentalSize)
.attr("text", (rental) =>
@setListingDisplay(rental)
)
@updateVisibility()
marker.on("click", (rental, i) =>
@viewedIndices[rental.id] = new Date()*1
$.cookie("viewed-listings", JSON.stringify(@viewedIndices), { expires: 30 })
@selector.selectAll("g").select("rect").attr("class", @rentalClass)
recordEvent('Rental View',rental.source,rental.url)
trackEvent('Rental View',
"Rental Source":rental.source
"url":rental.url
"price":rental.price
"bedrooms":rental.bedrooms
"min price":priceRange[0]
"max price":priceRange[1]
"min rooms":roomsRange[0]
"max rooms":roomsRange[1]
"shared allowed":allowShared
"zoom level":@zoomLevel()
)
)
$(".rental").qtip(
content:
attr: 'text'
title:
text: 'Rental Details'
button: true
show: 'mousedown'
hide: false
position:
my: 'bottom center'
at: 'top center'
style: 'ui-tooltip-tipped'
)
# create layers - order of layers important because of SVG drawing
distanceLayer = new DistanceLayer map
busRouteLayer = new BusRouteLayer map
busStopLayer = new BusStopLayer map
rentalLayer = new RentalsLayer map
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupDistanceSlider = () ->
# TODO support multiple event listers
sliderChanged = (value) ->
$( "#slider-distance > .value" ).html( value + "m" )
distanceLayer.distanceInMeters(value)
$("#slider-distance-element").slider(
range: "min"
value: distanceLayer.distanceInMeters()
step: 10
min: 0
max: 2500
slide: (event, ui) -> sliderChanged(ui.value)
stop: (event, ui) -> trackEvent 'distance changed'
distance: distanceLayer.distanceInMeters()
)
sliderChanged($("#slider-distance-element").slider("value"))
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupPriceSlider = () ->
# TODO support multiple event listers
sliderChanged = (values) ->
$( "#slider-price > .value" ).html( "$" + values[0] + " - " + values[1] )
rentalLayer.priceRange(values)
$("#slider-price-element").slider(
range: true
values: rentalLayer.priceRange()
step: 50
min: 0
max: 3000
slide: (event, ui) -> sliderChanged(ui.values)
stop: (event, ui) -> trackEvent 'price changed'
'low price': rentalLayer.priceRange()[0]
'high price': rentalLayer.priceRange()[1]
)
sliderChanged($("#slider-price-element").slider("values"))
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupRoomsSlider = () ->
# TODO support multiple event listers
sliderChanged = (values) ->
$( "#slider-rooms > .value" ).html( values[0] + " - " + values[1] + " rooms" )
rentalLayer.roomsRange(values)
$("#slider-rooms-element").slider(
range: true
values: rentalLayer.roomsRange()
min: 0
max: 5
slide: (event, ui) -> sliderChanged(ui.values)
stop: (event, ui) -> trackEvent '# rooms changed'
'min rooms': rentalLayer.roomsRange()[0]
'max rooms': rentalLayer.roomsRange()[1]
)
sliderChanged($("#slider-rooms-element").slider("values"))
setupSharedCheckbox = () ->
$("#show-shared").attr 'checked', rentalLayer.allowShared()
$("#show-shared").click ->
rentalLayer.allowShared(this.checked)
if this.checked
trackEvent 'shared selected'
else
trackEvent 'private selected'
loadBusRoutes = () ->
d3.json 'data/uvic_transit.json', (json) ->
points = {}
json.points.forEach((point) ->
points[point.id] = point
)
injectLocations json.stops,points
distanceLayer.addStops json.stops
busRouteLayer.addRoutes json.routes,points
busStopLayer.addStops json.stops
loadRentals = () ->
d3.json 'data/rentals.json', (json) ->
rentalLayer.addRentals json
do ->
setupDistanceSlider()
setupPriceSlider()
setupRoomsSlider()
setupSharedCheckbox()
loadBusRoutes()
loadRentals()
trackEvent('RentalMap loaded')
$(window).unload( () ->
trackEvent('RentalMap closed')
)
$(".message .close").on("click", () ->
$(".message").hide()
$.cookie("survey-closed",true, { expires: 5 })
trackEvent('Survey Closed')
)
$(window).on("resize", () ->
if $(window).width() < 600
$(".message").hide()
else
$(".message").show()
)
addthis.addEventListener('addthis.menu.share', (evt) ->
trackEvent 'AddThis', evt.data
);
# Set to track outbound links from the site
$("a[rel*='external']").click(->
link = $(this)
recordEvent('External Link',link.text(),link.attr('href'))
trackEvent('External Link',{"Link Text":link.text(),"url":link.attr('href')})
)
# Hide the default loading dialog, in case it hasn't been covered yet
$("#loading").hide()
else
$('#unsupportedBrowser').show()
$('.regular').hide()
recordEvent('Unsupported Browser','No SVG' ,navigator.userAgent)
trackEvent('Unsupported Browser',{"Browser":navigator.userAgent})
| true | rentalSize = if Modernizr.touch then 12 else 8
busSize = 3.5
busClusterSize = 5
injectLocations = (stops,points) ->
stops.forEach((stop) ->
location = points[stop.p]
stop.lat = location.lat
stop.lon = location.lon
)
trackEvent = (name, values, callback = null) ->
mixpanel.track name, values
if callback
callback()
recordOutboundLink = (link, name, values) ->
recordEvent name, values.source, values.url
trackEvent name, values, () -> window.open(link.href,"_blank")
window.recordOutboundLink = recordOutboundLink
recordEvent = (category, action, label) ->
_gat._getTrackerByName()._trackEvent category, action, label
window.recordEvent = recordEvent
setVariable = (index, name, value) ->
# This custom var is set to slot #1. Required parameter.
# The name acts as a kind of category for the user activity. Required parameter.
# This value of the custom variable. Required parameter.
_gaq.push ["_setCustomVar", index, name, value, 2] # Sets the scope to session-level. Optional parameter.
window.setVariable = setVariable
if Modernizr.svg and Modernizr.inlinesvg
if $(window).height() < 500 or $(window).width() < 500
$(".desktop").hide()
if !($(window).width() < 600 or $.cookie("survey-closed") or $.cookie("survey-visited"))
$(".message").show()
if Modernizr.touch
$(".github").hide()
$(".header").show()
headerToggle = (element) ->
if $("#standard-options").is(":visible")
$("#standard-options").hide "slow"
$(element).button "option", "icons",
primary: "ui-icon-triangle-1-s"
trackEvent 'hid options'
else
$("#standard-options").show "slow"
$(element).button "option", "icons",
primary: "ui-icon-triangle-1-n"
trackEvent 'show options'
$(".header-expand").button(
icons:
primary: "ui-icon ui-icon-triangle-1-n"
text: false
).click ->
headerToggle this
toggleAdditional = ->
if $("#additional-notices").is(":visible")
$("#additional-notices").hide "slow"
$("a#additional-expand").text "additional notices"
trackEvent 'hid notices'
else
$("#additional-notices").show "slow"
$("a#additional-expand").text "less notices"
trackEvent 'show notices'
$("a#additional-expand").click ->
toggleAdditional()
# Code based on Polymaps example from MPI:NAME:<NAME>END_PI BPI:NAME:<NAME>END_PI http://bl.ocks.org/899670
polymaps = org.polymaps
map = polymaps.map().container(d3.select("#map").append("svg:svg").attr("width", "100%").attr("height", "100%").node())
.zoom(13)
.center({lat: 48.455164, lon: -123.351059})# Victoria BC west of Cedar Hill Golf Course
.add(polymaps.drag())
.add(polymaps.wheel().smooth(false))
.add(polymaps.dblclick())
.add(polymaps.arrow())
.add(polymaps.touch())
# Stamen toner tiles http://maps.stamen.com
map.add(polymaps.image().url(polymaps.url("http://tile.stamen.com/toner/{Z}/{X}/{Y}.png")))
# Classes
class Layer
zoomLevel: -> @map.zoom()
@prevZoom = 13
@distance = 0
pixelDistance: ->
p0 = @map.pointLocation({x: 0, y: 0})
p1 = @map.pointLocation({x: 1, y: 1})
@distance = {lat:Math.abs(p0.lat - p1.lat),lon:Math.abs(p0.lon - p1.lon)}
@distance
constructor: (@map) ->
@selector = d3.select("#map svg").insert("svg:g")
@map.on "move", => @update()
@map.on "resize", => @update()
# Lat/Lng transform function
transform: (location) =>
d = @map.locationPoint(location)
"translate(" + d.x + "," + d.y + ")"
cluster: (elements, distance) ->
currentElements = elements.slice(0)
pixelDistance = @pixelDistance()
distLat = distance * pixelDistance.lat
distLon = distance * pixelDistance.lon
clustered = []
while currentElements.length > 0
stop = currentElements.shift()
cluster = []
cluster.push stop
i = 0
while i < currentElements.length
if Math.abs(currentElements[i].lat - stop.lat) < distLat and Math.abs(currentElements[i].lon - stop.lon) < distLon
aStop = currentElements.splice i,1
cluster.push aStop[0]
i--
i++
clustered.push cluster
clustered
filter: (clusters, distance) ->
tLeft = @map.pointLocation({x:0-distance,y:0-distance})
bRight = @map.pointLocation({x: $(window).width()+distance, y: $(window).height()+distance})
output = (cluster for cluster in clusters when bRight.lat <= cluster[0].lat and cluster[0].lat <= tLeft.lat and tLeft.lon <= cluster[0].lon and cluster[0].lon <= bRight.lon)
output
class DistanceLayer extends Layer
stops = []
clusters = []
prevLocalClusters = []
update: ->
if @zoomLevel() != @prevZoom or (@stops and @prevNumStops != @stops.length)
@prevNumStops = @stops.length
@prevZoom = @zoomLevel()
# We clustered the stops if they're within 10 pixels, do the same for the stop layer
@clusters = @cluster(@stops,10)
@localClusters = @filter(@clusters,@distanceInPixels())
if (not @prevLocalClusters) or @prevLocalClusters != @localClusters
@prevLocalClusters = @localClusters
# Add new incoming circles
marker = @selector.selectAll("g").data(@localClusters)
marker.enter().append("g")
.append("circle").attr("class", "reach").attr('r', @distanceInPixels())
# Remove old circles
marker.exit().remove()
#Do this to all remaining circles
@updateCircleRadius()
@selector.selectAll("g").attr("transform", (cluster) => @transform cluster[0])
distanceInMeters = (if $.cookie("distance") then $.cookie("distance") else 500) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
distanceInMeters: () ->
if arguments.length == 0
distanceInMeters
else
distanceInMeters = arguments[0]
$.cookie("distance",distanceInMeters, { expires: 30 })
setVariable(1,"Distance",distanceInMeters.toString())
@updateCircleRadius()
this
distanceInPixels: () ->
# Calculates pixel for 1km distance
# http://jan.ucc.nau.edu/~cvm/latlongdist.html with 0N 0W to 0N 0.008983W is 1km
pixelsPerKm = @map.locationPoint({ lat: 0, lon: 0.008983 }).x - @map.locationPoint({ lat: 0, lon: 0 }).x
@distanceInMeters() / 1000 * pixelsPerKm
updateCircleRadius: ->
@selector.selectAll("circle.reach").attr('r', @distanceInPixels())
addStops: (stops) ->
stops.sort((a,b) -> a.lat-b.lat)
@stops = stops
# TODO just have a single g element that is transformed
#marker = @selector.selectAll("g").data(stops).enter().append("g").attr("transform", @transform)
#marker.append("circle").attr("class", "reach").attr('r', @distanceInPixels())
@update()
class BusRouteLayer extends Layer
svgLine = d3.svg.line().x((d) -> d.x).y((d) -> d.y).interpolate("linear")
update: () -> @selector.selectAll("path").attr("d", (d) => @line(d))
addRoutes: (routes,points) ->
# TODO prevent overplotting by intelligently selecting route segments between stops
# map stops by their id
@line = (route) -> svgLine(route.map((routePoint) => @map.locationPoint(points[routePoint])))
@selector.selectAll("g").data(routes).enter().append("path").attr("class", "route").attr("d", (d) => @line(d))
class BusStopLayer extends Layer
clusters = []
stops = []
prevNumStops = 0
prevLocalClusters = []
update: ->
# If the zoom level changed, re cluster the stops
if @zoomLevel() != @prevZoom or (@stops and @prevNumStops != @stops.length)
if @prevZoom and @zoomLevel() != @prevZoom
trackEvent 'Zoom level changed', {'Zoom level':@zoomLevel()}
@prevNumStops = @stops.length
@prevZoom = @zoomLevel()
@clusters = @cluster(@stops,10)
# Filter out any stops not within an acceptable region of the screen. We'll add them as needed
@localClusters = @filter(@clusters,10)
if (not @prevLocalClusters) or @localClusters != @prevLocalClusters
marker = @selector.selectAll("g").data(@localClusters)
# retained markers are updated
marker.select('circle')
.attr('r', (cluster) -> if cluster.length > 1 then busClusterSize else busSize)
.attr("text", @representCluster)
# new markers are added
marker.enter().append("g")
.append("circle")
.attr("class", "stop no-tip")
.attr('r', (cluster) -> if cluster.length > 1 then busClusterSize else busSize)
.attr("text", @representCluster)
# old markers are removed
marker.exit().remove()
# TODO just have a single g element that is transformed
@selector.selectAll("g")
.attr("transform", (cluster) => @transform cluster[0])
representCluster: (cluster) ->
routes = []
for stop in cluster
for route in stop.routes
routes.push route
# This next two lines should remove duplicates
routes = routes.sort()
routes = (route for route, i in routes when i=0 or route != routes[i-1])
# Now we sort by the numeric route value
routes = routes.sort((a,b) -> parseInt(a.match(/^\d+/)[0]) - parseInt(b.match(/^\d+/)[0]))
# Now layout the sorted routes
"<ul>" + (("<li>" + route + "</li>") for route in routes).join("") + "</ul>"
addStops: (stops) ->
stops.sort((a,b) -> a.lat-b.lat)
@stops = stops
if (not Modernizr.touch)
$(".stop").live("mouseover", (event) ->
$(this).qtip(
overwrite: false
content:
attr: 'text'
show:
event: event.type,
ready: true
hide: 'mouseout'
, event)
)
@update()
#$.cookie("viewed-listings") then JSON.parse($.cookie("viewed-listings")
class RentalsLayer extends Layer
viewedIndices: (if $.cookie("viewed-listings") then JSON.parse($.cookie("viewed-listings")) else new Object())
rentalClass: (rental, i) =>
if (@viewedIndices.hasOwnProperty(rental.id))
if (rental.updated_at > @viewedIndices[rental.id])
delete @viewedIndices[rental.id]
"rental"
else "rental rental-viewed"
else "rental"
priceRange = (if $.cookie("priceLow") and $.cookie("priceHigh") then [$.cookie("priceLow"),$.cookie("priceHigh")] else [0,3000]) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
priceRange: () ->
if arguments.length == 0
priceRange
else
priceRange = arguments[0]
$.cookie("priceLow",priceRange[0], { expires: 30 })
$.cookie("priceHigh",priceRange[1], { expires: 30 })
setVariable(2,"Price Low",priceRange[0].toString())
setVariable(3,"Price High",priceRange[1].toString())
@updateVisibility()
this
roomsRange = (if $.cookie("roomsLow") and $.cookie("roomsHigh") then [$.cookie("roomsLow"),$.cookie("roomsHigh")] else [0,5]) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
roomsRange: () ->
if arguments.length == 0
roomsRange
else
roomsRange = arguments[0]
$.cookie("roomsLow",roomsRange[0], { expires: 30 })
$.cookie("roomsHigh",roomsRange[1], { expires: 30 })
setVariable(4,"Min Rooms", roomsRange[0].toString())
setVariable(5,"Max Rooms", roomsRange[1].toString())
@updateVisibility()
this
allowShared = (if $.cookie("showShared") then $.cookie("showShared") == "true" else false) # (private) assume you can walk 500m in 6min, this seems to be a good default distance
allowShared: () ->
if arguments.length == 0
allowShared
else
allowShared = arguments[0]
$.cookie("showShared",allowShared, { expires: 30 })
@updateVisibility()
this
isNotSharedOrAllowed: (rental) ->
match = /shared|room/i.test(rental.type)
if match
allowShared
else
true
updateVisibility: ->
@selector.selectAll("rect").attr('visibility', (rentals) =>
suites = (suite for suite in rentals.availabilities when suite && priceRange[0] <= suite.price <= priceRange[1] && roomsRange[0] <= suite.bedrooms <= roomsRange[1] )
if suites.length > 0
if @isNotSharedOrAllowed(rentals) then 'visible' else 'hidden'
else
'hidden'
)
update: ->
@selector.selectAll("g").attr("transform", @transform)
$(".rental").qtip('reposition')
convertDateToUTC: (date) ->
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds())
setListingDisplay: (rental) ->
listings = (("<li>" + (if suite.bedrooms or suite.bedrooms == 0 then suite.bedrooms else "unknown") + " bedroom: " + (if suite.price > 0 then "$" + suite.price else "Unknown") + "</li>" ) for suite in rental.availabilities)
output = ""
if rental.image_url
output = output + "<a href=\"" + rental.url + "\" target=\"_blank\" onClick=\"recordOutboundLink(this, 'Outbound Links', {\"source\":\"" + rental.source + "\", \"url\":\"" + rental.url + "\", \"price\":\"" + rental.url + "\", \"bedrooms\":\"" + rental.bedrooms + "\"})\"><img class=\"rental-img\" src=\""+ rental.image_url + "\"></a>"
output = output + rental.source + ", " + rental.type + " <br/><ul>" + listings.join("") + "</ul><br /><a href=\"" + rental.url + "\" target=\"_blank\" onClick=\"recordOutboundLink(this, 'Outbound Links', {'source':'" + rental.source + "', 'url':'" + rental.url + "'});return false;\">View Original Listing</a>"
output
addRentals: (rentals) ->
# TODO just have a single g element that is transformed
marker = @selector.selectAll("g").data(rentals).enter().append("g").attr("transform", @transform)
marker.append("rect")
.attr("class", @rentalClass)
.attr("x", -1 * rentalSize /2)
.attr("y", -1 * rentalSize /2)
.attr('height', rentalSize)
.attr('width', rentalSize)
.attr("text", (rental) =>
@setListingDisplay(rental)
)
@updateVisibility()
marker.on("click", (rental, i) =>
@viewedIndices[rental.id] = new Date()*1
$.cookie("viewed-listings", JSON.stringify(@viewedIndices), { expires: 30 })
@selector.selectAll("g").select("rect").attr("class", @rentalClass)
recordEvent('Rental View',rental.source,rental.url)
trackEvent('Rental View',
"Rental Source":rental.source
"url":rental.url
"price":rental.price
"bedrooms":rental.bedrooms
"min price":priceRange[0]
"max price":priceRange[1]
"min rooms":roomsRange[0]
"max rooms":roomsRange[1]
"shared allowed":allowShared
"zoom level":@zoomLevel()
)
)
$(".rental").qtip(
content:
attr: 'text'
title:
text: 'Rental Details'
button: true
show: 'mousedown'
hide: false
position:
my: 'bottom center'
at: 'top center'
style: 'ui-tooltip-tipped'
)
# create layers - order of layers important because of SVG drawing
distanceLayer = new DistanceLayer map
busRouteLayer = new BusRouteLayer map
busStopLayer = new BusStopLayer map
rentalLayer = new RentalsLayer map
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupDistanceSlider = () ->
# TODO support multiple event listers
sliderChanged = (value) ->
$( "#slider-distance > .value" ).html( value + "m" )
distanceLayer.distanceInMeters(value)
$("#slider-distance-element").slider(
range: "min"
value: distanceLayer.distanceInMeters()
step: 10
min: 0
max: 2500
slide: (event, ui) -> sliderChanged(ui.value)
stop: (event, ui) -> trackEvent 'distance changed'
distance: distanceLayer.distanceInMeters()
)
sliderChanged($("#slider-distance-element").slider("value"))
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupPriceSlider = () ->
# TODO support multiple event listers
sliderChanged = (values) ->
$( "#slider-price > .value" ).html( "$" + values[0] + " - " + values[1] )
rentalLayer.priceRange(values)
$("#slider-price-element").slider(
range: true
values: rentalLayer.priceRange()
step: 50
min: 0
max: 3000
slide: (event, ui) -> sliderChanged(ui.values)
stop: (event, ui) -> trackEvent 'price changed'
'low price': rentalLayer.priceRange()[0]
'high price': rentalLayer.priceRange()[1]
)
sliderChanged($("#slider-price-element").slider("values"))
# TODO decouple using events, e.g. from backbone --> route event, location, zoom on url
setupRoomsSlider = () ->
# TODO support multiple event listers
sliderChanged = (values) ->
$( "#slider-rooms > .value" ).html( values[0] + " - " + values[1] + " rooms" )
rentalLayer.roomsRange(values)
$("#slider-rooms-element").slider(
range: true
values: rentalLayer.roomsRange()
min: 0
max: 5
slide: (event, ui) -> sliderChanged(ui.values)
stop: (event, ui) -> trackEvent '# rooms changed'
'min rooms': rentalLayer.roomsRange()[0]
'max rooms': rentalLayer.roomsRange()[1]
)
sliderChanged($("#slider-rooms-element").slider("values"))
setupSharedCheckbox = () ->
$("#show-shared").attr 'checked', rentalLayer.allowShared()
$("#show-shared").click ->
rentalLayer.allowShared(this.checked)
if this.checked
trackEvent 'shared selected'
else
trackEvent 'private selected'
loadBusRoutes = () ->
d3.json 'data/uvic_transit.json', (json) ->
points = {}
json.points.forEach((point) ->
points[point.id] = point
)
injectLocations json.stops,points
distanceLayer.addStops json.stops
busRouteLayer.addRoutes json.routes,points
busStopLayer.addStops json.stops
loadRentals = () ->
d3.json 'data/rentals.json', (json) ->
rentalLayer.addRentals json
do ->
setupDistanceSlider()
setupPriceSlider()
setupRoomsSlider()
setupSharedCheckbox()
loadBusRoutes()
loadRentals()
trackEvent('RentalMap loaded')
$(window).unload( () ->
trackEvent('RentalMap closed')
)
$(".message .close").on("click", () ->
$(".message").hide()
$.cookie("survey-closed",true, { expires: 5 })
trackEvent('Survey Closed')
)
$(window).on("resize", () ->
if $(window).width() < 600
$(".message").hide()
else
$(".message").show()
)
addthis.addEventListener('addthis.menu.share', (evt) ->
trackEvent 'AddThis', evt.data
);
# Set to track outbound links from the site
$("a[rel*='external']").click(->
link = $(this)
recordEvent('External Link',link.text(),link.attr('href'))
trackEvent('External Link',{"Link Text":link.text(),"url":link.attr('href')})
)
# Hide the default loading dialog, in case it hasn't been covered yet
$("#loading").hide()
else
$('#unsupportedBrowser').show()
$('.regular').hide()
recordEvent('Unsupported Browser','No SVG' ,navigator.userAgent)
trackEvent('Unsupported Browser',{"Browser":navigator.userAgent})
|
[
{
"context": "###*\n * Cookie parser for GridFW\n * @copyright khalid RAFIK 2018\n###\n'use strict'\n\ncookie = require 'cookie'\n",
"end": 59,
"score": 0.9778971672058105,
"start": 47,
"tag": "NAME",
"value": "khalid RAFIK"
}
] | assets/index.coffee | gridfw/gridfw-cookie | 0 | ###*
* Cookie parser for GridFW
* @copyright khalid RAFIK 2018
###
'use strict'
cookie = require 'cookie'
CryptoJS = require('crypto-js')
AESCrypto = CryptoJS.AES
# utils
_defineProperty= Object.defineProperty
###*
* Clear cookie
* @example
* ctx.clearCookie('name', options)
###
_clearCookie= (name, options)->
options ?= Object.create null
options.expires ?= new Date 1
options.path ?= '/'
@cookie name, '', options
class Cookie
constructor: (@app)->
@enabled = on # the plugin is enabled
###*
* Reload parser
###
reload: (settings)->
settings ?= Object.create null
#=include _set-cookie.coffee
#=include _parse-cookies.coffee
# secret
_secret = settings.secret
throw new Error "settings.secret expected string or null" if _secret and typeof _secret isnt 'string'
# properties
@fxes=
Request: Object.create null,
cookies:
get: parseCookie
configurable: on
signedCookies:
get: parseCookie
configurable: on
Context: Object.create null,
# get cookies
cookies:
get: ->
cookies= @req.cookies
_defineProperty this, 'cookies', value: cookies
cookies
configurable: on
# set cookie
cookie: value: setCookie
setCookie: value: setCookie
clearCookie: value: _clearCookie
# enable
@enable()
return
###*
* destroy
###
destroy: ->
@app.removeProperties 'Cookie', @fxes
return
###*
* Disable, enable
###
disable: -> @destroy
enable: ->
# Context plugins
@app.addProperties 'Cookie', @fxes
return
module.exports = Cookie | 186056 | ###*
* Cookie parser for GridFW
* @copyright <NAME> 2018
###
'use strict'
cookie = require 'cookie'
CryptoJS = require('crypto-js')
AESCrypto = CryptoJS.AES
# utils
_defineProperty= Object.defineProperty
###*
* Clear cookie
* @example
* ctx.clearCookie('name', options)
###
_clearCookie= (name, options)->
options ?= Object.create null
options.expires ?= new Date 1
options.path ?= '/'
@cookie name, '', options
class Cookie
constructor: (@app)->
@enabled = on # the plugin is enabled
###*
* Reload parser
###
reload: (settings)->
settings ?= Object.create null
#=include _set-cookie.coffee
#=include _parse-cookies.coffee
# secret
_secret = settings.secret
throw new Error "settings.secret expected string or null" if _secret and typeof _secret isnt 'string'
# properties
@fxes=
Request: Object.create null,
cookies:
get: parseCookie
configurable: on
signedCookies:
get: parseCookie
configurable: on
Context: Object.create null,
# get cookies
cookies:
get: ->
cookies= @req.cookies
_defineProperty this, 'cookies', value: cookies
cookies
configurable: on
# set cookie
cookie: value: setCookie
setCookie: value: setCookie
clearCookie: value: _clearCookie
# enable
@enable()
return
###*
* destroy
###
destroy: ->
@app.removeProperties 'Cookie', @fxes
return
###*
* Disable, enable
###
disable: -> @destroy
enable: ->
# Context plugins
@app.addProperties 'Cookie', @fxes
return
module.exports = Cookie | true | ###*
* Cookie parser for GridFW
* @copyright PI:NAME:<NAME>END_PI 2018
###
'use strict'
cookie = require 'cookie'
CryptoJS = require('crypto-js')
AESCrypto = CryptoJS.AES
# utils
_defineProperty= Object.defineProperty
###*
* Clear cookie
* @example
* ctx.clearCookie('name', options)
###
_clearCookie= (name, options)->
options ?= Object.create null
options.expires ?= new Date 1
options.path ?= '/'
@cookie name, '', options
class Cookie
constructor: (@app)->
@enabled = on # the plugin is enabled
###*
* Reload parser
###
reload: (settings)->
settings ?= Object.create null
#=include _set-cookie.coffee
#=include _parse-cookies.coffee
# secret
_secret = settings.secret
throw new Error "settings.secret expected string or null" if _secret and typeof _secret isnt 'string'
# properties
@fxes=
Request: Object.create null,
cookies:
get: parseCookie
configurable: on
signedCookies:
get: parseCookie
configurable: on
Context: Object.create null,
# get cookies
cookies:
get: ->
cookies= @req.cookies
_defineProperty this, 'cookies', value: cookies
cookies
configurable: on
# set cookie
cookie: value: setCookie
setCookie: value: setCookie
clearCookie: value: _clearCookie
# enable
@enable()
return
###*
* destroy
###
destroy: ->
@app.removeProperties 'Cookie', @fxes
return
###*
* Disable, enable
###
disable: -> @destroy
enable: ->
# Context plugins
@app.addProperties 'Cookie', @fxes
return
module.exports = Cookie |
[
{
"context": "s.tags\n @author = @matter.attributes.author ? 'Adam Stokes'\n @html = markdown(@matter.body)\n hasCategory",
"end": 642,
"score": 0.9998790621757507,
"start": 631,
"tag": "NAME",
"value": "Adam Stokes"
}
] | post.coffee | battlemidget/bummyjab | 0 | fs = require('graceful-fs')
fm = require('fastmatter')
moment = require('moment')
markdown = require('marked')
hljs = require('highlight.js')
utils = require('./utils')
# markdown.setOptions highlight: (code) ->
# hljs.highlightAuto(code).value
class Post
constructor: (post) ->
@post = post
body = fs.readFileSync @post, 'utf-8'
@matter = fm(body.toString())
@title = @matter.attributes.title ? "No title defined."
@permalink = utils.stringify(@post)
@date = moment(@matter.attributes.date).format('YYYY-MM-DDTHH:mm:ss')
@tags = @matter.attributes.tags
@author = @matter.attributes.author ? 'Adam Stokes'
@html = markdown(@matter.body)
hasCategory: (cat) ->
if cat in @tags
return true
module.exports = Post
| 66417 | fs = require('graceful-fs')
fm = require('fastmatter')
moment = require('moment')
markdown = require('marked')
hljs = require('highlight.js')
utils = require('./utils')
# markdown.setOptions highlight: (code) ->
# hljs.highlightAuto(code).value
class Post
constructor: (post) ->
@post = post
body = fs.readFileSync @post, 'utf-8'
@matter = fm(body.toString())
@title = @matter.attributes.title ? "No title defined."
@permalink = utils.stringify(@post)
@date = moment(@matter.attributes.date).format('YYYY-MM-DDTHH:mm:ss')
@tags = @matter.attributes.tags
@author = @matter.attributes.author ? '<NAME>'
@html = markdown(@matter.body)
hasCategory: (cat) ->
if cat in @tags
return true
module.exports = Post
| true | fs = require('graceful-fs')
fm = require('fastmatter')
moment = require('moment')
markdown = require('marked')
hljs = require('highlight.js')
utils = require('./utils')
# markdown.setOptions highlight: (code) ->
# hljs.highlightAuto(code).value
class Post
constructor: (post) ->
@post = post
body = fs.readFileSync @post, 'utf-8'
@matter = fm(body.toString())
@title = @matter.attributes.title ? "No title defined."
@permalink = utils.stringify(@post)
@date = moment(@matter.attributes.date).format('YYYY-MM-DDTHH:mm:ss')
@tags = @matter.attributes.tags
@author = @matter.attributes.author ? 'PI:NAME:<NAME>END_PI'
@html = markdown(@matter.body)
hasCategory: (cat) ->
if cat in @tags
return true
module.exports = Post
|
[
{
"context": "me\n Accounts.createUser\n username: username,\n email: email,\n password: pass",
"end": 546,
"score": 0.9983401298522949,
"start": 538,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rname,\n email: email,\n password: password,\n profile: AccountsEntry.settings.defaul",
"end": 600,
"score": 0.9993588924407959,
"start": 592,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ateUser\n email: email\n password: password\n profile: AccountsEntry.settings.default",
"end": 755,
"score": 0.999380350112915,
"start": 747,
"tag": "PASSWORD",
"value": "password"
}
] | server/entry.coffee | hiddenswitch/accounts-entry | 0 | Meteor.startup ->
Accounts.urls.resetPassword = (token) ->
Meteor.absoluteUrl('reset-password/' + token)
AccountsEntry =
settings: {}
config: (appConfig) ->
@settings = _.extend(@settings, appConfig)
@AccountsEntry = AccountsEntry
Meteor.methods
entryValidateSignupCode: (signupCode) ->
not AccountsEntry.settings.signupCode or signupCode is AccountsEntry.settings.signupCode
accountsCreateUser: (username, email, password) ->
if username
Accounts.createUser
username: username,
email: email,
password: password,
profile: AccountsEntry.settings.defaultProfile || {}
else
Accounts.createUser
email: email
password: password
profile: AccountsEntry.settings.defaultProfile || {}
| 181155 | Meteor.startup ->
Accounts.urls.resetPassword = (token) ->
Meteor.absoluteUrl('reset-password/' + token)
AccountsEntry =
settings: {}
config: (appConfig) ->
@settings = _.extend(@settings, appConfig)
@AccountsEntry = AccountsEntry
Meteor.methods
entryValidateSignupCode: (signupCode) ->
not AccountsEntry.settings.signupCode or signupCode is AccountsEntry.settings.signupCode
accountsCreateUser: (username, email, password) ->
if username
Accounts.createUser
username: username,
email: email,
password: <PASSWORD>,
profile: AccountsEntry.settings.defaultProfile || {}
else
Accounts.createUser
email: email
password: <PASSWORD>
profile: AccountsEntry.settings.defaultProfile || {}
| true | Meteor.startup ->
Accounts.urls.resetPassword = (token) ->
Meteor.absoluteUrl('reset-password/' + token)
AccountsEntry =
settings: {}
config: (appConfig) ->
@settings = _.extend(@settings, appConfig)
@AccountsEntry = AccountsEntry
Meteor.methods
entryValidateSignupCode: (signupCode) ->
not AccountsEntry.settings.signupCode or signupCode is AccountsEntry.settings.signupCode
accountsCreateUser: (username, email, password) ->
if username
Accounts.createUser
username: username,
email: email,
password: PI:PASSWORD:<PASSWORD>END_PI,
profile: AccountsEntry.settings.defaultProfile || {}
else
Accounts.createUser
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
profile: AccountsEntry.settings.defaultProfile || {}
|
[
{
"context": "'\n\t\t\t\t\torigin: 'null'\n\t\t\t\t\t'sec-websocket-key1': '38b01/4z3y;\\\\S 56H 5^ 9Qz l'\n\t\t\t\t\t'sec-websocket-key2': '3Y05g9S:HvN374 39o3-",
"end": 426,
"score": 0.9996227622032166,
"start": 396,
"tag": "KEY",
"value": "38b01/4z3y;\\\\S 56H 5^ 9Qz l"
},
{
"context": ";\\\\S 56H 5^ 9Qz l'\n\t\t\t\t\t'sec-websocket-key2': '3Y05g9S:HvN374 39o3-;'\n\t\t\tclose: () ->\n\t\t\taddListener: () ->\n\t\t\thandshak",
"end": 478,
"score": 0.9996986389160156,
"start": 456,
"tag": "KEY",
"value": "3Y05g9S:HvN374 39o3-;'"
}
] | spec/clients_spec.coffee | petrjanda/platformjs | 1 | require './spec_helper'
Clients = require 'clients'
Client = require 'client'
describe "Clients", ->
beforeEach ->
@clients = new Clients()
# Mock the client
@client =
sid: 123
state: Client.STATUS_READY
request:
method: 'GET'
headers:
upgrade: 'WebSocket'
connection: 'Upgrade'
host: 'localhost:8000'
origin: 'null'
'sec-websocket-key1': '38b01/4z3y;\\S 56H 5^ 9Qz l'
'sec-websocket-key2': '3Y05g9S:HvN374 39o3-;'
close: () ->
addListener: () ->
handshake: () ->
send: () ->
describe "client count", ->
it "should be 1", ->
@clients.connect(@client)
expect(@clients.count).toBe(1)
it "should be 0", ->
@clients.connect(@client)
@count = @clients.count
@clients.disconnect(@client)
expect(@clients.count).toBe(@count - 1)
it "should not count one client twice", ->
@clients.connect(@client)
@clients.connect(@client)
expect(@clients.count).toBe(1)
describe "connect", ->
describe "with valid request headers", ->
it "should start handshake", ->
spyOn @client, 'handshake'
@clients.connect(@client)
expect(@client.handshake).toHaveBeenCalled()
it "should add listers to client", ->
s = spyOn @client, 'addListener'
@clients.connect(@client)
expect(@client.addListener).toHaveBeenCalled()
expect(s.callCount).toBe(2)
it "should not call close ", ->
spyOn @client, 'close'
@clients.connect(@client)
expect(@client.close).not.toHaveBeenCalled()
it "should store client", ->
@clients.connect(@client)
expect(@clients.list[@client.sid]).toBe(@client)
describe "with invalid request method", ->
it "should call close", ->
@client.request.method = 'POST'
spyOn @client, 'close'
@clients.connect(@client)
expect(@client.close).toHaveBeenCalled()
describe "disconnect", ->
beforeEach ->
@clients.connect(@client)
it "should close the client", ->
spyOn @client, 'close'
@clients.disconnect(@client)
expect(@client.close).toHaveBeenCalled()
it "should delete client from list", ->
@clients.disconnect(@client)
expect(@clients.list[@client.sid]).not.toBeDefined()
describe "diconnectAll", ->
beforeEach ->
@clients.connect(@client)
it "should close all clients", ->
spyOn @client, 'close'
@clients.disconnectAll()
expect(@client.close).toHaveBeenCalled()
it "client count should be 0", ->
@clients.disconnectAll()
expect(@clients.count).toEqual(0)
it "clients should be empty", ->
@clients.disconnectAll()
expect(@clients.list).toEqual({})
describe "broadcast", ->
beforeEach ->
@clients.connect(@client)
it "should call send for all clients", ->
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).toHaveBeenCalled()
it "should not call send in case client is not ready", ->
@client.state = Client.STATUS_OPENING
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).not.toHaveBeenCalled()
it "should not call send in case client is closing", ->
@client.state = Client.STATUS_CLOSING
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).not.toHaveBeenCalled()
| 142508 | require './spec_helper'
Clients = require 'clients'
Client = require 'client'
describe "Clients", ->
beforeEach ->
@clients = new Clients()
# Mock the client
@client =
sid: 123
state: Client.STATUS_READY
request:
method: 'GET'
headers:
upgrade: 'WebSocket'
connection: 'Upgrade'
host: 'localhost:8000'
origin: 'null'
'sec-websocket-key1': '<KEY>'
'sec-websocket-key2': '<KEY>
close: () ->
addListener: () ->
handshake: () ->
send: () ->
describe "client count", ->
it "should be 1", ->
@clients.connect(@client)
expect(@clients.count).toBe(1)
it "should be 0", ->
@clients.connect(@client)
@count = @clients.count
@clients.disconnect(@client)
expect(@clients.count).toBe(@count - 1)
it "should not count one client twice", ->
@clients.connect(@client)
@clients.connect(@client)
expect(@clients.count).toBe(1)
describe "connect", ->
describe "with valid request headers", ->
it "should start handshake", ->
spyOn @client, 'handshake'
@clients.connect(@client)
expect(@client.handshake).toHaveBeenCalled()
it "should add listers to client", ->
s = spyOn @client, 'addListener'
@clients.connect(@client)
expect(@client.addListener).toHaveBeenCalled()
expect(s.callCount).toBe(2)
it "should not call close ", ->
spyOn @client, 'close'
@clients.connect(@client)
expect(@client.close).not.toHaveBeenCalled()
it "should store client", ->
@clients.connect(@client)
expect(@clients.list[@client.sid]).toBe(@client)
describe "with invalid request method", ->
it "should call close", ->
@client.request.method = 'POST'
spyOn @client, 'close'
@clients.connect(@client)
expect(@client.close).toHaveBeenCalled()
describe "disconnect", ->
beforeEach ->
@clients.connect(@client)
it "should close the client", ->
spyOn @client, 'close'
@clients.disconnect(@client)
expect(@client.close).toHaveBeenCalled()
it "should delete client from list", ->
@clients.disconnect(@client)
expect(@clients.list[@client.sid]).not.toBeDefined()
describe "diconnectAll", ->
beforeEach ->
@clients.connect(@client)
it "should close all clients", ->
spyOn @client, 'close'
@clients.disconnectAll()
expect(@client.close).toHaveBeenCalled()
it "client count should be 0", ->
@clients.disconnectAll()
expect(@clients.count).toEqual(0)
it "clients should be empty", ->
@clients.disconnectAll()
expect(@clients.list).toEqual({})
describe "broadcast", ->
beforeEach ->
@clients.connect(@client)
it "should call send for all clients", ->
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).toHaveBeenCalled()
it "should not call send in case client is not ready", ->
@client.state = Client.STATUS_OPENING
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).not.toHaveBeenCalled()
it "should not call send in case client is closing", ->
@client.state = Client.STATUS_CLOSING
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).not.toHaveBeenCalled()
| true | require './spec_helper'
Clients = require 'clients'
Client = require 'client'
describe "Clients", ->
beforeEach ->
@clients = new Clients()
# Mock the client
@client =
sid: 123
state: Client.STATUS_READY
request:
method: 'GET'
headers:
upgrade: 'WebSocket'
connection: 'Upgrade'
host: 'localhost:8000'
origin: 'null'
'sec-websocket-key1': 'PI:KEY:<KEY>END_PI'
'sec-websocket-key2': 'PI:KEY:<KEY>END_PI
close: () ->
addListener: () ->
handshake: () ->
send: () ->
describe "client count", ->
it "should be 1", ->
@clients.connect(@client)
expect(@clients.count).toBe(1)
it "should be 0", ->
@clients.connect(@client)
@count = @clients.count
@clients.disconnect(@client)
expect(@clients.count).toBe(@count - 1)
it "should not count one client twice", ->
@clients.connect(@client)
@clients.connect(@client)
expect(@clients.count).toBe(1)
describe "connect", ->
describe "with valid request headers", ->
it "should start handshake", ->
spyOn @client, 'handshake'
@clients.connect(@client)
expect(@client.handshake).toHaveBeenCalled()
it "should add listers to client", ->
s = spyOn @client, 'addListener'
@clients.connect(@client)
expect(@client.addListener).toHaveBeenCalled()
expect(s.callCount).toBe(2)
it "should not call close ", ->
spyOn @client, 'close'
@clients.connect(@client)
expect(@client.close).not.toHaveBeenCalled()
it "should store client", ->
@clients.connect(@client)
expect(@clients.list[@client.sid]).toBe(@client)
describe "with invalid request method", ->
it "should call close", ->
@client.request.method = 'POST'
spyOn @client, 'close'
@clients.connect(@client)
expect(@client.close).toHaveBeenCalled()
describe "disconnect", ->
beforeEach ->
@clients.connect(@client)
it "should close the client", ->
spyOn @client, 'close'
@clients.disconnect(@client)
expect(@client.close).toHaveBeenCalled()
it "should delete client from list", ->
@clients.disconnect(@client)
expect(@clients.list[@client.sid]).not.toBeDefined()
describe "diconnectAll", ->
beforeEach ->
@clients.connect(@client)
it "should close all clients", ->
spyOn @client, 'close'
@clients.disconnectAll()
expect(@client.close).toHaveBeenCalled()
it "client count should be 0", ->
@clients.disconnectAll()
expect(@clients.count).toEqual(0)
it "clients should be empty", ->
@clients.disconnectAll()
expect(@clients.list).toEqual({})
describe "broadcast", ->
beforeEach ->
@clients.connect(@client)
it "should call send for all clients", ->
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).toHaveBeenCalled()
it "should not call send in case client is not ready", ->
@client.state = Client.STATUS_OPENING
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).not.toHaveBeenCalled()
it "should not call send in case client is closing", ->
@client.state = Client.STATUS_CLOSING
spyOn @client, 'send'
@clients.broadcast("message")
expect(@client.send).not.toHaveBeenCalled()
|
[
{
"context": " -- Required settings --\n\nsteroids.config.name = \"Hello World\"\nsteroids.config.location = \"http://localho",
"end": 56,
"score": 0.5679582953453064,
"start": 51,
"tag": "NAME",
"value": "Hello"
}
] | testApp/config/application.coffee | pentateu/steroids-js | 0 | # -- Required settings --
steroids.config.name = "Hello World"
steroids.config.location = "http://localhost:13101/views/steroids/index.html"
# -- Tabs --
# A boolean to enable tab bar (on bottom)
# This will override steroids.config.location (that is for single webview apps, like in PhoneGap)
# Default: false
#
steroids.config.tabBar.enabled = true
# Array with objects to specify which tabs are created on app startup
#
# Tab object properties are:
# - title: text to show in tab title
# - icon: path to icon file (f.e. images/icon@2x.png)
# - location: can be one of these
# - file URL (relative to www, f.e. index.html)
# - http://localhost:13101/ (serves files locally from www, f.e. http://localhost:13101/ would serve index.html)
# - http://www.google.com (directly from internet)
#
steroids.config.tabBar.tabs = [
# {
# title: "FUT"
# icon: "icons/telescope@2x.png"
# location: "http://localhost/views/steroids/serve.html"
# }
{
title: "HTTP"
icon: "icons/pill@2x.png"
location: "http://localhost/views/steroids/index.html"
}
{
title: "FileURL"
icon: "icons/shoebox@2x.png"
location: "views/steroids/index.html"
}
{
title: "noJS"
icon: "icons/shoebox@2x.png"
location: "nojs.html"
}
]
# -- Status bar --
# Sets status bar visible (carrier, clock, battery status)
# Default: false
#
steroids.config.statusBar.enabled = Math.random() > 0.5
# -- Colors --
# Color values can be set in hex codes, eg. #ffbb20
# Setting these values override values set by the application theme in steroids.config.theme
# Default for all attributes: ""
# steroids.config.navigationBar.tintColor = ""
# steroids.config.navigationBar.titleColor = ""
# steroids.config.navigationBar.titleShadowColor = ""
# steroids.config.navigationBar.buttonTintColor = ""
# steroids.config.navigationBar.buttonTitleColor = ""
# steroids.config.navigationBar.buttonShadowColor = ""
# steroids.config.tabBar.tintColor = ""
# steroids.config.tabBar.tabTitleColor = ""
# steroids.config.tabBar.tabTitleShadowColor = ""
# steroids.config.tabBar.selectedTabTintColor = ""
# Can be used to set an indicator image for the selected tab (can be bigger than the tab)
# Default: ""
# steroids.config.tabBar.selectedTabBackgroundImage = ""
# Built-in iOS theme, values: black and default
# Default: "default"
#
# steroids.config.theme = "default"
# The preMake command is run before `steroids make`, the process where `app/` and `www/` folders are processed into the `dist/` folder.
# steroids.config.hooks.preMake.cmd = "grunt"
# steroids.config.hooks.preMake.args = ["build"]
#
# The postMake command is run right after `steroids make`, before running `steroids package`, the process that packages the app before sending it to client devices.
# steroids.config.hooks.postMake.cmd = "echo"
# steroids.config.hooks.postMake.args = ["cleaning up files"]
| 219271 | # -- Required settings --
steroids.config.name = "<NAME> World"
steroids.config.location = "http://localhost:13101/views/steroids/index.html"
# -- Tabs --
# A boolean to enable tab bar (on bottom)
# This will override steroids.config.location (that is for single webview apps, like in PhoneGap)
# Default: false
#
steroids.config.tabBar.enabled = true
# Array with objects to specify which tabs are created on app startup
#
# Tab object properties are:
# - title: text to show in tab title
# - icon: path to icon file (f.e. images/icon@2x.png)
# - location: can be one of these
# - file URL (relative to www, f.e. index.html)
# - http://localhost:13101/ (serves files locally from www, f.e. http://localhost:13101/ would serve index.html)
# - http://www.google.com (directly from internet)
#
steroids.config.tabBar.tabs = [
# {
# title: "FUT"
# icon: "icons/telescope@2x.png"
# location: "http://localhost/views/steroids/serve.html"
# }
{
title: "HTTP"
icon: "icons/pill@2x.png"
location: "http://localhost/views/steroids/index.html"
}
{
title: "FileURL"
icon: "icons/shoebox@2x.png"
location: "views/steroids/index.html"
}
{
title: "noJS"
icon: "icons/shoebox@2x.png"
location: "nojs.html"
}
]
# -- Status bar --
# Sets status bar visible (carrier, clock, battery status)
# Default: false
#
steroids.config.statusBar.enabled = Math.random() > 0.5
# -- Colors --
# Color values can be set in hex codes, eg. #ffbb20
# Setting these values override values set by the application theme in steroids.config.theme
# Default for all attributes: ""
# steroids.config.navigationBar.tintColor = ""
# steroids.config.navigationBar.titleColor = ""
# steroids.config.navigationBar.titleShadowColor = ""
# steroids.config.navigationBar.buttonTintColor = ""
# steroids.config.navigationBar.buttonTitleColor = ""
# steroids.config.navigationBar.buttonShadowColor = ""
# steroids.config.tabBar.tintColor = ""
# steroids.config.tabBar.tabTitleColor = ""
# steroids.config.tabBar.tabTitleShadowColor = ""
# steroids.config.tabBar.selectedTabTintColor = ""
# Can be used to set an indicator image for the selected tab (can be bigger than the tab)
# Default: ""
# steroids.config.tabBar.selectedTabBackgroundImage = ""
# Built-in iOS theme, values: black and default
# Default: "default"
#
# steroids.config.theme = "default"
# The preMake command is run before `steroids make`, the process where `app/` and `www/` folders are processed into the `dist/` folder.
# steroids.config.hooks.preMake.cmd = "grunt"
# steroids.config.hooks.preMake.args = ["build"]
#
# The postMake command is run right after `steroids make`, before running `steroids package`, the process that packages the app before sending it to client devices.
# steroids.config.hooks.postMake.cmd = "echo"
# steroids.config.hooks.postMake.args = ["cleaning up files"]
| true | # -- Required settings --
steroids.config.name = "PI:NAME:<NAME>END_PI World"
steroids.config.location = "http://localhost:13101/views/steroids/index.html"
# -- Tabs --
# A boolean to enable tab bar (on bottom)
# This will override steroids.config.location (that is for single webview apps, like in PhoneGap)
# Default: false
#
steroids.config.tabBar.enabled = true
# Array with objects to specify which tabs are created on app startup
#
# Tab object properties are:
# - title: text to show in tab title
# - icon: path to icon file (f.e. images/icon@2x.png)
# - location: can be one of these
# - file URL (relative to www, f.e. index.html)
# - http://localhost:13101/ (serves files locally from www, f.e. http://localhost:13101/ would serve index.html)
# - http://www.google.com (directly from internet)
#
steroids.config.tabBar.tabs = [
# {
# title: "FUT"
# icon: "icons/telescope@2x.png"
# location: "http://localhost/views/steroids/serve.html"
# }
{
title: "HTTP"
icon: "icons/pill@2x.png"
location: "http://localhost/views/steroids/index.html"
}
{
title: "FileURL"
icon: "icons/shoebox@2x.png"
location: "views/steroids/index.html"
}
{
title: "noJS"
icon: "icons/shoebox@2x.png"
location: "nojs.html"
}
]
# -- Status bar --
# Sets status bar visible (carrier, clock, battery status)
# Default: false
#
steroids.config.statusBar.enabled = Math.random() > 0.5
# -- Colors --
# Color values can be set in hex codes, eg. #ffbb20
# Setting these values override values set by the application theme in steroids.config.theme
# Default for all attributes: ""
# steroids.config.navigationBar.tintColor = ""
# steroids.config.navigationBar.titleColor = ""
# steroids.config.navigationBar.titleShadowColor = ""
# steroids.config.navigationBar.buttonTintColor = ""
# steroids.config.navigationBar.buttonTitleColor = ""
# steroids.config.navigationBar.buttonShadowColor = ""
# steroids.config.tabBar.tintColor = ""
# steroids.config.tabBar.tabTitleColor = ""
# steroids.config.tabBar.tabTitleShadowColor = ""
# steroids.config.tabBar.selectedTabTintColor = ""
# Can be used to set an indicator image for the selected tab (can be bigger than the tab)
# Default: ""
# steroids.config.tabBar.selectedTabBackgroundImage = ""
# Built-in iOS theme, values: black and default
# Default: "default"
#
# steroids.config.theme = "default"
# The preMake command is run before `steroids make`, the process where `app/` and `www/` folders are processed into the `dist/` folder.
# steroids.config.hooks.preMake.cmd = "grunt"
# steroids.config.hooks.preMake.args = ["build"]
#
# The postMake command is run right after `steroids make`, before running `steroids package`, the process that packages the app before sending it to client devices.
# steroids.config.hooks.postMake.cmd = "echo"
# steroids.config.hooks.postMake.args = ["cleaning up files"]
|
[
{
"context": "req) ->\n req.body = users: [{id: 1, name: 'bob'}, {id: 2, name: 'david'}]\n req.ok = true\n",
"end": 436,
"score": 0.9986296892166138,
"start": 433,
"tag": "NAME",
"value": "bob"
},
{
"context": "dy = users: [{id: 1, name: 'bob'}, {id: 2, name: 'david'}]\n req.ok = true\n req\n\n it 'sho",
"end": 460,
"score": 0.9996100068092346,
"start": 455,
"tag": "NAME",
"value": "david"
}
] | test/delivery_service.spec.cjsx | PayloadDev/react-at-rest | 48 | React = require 'react'
superagent = require 'superagent'
mocker = require('superagent-mocker')(superagent)
expect = require 'expect'
TestUtils = require 'react-addons-test-utils'
{Store, DeliveryService} = require '../modules'
describe 'DeliveryService', ->
store = new Store 'users'
describe '#render()', ->
before ->
mocker.get '/users', (req) ->
req.body = users: [{id: 1, name: 'bob'}, {id: 2, name: 'david'}]
req.ok = true
req
it 'should render in an unloaded state', ->
class UserTestPage extends DeliveryService
render: ->
return <div /> unless @state.loaded
<h1 />
component = TestUtils.renderIntoDocument <UserTestPage />
expect(component.state.loaded).toBe false
expect(TestUtils.findRenderedDOMComponentWithTag component, 'div').toExist()
describe '#resourcesDidLoad()', ->
it 'should retrieve bound data', (done) ->
class UserTestPage extends DeliveryService
bindResources: ->
@retrieveAll store
resourcesDidLoad: ->
expect(component.state.loaded).toBe true
expect(component.state.users).toExist()
expect(component.state.users.length).toBe 2
done()
render: ->
return <div /> unless @state.loaded
<h1 />
component = TestUtils.renderIntoDocument <UserTestPage />
describe '#mungeArgs()', ->
it 'should detect a null first argument', ->
spy = expect.spyOn console, 'error'
options = DeliveryService::mungeArgs [null, {company: 'GloboChem'}]
expect(spy).toHaveBeenCalled()
expect(options).toEqual {company: 'GloboChem'}
expect.restoreSpies()
it 'should return options when there is 1 argument', ->
options = DeliveryService::mungeArgs [{company: 'GloboChem'}]
expect(options).toEqual {company: 'GloboChem'}
it 'should return null when there is a single null argument', ->
options = DeliveryService::mungeArgs [null]
expect(options).toEqual null
| 75215 | React = require 'react'
superagent = require 'superagent'
mocker = require('superagent-mocker')(superagent)
expect = require 'expect'
TestUtils = require 'react-addons-test-utils'
{Store, DeliveryService} = require '../modules'
describe 'DeliveryService', ->
store = new Store 'users'
describe '#render()', ->
before ->
mocker.get '/users', (req) ->
req.body = users: [{id: 1, name: '<NAME>'}, {id: 2, name: '<NAME>'}]
req.ok = true
req
it 'should render in an unloaded state', ->
class UserTestPage extends DeliveryService
render: ->
return <div /> unless @state.loaded
<h1 />
component = TestUtils.renderIntoDocument <UserTestPage />
expect(component.state.loaded).toBe false
expect(TestUtils.findRenderedDOMComponentWithTag component, 'div').toExist()
describe '#resourcesDidLoad()', ->
it 'should retrieve bound data', (done) ->
class UserTestPage extends DeliveryService
bindResources: ->
@retrieveAll store
resourcesDidLoad: ->
expect(component.state.loaded).toBe true
expect(component.state.users).toExist()
expect(component.state.users.length).toBe 2
done()
render: ->
return <div /> unless @state.loaded
<h1 />
component = TestUtils.renderIntoDocument <UserTestPage />
describe '#mungeArgs()', ->
it 'should detect a null first argument', ->
spy = expect.spyOn console, 'error'
options = DeliveryService::mungeArgs [null, {company: 'GloboChem'}]
expect(spy).toHaveBeenCalled()
expect(options).toEqual {company: 'GloboChem'}
expect.restoreSpies()
it 'should return options when there is 1 argument', ->
options = DeliveryService::mungeArgs [{company: 'GloboChem'}]
expect(options).toEqual {company: 'GloboChem'}
it 'should return null when there is a single null argument', ->
options = DeliveryService::mungeArgs [null]
expect(options).toEqual null
| true | React = require 'react'
superagent = require 'superagent'
mocker = require('superagent-mocker')(superagent)
expect = require 'expect'
TestUtils = require 'react-addons-test-utils'
{Store, DeliveryService} = require '../modules'
describe 'DeliveryService', ->
store = new Store 'users'
describe '#render()', ->
before ->
mocker.get '/users', (req) ->
req.body = users: [{id: 1, name: 'PI:NAME:<NAME>END_PI'}, {id: 2, name: 'PI:NAME:<NAME>END_PI'}]
req.ok = true
req
it 'should render in an unloaded state', ->
class UserTestPage extends DeliveryService
render: ->
return <div /> unless @state.loaded
<h1 />
component = TestUtils.renderIntoDocument <UserTestPage />
expect(component.state.loaded).toBe false
expect(TestUtils.findRenderedDOMComponentWithTag component, 'div').toExist()
describe '#resourcesDidLoad()', ->
it 'should retrieve bound data', (done) ->
class UserTestPage extends DeliveryService
bindResources: ->
@retrieveAll store
resourcesDidLoad: ->
expect(component.state.loaded).toBe true
expect(component.state.users).toExist()
expect(component.state.users.length).toBe 2
done()
render: ->
return <div /> unless @state.loaded
<h1 />
component = TestUtils.renderIntoDocument <UserTestPage />
describe '#mungeArgs()', ->
it 'should detect a null first argument', ->
spy = expect.spyOn console, 'error'
options = DeliveryService::mungeArgs [null, {company: 'GloboChem'}]
expect(spy).toHaveBeenCalled()
expect(options).toEqual {company: 'GloboChem'}
expect.restoreSpies()
it 'should return options when there is 1 argument', ->
options = DeliveryService::mungeArgs [{company: 'GloboChem'}]
expect(options).toEqual {company: 'GloboChem'}
it 'should return null when there is a single null argument', ->
options = DeliveryService::mungeArgs [null]
expect(options).toEqual null
|
[
{
"context": "mation\n constructor: (@deg, @family) ->\n\n key: \"rotate\"\n\n toAttr: ->\n \"rotate(#{@deg.places 3} #{@fa",
"end": 1542,
"score": 0.9754685163497925,
"start": 1536,
"tag": "KEY",
"value": "rotate"
}
] | src/coffee/geometry/transformations.coffee | agiza/mondrian | 226 | class Transformations
constructor: (@owner, @transformations) ->
transform = @owner.rep.getAttribute "transform"
@transformations.map (t) => t.family = @
@parseExisting transform if transform?
commit: ->
@owner.data.transform = @toAttr()
toAttr: ->
@transformations.map((t) -> t.toAttr()).join " "
toCSS: ->
@transformations.map((t) -> t.toCSS()).join " "
get: (key) ->
f = @transformations.filter (t) -> t.key is key
return f[0] if f.length > 0
parseExisting: (transform) ->
operations = transform.match /\w+\([^\)]*\)/g
for op in operations
# get the keyword, like "rotate" from "rotate(10)"
keyword = op.match(/^\w+/g)[0]
alreadyDefined = @get keyword
if alreadyDefined?
alreadyDefined.parse op
else
representative = {
rotate: RotateTransformation
scale: ScaleTransformation
}[keyword]
if representative?
newlyDefined = new representative().parse(op)
newlyDefined.family = @
@transformations.push newlyDefined
applyAsCSS: (rep) ->
og = "-#{@owner.origin.x} -#{@owner.origin.y}"
tr = @toCSS()
rep.style.transformOrigin = og
rep.style.webkitTransformOrigin = og
rep.style.mozTransformOrigin = og
rep.style.transform = tr
rep.style.webkitTransformOrigin = og
rep.style.webkitTransform = tr
rep.style.mozTransformOrigin = og
rep.style.mozTransform = tr
class RotateTransformation
constructor: (@deg, @family) ->
key: "rotate"
toAttr: ->
"rotate(#{@deg.places 3} #{@family.owner.center().x.places 3} #{@family.owner.center().y.places 3})"
toCSS: ->
"rotate(#{@deg.places 3}deg)"
rotate: (a) ->
@deg += a
@deg %= 360
@
parse: (op) ->
[@deg, x, y] = op.match(/[\d\.]+/g).map parseFloat
class ScaleTransformation
constructor: (@x = 1, @y = 1) ->
key: "scale"
toAttr: ->
"scale(#{@x} #{@y})"
toCSS: ->
"scale(#{@x}, #{@y})"
parse: (op) ->
[@x, @y] = op.match(/[\d\.]+/g).map parseFloat
scale: (x = 1, y = 1) ->
@x *= x
@y *= y
class TranslateTransformation
constructor: (@x = 0, @y = 1) ->
key: "translate"
toAttr: ->
"translate(#{@x} #{@y})"
toCSS: ->
"translate(#{@x}px, #{@y}px)"
parse: (op) ->
[@x, @y] = op.match(/[\-\d\.]+/g).map parseFloat
nudge: (x, y) ->
console.log x, y
@x += x
@y -= y
| 224664 | class Transformations
constructor: (@owner, @transformations) ->
transform = @owner.rep.getAttribute "transform"
@transformations.map (t) => t.family = @
@parseExisting transform if transform?
commit: ->
@owner.data.transform = @toAttr()
toAttr: ->
@transformations.map((t) -> t.toAttr()).join " "
toCSS: ->
@transformations.map((t) -> t.toCSS()).join " "
get: (key) ->
f = @transformations.filter (t) -> t.key is key
return f[0] if f.length > 0
parseExisting: (transform) ->
operations = transform.match /\w+\([^\)]*\)/g
for op in operations
# get the keyword, like "rotate" from "rotate(10)"
keyword = op.match(/^\w+/g)[0]
alreadyDefined = @get keyword
if alreadyDefined?
alreadyDefined.parse op
else
representative = {
rotate: RotateTransformation
scale: ScaleTransformation
}[keyword]
if representative?
newlyDefined = new representative().parse(op)
newlyDefined.family = @
@transformations.push newlyDefined
applyAsCSS: (rep) ->
og = "-#{@owner.origin.x} -#{@owner.origin.y}"
tr = @toCSS()
rep.style.transformOrigin = og
rep.style.webkitTransformOrigin = og
rep.style.mozTransformOrigin = og
rep.style.transform = tr
rep.style.webkitTransformOrigin = og
rep.style.webkitTransform = tr
rep.style.mozTransformOrigin = og
rep.style.mozTransform = tr
class RotateTransformation
constructor: (@deg, @family) ->
key: "<KEY>"
toAttr: ->
"rotate(#{@deg.places 3} #{@family.owner.center().x.places 3} #{@family.owner.center().y.places 3})"
toCSS: ->
"rotate(#{@deg.places 3}deg)"
rotate: (a) ->
@deg += a
@deg %= 360
@
parse: (op) ->
[@deg, x, y] = op.match(/[\d\.]+/g).map parseFloat
class ScaleTransformation
constructor: (@x = 1, @y = 1) ->
key: "scale"
toAttr: ->
"scale(#{@x} #{@y})"
toCSS: ->
"scale(#{@x}, #{@y})"
parse: (op) ->
[@x, @y] = op.match(/[\d\.]+/g).map parseFloat
scale: (x = 1, y = 1) ->
@x *= x
@y *= y
class TranslateTransformation
constructor: (@x = 0, @y = 1) ->
key: "translate"
toAttr: ->
"translate(#{@x} #{@y})"
toCSS: ->
"translate(#{@x}px, #{@y}px)"
parse: (op) ->
[@x, @y] = op.match(/[\-\d\.]+/g).map parseFloat
nudge: (x, y) ->
console.log x, y
@x += x
@y -= y
| true | class Transformations
constructor: (@owner, @transformations) ->
transform = @owner.rep.getAttribute "transform"
@transformations.map (t) => t.family = @
@parseExisting transform if transform?
commit: ->
@owner.data.transform = @toAttr()
toAttr: ->
@transformations.map((t) -> t.toAttr()).join " "
toCSS: ->
@transformations.map((t) -> t.toCSS()).join " "
get: (key) ->
f = @transformations.filter (t) -> t.key is key
return f[0] if f.length > 0
parseExisting: (transform) ->
operations = transform.match /\w+\([^\)]*\)/g
for op in operations
# get the keyword, like "rotate" from "rotate(10)"
keyword = op.match(/^\w+/g)[0]
alreadyDefined = @get keyword
if alreadyDefined?
alreadyDefined.parse op
else
representative = {
rotate: RotateTransformation
scale: ScaleTransformation
}[keyword]
if representative?
newlyDefined = new representative().parse(op)
newlyDefined.family = @
@transformations.push newlyDefined
applyAsCSS: (rep) ->
og = "-#{@owner.origin.x} -#{@owner.origin.y}"
tr = @toCSS()
rep.style.transformOrigin = og
rep.style.webkitTransformOrigin = og
rep.style.mozTransformOrigin = og
rep.style.transform = tr
rep.style.webkitTransformOrigin = og
rep.style.webkitTransform = tr
rep.style.mozTransformOrigin = og
rep.style.mozTransform = tr
class RotateTransformation
constructor: (@deg, @family) ->
key: "PI:KEY:<KEY>END_PI"
toAttr: ->
"rotate(#{@deg.places 3} #{@family.owner.center().x.places 3} #{@family.owner.center().y.places 3})"
toCSS: ->
"rotate(#{@deg.places 3}deg)"
rotate: (a) ->
@deg += a
@deg %= 360
@
parse: (op) ->
[@deg, x, y] = op.match(/[\d\.]+/g).map parseFloat
class ScaleTransformation
constructor: (@x = 1, @y = 1) ->
key: "scale"
toAttr: ->
"scale(#{@x} #{@y})"
toCSS: ->
"scale(#{@x}, #{@y})"
parse: (op) ->
[@x, @y] = op.match(/[\d\.]+/g).map parseFloat
scale: (x = 1, y = 1) ->
@x *= x
@y *= y
class TranslateTransformation
constructor: (@x = 0, @y = 1) ->
key: "translate"
toAttr: ->
"translate(#{@x} #{@y})"
toCSS: ->
"translate(#{@x}px, #{@y}px)"
parse: (op) ->
[@x, @y] = op.match(/[\-\d\.]+/g).map parseFloat
nudge: (x, y) ->
console.log x, y
@x += x
@y -= y
|
[
{
"context": " id: Info.id\n key: Info.key\n name: 'TEST APP'\n notifierURL: 'https://github.com/Wayfa",
"end": 2024,
"score": 0.7179228067398071,
"start": 2020,
"tag": "NAME",
"value": "TEST"
},
{
"context": "'TEST APP'\n notifierURL: 'https://github.com/Wayfarer247/airbrake-hapi'\n environment: 'production'\n\n ",
"end": 2080,
"score": 0.9997162818908691,
"start": 2069,
"tag": "USERNAME",
"value": "Wayfarer247"
}
] | test/integration/airbrake.coffee | Wayfarer247/airbrake-hapi | 0 | Hapi = require 'hapi'
should = require('chai').should()
Airbrake = require '../../lib'
AirbrakeInternal = require '../../lib/airbrake'
Info = require '../airbrake_info.json'
describe 'Airbrake Hapi', ->
it 'should correctly send', (done)->
error = new Error('It Broke Here')
hapiRequest =
url:
path: '/testing/test/t'
options =
id: Info.id
key: Info.key
server = on: (->)
airbrake = new AirbrakeInternal(server, options)
airbrake.environment = 'production'
airbrake.start ->
airbrake.notify(error, hapiRequest)
airbrake.on 'sent', (event)->
event.id.should.be.ok
event.url.should.contain 'https://airbrake.io/locate'
done()
it 'should error without a proper config', (done)->
error = new Error('It Broke Here')
hapiRequest =
url:
path: '/testing/test/t'
server = on: (->)
airbrake = new AirbrakeInternal(server, {})
airbrake.environment = 'production'
airbrake.on 'error', (event)->
event.message.should.equal 'options.uri is a required argument'
done()
airbrake.start ->
airbrake.notify(error, hapiRequest)
it 'should fail to load the plugin with no id/key given', (done)->
server = new Hapi.Server()
server.connection()
server.register register: Airbrake, (err)->
err.message.should.equal 'No Project ID or API Key was given!'
done()
it 'should load the plugin with the id and key', (done)->
server = new Hapi.Server()
server.connection()
server.register {register: Airbrake, options: {id: '1', key: '2'}}, (err)->
should.not.exist err
done()
it 'should notify when an error occurs', (done)->
@timeout 5000
server = new Hapi.Server()
handler = (req, reply)->
throw new Error('BROKEN!')
reply()
server.connection()
server.route(method: 'GET', path: '/', handler: handler)
options =
id: Info.id
key: Info.key
name: 'TEST APP'
notifierURL: 'https://github.com/Wayfarer247/airbrake-hapi'
environment: 'production'
server.register {register: Airbrake, options: options}, (err)->
should.not.exist err
server.inject {method: 'GET', url: '/'}, (res)->
res.statusCode.should.equal 500
airbrake = server.plugins['airbrake-hapi'].airbrake
airbrake.on 'sent', (event)->
event.id.should.be.ok
event.url.should.contain 'https://airbrake.io/locate'
done()
| 224761 | Hapi = require 'hapi'
should = require('chai').should()
Airbrake = require '../../lib'
AirbrakeInternal = require '../../lib/airbrake'
Info = require '../airbrake_info.json'
describe 'Airbrake Hapi', ->
it 'should correctly send', (done)->
error = new Error('It Broke Here')
hapiRequest =
url:
path: '/testing/test/t'
options =
id: Info.id
key: Info.key
server = on: (->)
airbrake = new AirbrakeInternal(server, options)
airbrake.environment = 'production'
airbrake.start ->
airbrake.notify(error, hapiRequest)
airbrake.on 'sent', (event)->
event.id.should.be.ok
event.url.should.contain 'https://airbrake.io/locate'
done()
it 'should error without a proper config', (done)->
error = new Error('It Broke Here')
hapiRequest =
url:
path: '/testing/test/t'
server = on: (->)
airbrake = new AirbrakeInternal(server, {})
airbrake.environment = 'production'
airbrake.on 'error', (event)->
event.message.should.equal 'options.uri is a required argument'
done()
airbrake.start ->
airbrake.notify(error, hapiRequest)
it 'should fail to load the plugin with no id/key given', (done)->
server = new Hapi.Server()
server.connection()
server.register register: Airbrake, (err)->
err.message.should.equal 'No Project ID or API Key was given!'
done()
it 'should load the plugin with the id and key', (done)->
server = new Hapi.Server()
server.connection()
server.register {register: Airbrake, options: {id: '1', key: '2'}}, (err)->
should.not.exist err
done()
it 'should notify when an error occurs', (done)->
@timeout 5000
server = new Hapi.Server()
handler = (req, reply)->
throw new Error('BROKEN!')
reply()
server.connection()
server.route(method: 'GET', path: '/', handler: handler)
options =
id: Info.id
key: Info.key
name: '<NAME> APP'
notifierURL: 'https://github.com/Wayfarer247/airbrake-hapi'
environment: 'production'
server.register {register: Airbrake, options: options}, (err)->
should.not.exist err
server.inject {method: 'GET', url: '/'}, (res)->
res.statusCode.should.equal 500
airbrake = server.plugins['airbrake-hapi'].airbrake
airbrake.on 'sent', (event)->
event.id.should.be.ok
event.url.should.contain 'https://airbrake.io/locate'
done()
| true | Hapi = require 'hapi'
should = require('chai').should()
Airbrake = require '../../lib'
AirbrakeInternal = require '../../lib/airbrake'
Info = require '../airbrake_info.json'
describe 'Airbrake Hapi', ->
it 'should correctly send', (done)->
error = new Error('It Broke Here')
hapiRequest =
url:
path: '/testing/test/t'
options =
id: Info.id
key: Info.key
server = on: (->)
airbrake = new AirbrakeInternal(server, options)
airbrake.environment = 'production'
airbrake.start ->
airbrake.notify(error, hapiRequest)
airbrake.on 'sent', (event)->
event.id.should.be.ok
event.url.should.contain 'https://airbrake.io/locate'
done()
it 'should error without a proper config', (done)->
error = new Error('It Broke Here')
hapiRequest =
url:
path: '/testing/test/t'
server = on: (->)
airbrake = new AirbrakeInternal(server, {})
airbrake.environment = 'production'
airbrake.on 'error', (event)->
event.message.should.equal 'options.uri is a required argument'
done()
airbrake.start ->
airbrake.notify(error, hapiRequest)
it 'should fail to load the plugin with no id/key given', (done)->
server = new Hapi.Server()
server.connection()
server.register register: Airbrake, (err)->
err.message.should.equal 'No Project ID or API Key was given!'
done()
it 'should load the plugin with the id and key', (done)->
server = new Hapi.Server()
server.connection()
server.register {register: Airbrake, options: {id: '1', key: '2'}}, (err)->
should.not.exist err
done()
it 'should notify when an error occurs', (done)->
@timeout 5000
server = new Hapi.Server()
handler = (req, reply)->
throw new Error('BROKEN!')
reply()
server.connection()
server.route(method: 'GET', path: '/', handler: handler)
options =
id: Info.id
key: Info.key
name: 'PI:NAME:<NAME>END_PI APP'
notifierURL: 'https://github.com/Wayfarer247/airbrake-hapi'
environment: 'production'
server.register {register: Airbrake, options: options}, (err)->
should.not.exist err
server.inject {method: 'GET', url: '/'}, (res)->
res.statusCode.should.equal 500
airbrake = server.plugins['airbrake-hapi'].airbrake
airbrake.on 'sent', (event)->
event.id.should.be.ok
event.url.should.contain 'https://airbrake.io/locate'
done()
|
[
{
"context": "(\"click\", toggleActive)\n\ndocsearch({\n apiKey: \"761e2f48adc098d3b8ded157d79d009d\",\n indexName: \"luxonauta\",\n inputSelector: ",
"end": 334,
"score": 0.9997549057006836,
"start": 302,
"tag": "KEY",
"value": "761e2f48adc098d3b8ded157d79d009d"
}
] | coffee/main.coffee | luxonauta/luxadocs | 1 | toggleActive = () ->
navbarBurger.classList.toggle("is-active")
navbarMenu.classList.toggle("is-active")
navbarBurger = document.querySelector(".lx-nav-burger")
navbarMenu = document.querySelector(".lx-nav-menu")
navbarBurger.addEventListener("click", toggleActive)
docsearch({
apiKey: "761e2f48adc098d3b8ded157d79d009d",
indexName: "luxonauta",
inputSelector: "#search",
debug: false
}); | 93910 | toggleActive = () ->
navbarBurger.classList.toggle("is-active")
navbarMenu.classList.toggle("is-active")
navbarBurger = document.querySelector(".lx-nav-burger")
navbarMenu = document.querySelector(".lx-nav-menu")
navbarBurger.addEventListener("click", toggleActive)
docsearch({
apiKey: "<KEY>",
indexName: "luxonauta",
inputSelector: "#search",
debug: false
}); | true | toggleActive = () ->
navbarBurger.classList.toggle("is-active")
navbarMenu.classList.toggle("is-active")
navbarBurger = document.querySelector(".lx-nav-burger")
navbarMenu = document.querySelector(".lx-nav-menu")
navbarBurger.addEventListener("click", toggleActive)
docsearch({
apiKey: "PI:KEY:<KEY>END_PI",
indexName: "luxonauta",
inputSelector: "#search",
debug: false
}); |
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999102354049683,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmap-discussions/system-post.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 { button, div, span } from 'react-dom-factories'
el = React.createElement
bn = 'beatmap-discussion-system-post'
export SystemPost = (props) ->
message =
switch props.post.message.type
when 'resolved'
osu.trans "beatmap_discussions.system.resolved.#{props.post.message.value}",
user: osu.link laroute.route('users.show', user: props.user.id), props.user.username,
classNames: ["#{bn}__user"]
topClass = "#{bn} #{bn}--#{props.post.message.type}"
topClass += " #{bn}--deleted" if props.post.deleted_at
div
className: topClass
div
className: "#{bn}__content"
dangerouslySetInnerHTML:
__html: message
| 128569 | # 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 { button, div, span } from 'react-dom-factories'
el = React.createElement
bn = 'beatmap-discussion-system-post'
export SystemPost = (props) ->
message =
switch props.post.message.type
when 'resolved'
osu.trans "beatmap_discussions.system.resolved.#{props.post.message.value}",
user: osu.link laroute.route('users.show', user: props.user.id), props.user.username,
classNames: ["#{bn}__user"]
topClass = "#{bn} #{bn}--#{props.post.message.type}"
topClass += " #{bn}--deleted" if props.post.deleted_at
div
className: topClass
div
className: "#{bn}__content"
dangerouslySetInnerHTML:
__html: message
| 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 { button, div, span } from 'react-dom-factories'
el = React.createElement
bn = 'beatmap-discussion-system-post'
export SystemPost = (props) ->
message =
switch props.post.message.type
when 'resolved'
osu.trans "beatmap_discussions.system.resolved.#{props.post.message.value}",
user: osu.link laroute.route('users.show', user: props.user.id), props.user.username,
classNames: ["#{bn}__user"]
topClass = "#{bn} #{bn}--#{props.post.message.type}"
topClass += " #{bn}--deleted" if props.post.deleted_at
div
className: topClass
div
className: "#{bn}__content"
dangerouslySetInnerHTML:
__html: message
|
[
{
"context": "me: \"user\"\n @uri : \"/users\"\n\n\n @encode \"name\", \"lastname\", \"email\"\n @association(Address, @HA",
"end": 129,
"score": 0.5672674775123596,
"start": 125,
"tag": "NAME",
"value": "name"
},
{
"context": "r\"\n @uri : \"/users\"\n\n\n @encode \"name\", \"lastname\", \"email\"\n @association(Address, @HAS_ONE)\n @ti",
"end": 141,
"score": 0.8138721585273743,
"start": 133,
"tag": "NAME",
"value": "lastname"
}
] | spec/javascripts/support/user_model.coffee | zaeznet/joker-rails | 0 |
class window.User extends Joker.Model
@fields = new Object
@resourceName: "user"
@uri : "/users"
@encode "name", "lastname", "email"
@association(Address, @HAS_ONE)
@timestamp()
| 124512 |
class window.User extends Joker.Model
@fields = new Object
@resourceName: "user"
@uri : "/users"
@encode "<NAME>", "<NAME>", "email"
@association(Address, @HAS_ONE)
@timestamp()
| true |
class window.User extends Joker.Model
@fields = new Object
@resourceName: "user"
@uri : "/users"
@encode "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "email"
@association(Address, @HAS_ONE)
@timestamp()
|
[
{
"context": "\n \"archived-topic\": \"Archived topic\"\n \"mention\": \"@me\"\n \"batch-invite-textarea\": \"Enter emails. Use sp",
"end": 1077,
"score": 0.855443000793457,
"start": 1073,
"tag": "USERNAME",
"value": "\"@me"
},
{
"context": "\"wish-talk\": \"Wish more support?\"\n \"your-name\": \"Your name\"\n \"join-%s-room\": \"topic %s joined\"\n \"firim-url",
"end": 19141,
"score": 0.8390336036682129,
"start": 19132,
"tag": "USERNAME",
"value": "Your name"
},
{
"context": "oks\": \"Incoming Webhooks\"\n \"jiankongbao-token\": \"Jiankongbao Token\"\n \"enter-and-shift\": \"Shift + Ent",
"end": 20863,
"score": 0.6218297481536865,
"start": 20861,
"tag": "KEY",
"value": "Ji"
},
{
"context": "s\": \"Incoming Webhooks\"\n \"jiankongbao-token\": \"Jiankongbao Token\"\n \"enter-and-shift\": \"Shift + Enter for li",
"end": 20872,
"score": 0.7814299464225769,
"start": 20863,
"tag": "PASSWORD",
"value": "ankongbao"
},
{
"context": "ming Webhooks\"\n \"jiankongbao-token\": \"Jiankongbao Token\"\n \"enter-and-shift\": \"Shift + Enter for line bre",
"end": 20878,
"score": 0.6054701209068298,
"start": 20873,
"tag": "KEY",
"value": "Token"
},
{
"context": "\"\n \"contact-info\": \"Phone Number\"\n \"nickname\": \"Nickname\"\n \"enter-nickname\": \"Enter a nickname...\"\n \"nic",
"end": 27191,
"score": 0.998898983001709,
"start": 27183,
"tag": "USERNAME",
"value": "Nickname"
}
] | talk-web/client/locales/en.coffee | ikingye/talk-os | 3,084 | module.exports =
"about-guest-email": "If you need to save %s, there will be a record sent to your mailbox。"
"about-guest-talk": "Now you can participate in discussions. As a visitor, you are only allowed to view the page in this conversation."
"about-integrations": "Talk can help you aggregate informations scattered in various places into one place, and facilitate swift access to information, to initiate discussions."
"about-private-topic": "Private topic(only topic members see it)"
"about-public-topic": "Public topic(all members can see it)"
"about-talk": "About Talk"
"add": "Add"
"add-coding": "Add Coding.net"
"add-firim": "Connect to FIR.im"
"add-github": "Connect to GitHub"
"add-gitlab": "Connect to GitLab"
"add-jiankongbao": "Connect Jiankongbao"
"add-jinshuju": "Add jinshuju.net"
"add-rss": "Add RSS"
"add-service": "Add integrations"
"add-weibo": "Add Weibo"
"admin": "Administrator"
"ai-robot": "Talk AI"
"all-members": "All"
"archived-topics": "Archived topics"
"archived-topic": "Archived topic"
"mention": "@me"
"batch-invite-textarea": "Enter emails. Use space, semicolon or newline to divide"
"blog": "Blog"
'by-mail-integrations': 'Integrations by email'
"cancel": "Cancel"
"change": "Change"
"choose-repo": "Choose a GitHub repo:"
"choose-a-topic": "Choose a topic"
"choose-topic": "Choose a topic"
"choose-topic-for-integration": "Choose the topic to connect with:"
"close": "Close"
"coding": "Coding.net"
"coding-url-guide": "Open your project settings on Coding.net, select the WebHook settings, add a WebHook address to your project to receive push notifications."
"comma": ", "
"comment": "Comments"
"comming-soon": "Coming soon"
"config-github": "Config GitHub"
"confirm": "Confirm"
"confirm-adding": "Confirm add"
"confirm-delete-topic": "All records in this topic will be permanently deleted. Confirm to delete."
"confirm-delete-topic-member": "Confirm to remove member."
"connect-to-firim": "Connect to FIR.im:"
"connect-to-github": "Connect to GitHub: "
"connect-to-weibo": "Connect to Weibo: "
"connected": "Network connected, welcome back"
"contact-quitted": "Quitted member"
"create-team": "Create a new team"
"created-updated-time": "created on {{created}}, updated on {{updated}}"
"custom-robot": "Custom Robot"
"custom-service": "Customize service"
"default-default-style": "Default style"
"delete": "Delete"
"desktop-notifications": "Desktop notifications"
"disable–guest-mode": "Disable guest access"
"disable-topic-notifications": "Disable push notification"
"enable-topic-notifications": "Enable push notification"
"dismiss": "Dismiss"
"display-settings": "Display settings"
"dnd-guide": "Drop file here to upload."
"dot": ". "
"douban": "Douban"
"download": "Download"
"download-apps": "Download Apps"
"download-file": "Download file"
"edit": "Edit"
"inte-email": "Email"
"inte-email-details": "More"
"inte-email-select-topic": "Select a topic"
"inte-email-select-topic-description": "or, create one"
"inte-email-address": "Email address"
"inte-email-address-description": "You may send emails to this address to push messages into the selected topic."
"inte-email-ifttt-tutorial": "How to get more integrations through IFTTT."
"inte-email-summary": "Push messages to a specific topic."
"inte-email-description": "Push messages to a specific topic."
"email-%s-message": "You may send emails to %s, which will push messages to this topic"
"email-message": "Send messages with email"
"email-message-%s": "You may send emails to the address below to push messages into %s"
"email-notifications": "Email notifications"
"email-optional": "Email(Optional)"
"emoji-deluxe": "Emoji Deluxe"
"end-of-history": "No more history messages"
"end-of-recent": "No more recent messages"
"error": "Sorry, something error!"
"failed-adding-rss": "Failed to add RSS integration."
"feedback-mail": "Send feedback to "
"fill-in-callback-token": "Fill in with a callback token(optional)"
"fill-repo-name": "account/repo (one that you have the \"write\" permission)"
"firim": "FIR.im"
"fold": "Fold"
"generate-webhook": "Generate WebHook url"
"generate–guest-link": "Generate guest access url"
"github": "GitHub"
"github-title-commit_comment": "Any time a Commit is commented on"
"github-title-create": "Any time a Branch or Tag is created"
"github-title-delete": "Any time a Branch or Tag is deleted"
"github-title-fork": "Any time a Repository is forked"
"github-title-issue_comment": "Any time an Issue is commented on"
"github-title-issues": "Any time an Issue is assigned, unassigned, labelled, unlabelled, opened, closed, or reopened"
"github-title-pull_request": "Any time a Pull Request is assigned, unassigned, labelled, unlabelled, opened, closed, reopened, or synchronized (updated due to a new push in the branch that the pull request is tracking)"
"github-title-pull_request_review_comment": "Any time a Commit is commented on while inside a Pull Request review (the Files Changed tab)"
"github-title-push": "Any Git push to a Repository, including editing tags or branches. Commits via API actions that update references are also counted. This is the default event"
"gitlab": "GitLab"
"gitlab-url-guide": "Copy this WebHook to your GitLab repo to use it. You may also find this url in the manager tab."
"guest-mode": "Guest mode"
"guest-mode-intro": "With Guest mode is turned on, visitors can join the discussion by visiting the url, but they can't see your message history."
"guest-mode-opened": "Guest mode is on. You can turn it off when you finish the conversation."
"guest-views-history": "Guest sees history messages"
"guide-point-contacts": "\"SyncTalk\" is a communication space featured by security and pleasure. Just invite your team member to join the discussion, you are guaranteed away from any disturbance."
"guide-point-guide": "Tip"
"guide-point-members": "Find members in this topic."
"guide-point-switch": "Click here to share your documents with all who have been involved in this topic, or just try to drag you documents into the window directly?"
"guide-point-topic": "To make the discussion more specific, launch various topics for various objects. For instance: “the internal share” or “propaganda plan discussion” etc."
"guide-point-upload": "Click here to create a new team, or just select another team."
"hide": "Hide"
"hide-content": "Hide content"
"history-invisible-to-guests": "Topic history is now hidden from guests"
"history-visible-to-guests": "Topic history is now visible to guests"
"home": "Home"
"html5AudioNotSupport": "You browser does not support this audio"
"html5VideoNotSupport": "You browser does not support this video"
"info-coding-new-event": "Event from Coding.net"
"info-comment": "comment"
"info-commit_comment": "Comment on commit"
"info-create": "Create branch or tag"
"info-create-integration": "Created integration"
"info-created-file": "Uploaded file"
"info-created-snippet": "Created snippet"
"info-created-task": "Created task"
"info-delete": "Delete branch or tag"
"info-disable-guest": "Guest mode disabled"
"info-enable-guest": "Guest mode enabled"
"info-firim-message": "Message from FIR.im"
"info-fork": "Fork"
"info-github-new-event": "Event from GitHub"
"info-gitlab-new-event": "Event from GitLab"
"info-integration-error": "integration error"
"info-issue_comment": "Comment on issue"
"info-issues": "Issues"
"info-jiankongbao-new-event": "Event from Jiankongbao"
"info-jinshuju-new-event": "Event from Jinshuju"
"info-join-room": "Joined topic"
"info-join-team": "Joined team"
"info-leave-room": "Left topic"
"info-leave-team": "Left team"
"info-mention": "mention"
"info-mergeRequest": "Merge"
"info-merge_request": "Merge"
"info-message": "Messages"
"info-new-mail-message": "Shared from email: "
"info-pull_request": "PR"
"info-pull_request_review_comment": "Commit on PR"
"info-push": "Push"
"info-remove-integration": "Removed integration"
"info-repost": "repost"
"info-rss-new-item": "New RSS item:"
"info-topic": "topic"
"info-update-integration": "Updated integration"
"info-update-purpose": "Updated purpose: "
"info-update-topic": "Updated topic: "
"info-weibo-new-comment": "Comment from Weibo:"
"info-weibo-new-mention": "Mention from Weibo:"
"info-weibo-new-repost": "Repost from Weibo:"
"integration-notifications": "Send notifications on these occasions:"
"integrations": "Integrations"
"inte-guide": "User Guide"
"invalid-length": "Invalid content length"
"invite": "Invite"
"invite-members": "Invite members"
"issues": "Issues"
"jiankongbao": "Jiankongbao"
"jiankongbao-url-guide": "Copy this WebHook to your Jiankongbao to use it. You may also find this url in the manager tab."
"jinshuju": "jinshuju.net"
"jinshuju-url-guide": "At the bottom of the page \"Settings -- Data\" you may find \"Sends the data in JSON format to third parties\", fill out the webhook address to receive push notifications."
"join-topic": "Join topic"
"join-survey": "Join in our online survey"
"joined": "Joined"
"jump": "Jump"
"jump-to-origin": "Visit original page"
"just-now": "just now"
"landing-app": "Landing Talk"
"language": "Language"
"last-read-here": "Where you left off"
"left-member": "a member who left"
"login": "Log in"
"login-failed": "Login failed"
"logout": "Logout"
"manage-service": "Manage integrations"
"may-email-conversation": "Talk.ai may email you this conversation"
"me": "Me"
"member": "Member"
"member-menu": "Members Menu"
"members-list": "Members"
"merge": "Merge"
"message-deleter-confirm": "Are you sure about deleting this message?"
"message-deleter-title": "Delete message"
"message-editor-content": "What's the message?"
"message-editor-title": "Edit message"
"message-input-text": "Write something..."
"message-stars": "Message stars"
"message-style": "Message style"
"more-teams": "More teams..."
"more-topics": "More topics"
"name": "Name"
"nature": "Nature"
"need-notification": "Need to select at least one event for notifications"
"need-topic": "Need to specify a topic"
"need-weibo": "Need to bind a Weibo account"
"%s-new-messages": "%s new messages"
"new-topic": "New topic"
"new-version": "Update detected, "
"no-email": "No Email"
"no-matching-results": "No matching topic or member"
"no-more-results": "No more results"
"no-permission": "Only team's owner and administrator can edit!"
"no-phone": "No phone number"
"no-results": "No message found"
"no-more-search-results": "No more search results"
"no-rss-found": "Sorry, no feed it found, please try another link."
"no-starred-messages": "No starred messages"
"not-ready": "Sorry, service is not ready"
"notifications-disabled": "Push notification disabled"
"notification-preferences": " Notification preferences"
"notifications-not-supported": "Desktop notifications is not supported in this browser"
"notify-disabled": "Desktop notification was disabled in browser."
"objects": "Objects"
"on-new-message": "New messages"
"openness": "Openness"
"osx-app": "Mac App"
"other-settings": "Other settings"
"owner": "Owner"
"page-fallback": "Probably wrong link."
"paste-rss-url": "Paste RSS url here"
"people": "People"
"phone": "Phone"
"pin": "Pin"
"places": "Places"
"post": "Post"
"previewerConfirmDelete": "Do you want to delete this file permanently?"
"previewerDeleteFile": "Delete File"
"previewerDownload": "Download"
"previewerDownloadCollection": "Download all"
"previewerDownloadFile": "Download File"
"previewerEnterCollection": "Enter collection"
"previewerFileDeleted": "The file has been deleted."
"previewerMove": "Move"
"previewerOpenLink": "Open Link"
"previewerPictureDeleted": "The picture has been deleted"
"previewerReload": "Click to reload"
"previewerUpdate": "Update"
"private-message": "Private messages"
"push": "Push"
"quit-team": "Quit this team"
"quote-guest": "(Guest)"
"recognizing": "Recognizing"
"recover": "Recover"
"regenerate-guest-link": "Regenerate url"
"remove": "Remove"
"reply-to-mail": "Reply it"
"repost": "Repost"
"reset": "Reset"
"restricted-notifications": "Only direct messages & mentions"
"robot-welcome-note": "I am the assistant from Talk to help you solve problems you might encounter. I also bring you the latest features from Talk."
"room-archived": "Topic is archived by the administrator"
"room-archived-empty": "Sorry, no topic is archived."
"room-disabled": "Guest mode of this topic is disabled"
"room-general": "General"
"room-main-beginning": "This is a general topic, you can broadcast notices from here."
"room-main-contact": "This is the very beginning of your direct message history. Direct messages are private between the two of you."
"room-main-created": "This is topic was created by {{name}} on {{time}}."
"room-main-created2": "This is topic was created by {{name}} on {{time}}. The purpose is \"{{purpose}}\"."
"room-main-desc": "Begin talking"
"room-main-download": "Download our Apps: "
"room-main-history": "All history is here."
"invite-friends": "Invite friends to this topic"
"room-members-invited": "Already Invited"
"room-members-added": "Added team member"
"room-members-already": "Already joined"
"room-members-contact": "Add members"
"room-members-do": "Invite"
"room-members-error": "Failed to send invite"
"room-members-exceed-maximum": "Exceeds maximum email number"
"room-members-exists": "Already joined"
"room-members-hint": "Topic Members"
"room-members-input": "Add and invite other members"
"room-members-invalid": "Not a valid account"
"room-members-members": "Members in this topic"
"room-members-no-contacts": "Add team members that have joined"
"room-members-success": "Invite sent"
"room-messages-loaded": "All messages are loaded"
"room-messages-loading": "Loading history..."
"room-missing": "Topic not found, check your url"
"rss": "RSS"
"rss-required": "RSS url is required!"
"rss-url-invalid": "Url is invalid!"
"rss-url-to-integrate": "Please paste the link you want to subscribe:"
"save": "Save"
"saved": "Saved"
"search-%s": "Search conversations about \"%s\""
"search-with-keywords": "Search"
"send-guest-email": "submit your email"
"service": "Service"
"service-empty": "Integrations service not connected"
"show": "Show"
"show-usage-guide": "Show usage guide"
"side-contacts-invite": "Invite friends"
"side-rooms-header": "Topics list"
"signup": "Sign up"
"slim-default-style": "Slim style"
"someone": "Someone"
"stared-at": "Stared at"
"starred-tip": "Unstar message"
"success": "Success"
"switch-team": "Switch team"
"switch-teams": "Switch teams"
"symbols": "Symbols"
"talk": "Talk"
"talk-to-him": "Talk to him..."
"team": "team"
"team-color": "Team's color"
"team-configs": "Basic informations"
"team-contacts": "Team members"
"team-contacts-admin": "Admin"
"team-contacts-batch-invite": "Batch invite friends"
"team-contacts-batch-invite-link": "Batch invite"
"team-contacts-demote": "Cancel admin"
"team-contacts-do": "Invite"
"team-contacts-guide": "Current members"
"team-contacts-hint": "Team members"
"team-contacts-input": "Invite friends via Email"
"team-contacts-link": "Invite friends to this team via link: "
"team-contacts-member": "Member"
"team-contacts-owner": "Owner"
"team-contacts-promote": "Set as admin"
"team-contacts-remove": "Remove member"
"team-create-hint": "Create a new team"
"team-create-submit": "Create"
"team-created": "New team created"
"team-entrance-create": "Create or join a team"
"team-entrance-invite": "Invite members"
"team-invite-action": "Invite"
"team-invite-header": "Invite your friends to "
"team-invite-input": "Invite friends via Email"
"team-invite-invited": "People invited"
"team-invite-jump": "Jump this step"
"team-invite-know": "People you may know:"
"team-invite-next": "Next"
"team-menu": "Team Menu"
"team-name": "Team's name"
"team-name-placeholder": "A nice name for the team"
"team-rooms-create": "New topic"
"team-rooms-description": "{{name}} created this topic on {{time}}"
"team-rooms-preview": "Preview"
"team-rooms-joined": "Topics already joined"
"team-rooms-more": "More topics to join"
"team-rooms-nomore": "No more topics to join"
"team-settings": "Team settings"
"third-party-services": "Third-party services"
"this-member-left": "This member has left team"
"this-topic": "this topic"
"today": "Today"
"topic": "Topic"
"topic-archive": "Archive topic"
"topic-color": "Topic color"
"topic-configs": "Topic configs"
"topic-create": "Create topic"
"topic-details": "Topic settings"
"topic-leave": "Leave topic"
"topic-remove": "Remove topic"
"topic-remove-member-success": "Member removed from topic"
"topic-list": "Topic list"
"topic-members": "Topic members"
"topic-menu": "Topic menu"
"topic-name": "Topic name"
"topic-name-placeholder": "A name for this topic"
"topic-notifications-preferences": "Push notifications for this topic will be turned on/off on desktop and mobile devices respectively"
"topic-notifications-disabled": "Push notification disabled"
"topic-notifications-enabled": "Push notification enabled"
"topic-purpose": "Topic purpose"
"topic-purpose-placeholder": "Describe the topic"
"topic-required": "Topic is required!"
"topic-settings": "Advanced settings"
"topic-owner": "Topic creator"
"unfold": "Unfold"
"unknown-date": "Unknown date"
"unpin": "Unpin"
"unstarred-tip": "Star message"
"update": "Update"
"upload-files": "Upload files"
"uploader-error": "Failed to upload"
"uploader-error-unauthorized": "Failed to upload. Unauthorized!"
"uploader-files-duplicate": "Files duplicated"
"uploader-files-exceed-number": "Files exceed number limit"
"uploader-files-exceed-size": "Files exceed size limit (1G)"
"uploader-files-limit-size": "Cannot upload multiple files"
"uploader-files-not-accept": "File type is not supported or its size is 0"
"uploader-type-not-allowed": "File type is not supported"
"uploading-file": "Uploading file"
"usage-guide": "Usage guide"
"user-preferences": "Personal preferences"
"user-setting-blocked": "Desktop Notification is blocked in browser"
"user-settings-guide": "New users guide"
"user-settings-show-guide": "Show guide"
"version": "Version"
"visiting-guest": "You are about to visit a topic"
"visiting-topic": "You are about to visit topic \"%s\""
"warning-quit-team": "Once you quit the team, you will not be able to view any of the team chats. Please contact the team administrator if you want to rejoin."
"weibo": "Weibo"
"welcome-to-talk": "Welcome to Talk"
"will-update": "%s seconds later this page will reload"
"wish-talk": "Wish more support?"
"your-name": "Your name"
"join-%s-room": "topic %s joined"
"firim-url-guide": "Copy this WebHook to your Fir.im account to use it. You may also find this url in the manager tab."
"failed-create-integration": "Failed to create integration"
"keep-members-synced": "Sync members"
"enable-syncing": "Enable syncing"
"enable-syncing-tip": "After syncing, the current member list will be completely replaced by %sa, are sure to turn on syncing?"
"disable-syncing": "Disable syncing"
"member-syncing-on": "Member syncing is enable, "
"member-syncing-after": "After turning on syncing, "
"organization": "organization"
"member-syncing": "Member syncing"
"redirect-syncing-member": "Members syncing is on, you can not add or remove members here. Please go to %s in %s. Or you can choose turning off %s."
"filter-members": "Filter members"
"connect-with-webhook": "Connect with WebHooks"
"return-integrations-list": "Back"
"webhook-url": "Webhook Url"
"optional": "Optional"
"custom-name": "Custom name"
"about-custom-name": "Messages from this integration will use this name"
"custom-description": "Custom description"
"about-custom-description": "Description is optional"
"custom-icon-url": "Custom icon"
"about-custom-icon-url": "Upload jpg, png as an icon"
"upload": "Upload"
"save-changes": "Save changes"
"remove-integration": "Remove integration"
"or-comma": "Or, "
"create-a-topic": "Create a topic"
"new-added": "New"
"no-description": "No description"
"current-service-empty": "No connected integrations service in current topic"
"create-topic-success": "Topic created"
"remove-topic-success": "Topic removed"
"incoming-webhooks": "Incoming Webhooks"
"jiankongbao-token": "Jiankongbao Token"
"enter-and-shift": "Shift + Enter for line break, Enter to send"
"rich-text-editor": "Rich text"
"rich-text-editor-placeholder": "Write your content",
"send": "Send"
"show-full-post": "Show full post"
"about-rich-text": "Rich text mode supports long post, text styles, images."
"read-instructions": "Read instructions"
"howto-style-text": "How to add style to text"
"about-post-toolbar": "Write some text, %s, you will see the toolbar"
"selected-text": "select some of them"
"howto-insert-image": "How to insert images"
"insert-image-method-1": "1 Click the image button %s and select an image"
"insert-image-method-2": "2 Drag an image and drop into this box"
"insert-image-method-3": "3 Paste the image into this box"
"no-attachment-here": "Go back and send attachment as a message"
"save-draft": "Save draft"
"read-guide": "Read guide"
"about-incoming-short": "Incoming Webhook makes use of normal HTTP requests with a JSON payload."
"about-weibo-short": "Weibo is one of the most popular social network in China."
"about-rss-short": "RSS automatically syncs the latest site contents."
"about-github-short": "GitHub offers online source code hosting for Git projects."
"about-firim-short": "FIR.im is a beta testing platform that distribute beta versions of your apps and get feedback from users."
"about-gitlab-short": "GitLab is a web-based Git repository manager with wiki and issue tracking features."
"about-coding-short": "Coding.net is a developer-oriented cloud development platform, provides a running space, quality control, providing code hosting, project management, and other functions."
"about-jinshuju-short": "Jinshuju.net is an online form design, data collection, statistics and sharing tools."
"about-jiankongbao-short": "Jiankongbao is able to monitor website, servers, network, database, API, applications, performance, etc."
"about-incoming-long": "Incoming Webhook makes use of normal HTTP requests with a JSON payload. Copy your webhook address to third-party services to configure push notifications."
"about-weibo-long": "Weibo is one of the most popular social network in China. This integration allows you to receive mentions, reposts and replies."
"about-rss-long": "RSS automatically syncs the latest site contents. This integration allows you read RSS feed without leaving Talk."
"about-github-long": "GitHub offers online source code hosting for Git projects. This integration allows you receive GitHub comments, pull request, etc. "
"about-firim-long": "FIR.im is a beta testing platform that distribute beta versions of your apps and get feedback from users. This integration allows you receive notifications from FIR.im."
"about-gitlab-long": "GitLab is a web-based Git repository manager with wiki and issue tracking features. This integration allows you receive notification from GitLab."
"about-coding-long": "Coding.net is a developer-oriented cloud development platform, provides a running space, quality control, providing code hosting, project management, and other functions. When you Git version of the repository on the Coding.net when there is a new Push, you'll catch up on Talk received this Push on and information about the repository."
"about-jinshuju-long": "Jinshuju.net is an online form design, data collection, statistics and sharing tools. Fill in the data form setting Webhook address, you can simply receive new topics within a form to fill out log notification in Talk."
"about-jiankongbao-long": "Jiankongbao is able to monitor website, servers, network, database, API, applications, performance, etc. Add after Jiankongbao aggregation for a topic, you can catch up on Talk received the warning notice."
"add-integrations": "Add integrations"
"start-using-talk": "Start using Talk!"
"join-more-topics": "Join more topics"
"create-topic": "Create topic"
"join": "Join"
"need-to-login": "Request failed, please log in again!"
"windows-app": "Windows client"
"group-is-empty": "This group is empty"
"topped": "Pinned"
"find-by-name": "Find by name"
"find-by-name-or-service": "Find by topic name or integration name"
"integrations-banner": "Talk helps you receive third party notification in one place."
"team-members-syncing": "Team members syncing is enabled, cannot add members."
"no-in-topic": "(Not in topic)"
"previewing-topic": "You haven't joined %s topic yet"
"joined-topic": "Joined topic"
"you-may-invite": "%s,you mentioned %s, but he/she is not in this topic. Would you like to %sinvite him/her to join%s.(Only you can see this message)"
"invite-url-reset": "Reset invite url"
"topic-list-empty": "There are no topics for you to join."
"fail-send-empty": "Failed to send empty message"
"images-only": "[Image]"
"advanced-settings": "Advanced settings"
"attachments-collection": "Attachments collection"
"category-file": "Files"
"category-link": "Links"
"category-post": "Rich text"
"automatic-collection": "Message Types"
"all-positions": "All positions"
"conversation": "Conversation"
"type-keywords": "Enter keywords"
"show-more": "Show more"
"all-types": "All types"
"images": "Images"
"multimedia": "Multimedia"
"documents": "Documents"
"others": "Others"
"link": "Link"
"about-collection": "Files, rich text and links from this topic will automatically appear here."
"rich-text-conversion": "Convert to rich text"
"view-all-members": "View all members"
"search-members": "Search in members"
"search-topics": "Search in topics"
"search-groups": "Search in groups"
"new-message": "New messages."
"topics-to-join": "Topic to join"
"search-%s-in-current-talk": "Search \"%s\" in current talk"
"search-%s-in-all-talk": "Search \"%s\" in all talk"
"search-%s-in-story": "Search \"%s\" in Stories"
"conversation-messages": "Conversation messages"
"file-removed": "File removed"
"api-failed": "API failed"
"token": "Token"
"select-project": "Choose a project"
"on-select-project": "Choose the topic to receive messages"
"project-name": "Project name"
"failed-update-integration": "Failed to configure integration"
"team-prefs-edit": "Edit team preferences"
"hide-mobile-phone": "Hide phone number"
"contact-info": "Phone Number"
"nickname": "Nickname"
"enter-nickname": "Enter a nickname..."
"nickname-setting-tips": "The nickname can replace name displayed in the team"
"or": " or "
"favorite": "Favorite"
"collection": "Favorite"
"my-favorites": "Favorites"
"favorite-page": "Favorite Page"
"favorite-deleter-tip": "confirm delete"
"favorite-placeholder": "Your favorites will show up here."
"favorite-syncing": "Syncing your favorites"
"favorite-syncing-tip": "when added to favorites, the message will automatically save to the related account"
"message-favorited": "message favorited"
"message-favorited-failed": "favorite failed"
"tag-placeholder": "Messages with tags will show up here."
"failed-save-unread": "Failed to save unread information"
"intelligent-response": "Intelligent response"
"open-res-successed": "Opened intelligent response"
"close-res-successed": "Closed intelligent response"
"robot-first-res": "I only speak Chinese at the moment :-("
"no-contact-result": "no contact found"
"no-favorite": "no favorite found"
"no-favorite-tip": "You can add favorites during conversations"
"cancel-favorite": "Cancel this favorite"
"favorite-cancelled": 'Favorite cancelled'
"favorite-cancelled-failed": 'Action failed'
"snippet-editor": "Snippet editor"
"snippet-editor-placeholder": "Code Here..."
"snippet-editor-title-placeholder": "Title"
"post-editor-title-placeholder": "Title"
"snippet-send-empty": "Failed to send empty snippet"
"category-snippet": "Code snippet"
"tag": "Tags"
"open-tag-page": "Show all"
"enter-tag-name": "Enter tag name"
"edit-tags": "Edit Tags"
"edit-tag": "Edit Tag"
"finish-edit": "Finish Editing"
"all-tags": "All"
"tag-name": "Tag Name"
"no-tag": "No tag in current team"
"filter-tag-name": "Enter tag name..."
"save-tag-edit": "Save Changes"
"remove-tag": "Delete Tag"
"add-tag": "Add tags"
"tag-deleter-message": "This tag will be removed from all your messages."
"tag-modify-fail-message": "Existed or invalid tag name"
"no-results-need-keywords": "Change keywords and try again"
"too-long-text-submit": "You have exceeded the 1000 words limit, please send with rich text box"
"text-download-failed": "Failed to load file"
"no-tag-filter": "No filter"
"websocket-reconnect": "Websocket has disconnected, attempting to reconnect ..."
"websocket-end": "Websocket disconnected, please try and refresh the page"
"send-later": "Currently offline, please send later"
"forward": "Forward"
"forward-message": "Forward message"
"forward-number": "Forward (%s)"
"search-for-channel": "Search for topics or contacts"
"success-forwarding-message": "Forward succeeded"
"failed-forwarding-message": "Forward failed"
"complete-personal-profile": "Personal profile"
"setting-rookie": "Add personal profile"
"setting-team-create": "Create Team"
"setting-teams": "Choose Team"
"complete": "Complete"
"enter-your-name": "Enter Your Name"
"enter-team-name": "Team Name"
"create-new-team": "Create new team"
"create-new-team-sub": "Create a team that you own"
"sync-with-teambition": "Sync with Teambition Pro"
"sync-with-teambition-sub": "Sync all Teambition Pro teams to Talk"
"enter": "Enter"
"profile-page": "Profile Setting"
"notify-on-related": "Only direct messages"
"avatar": "Avatar"
"email": "E-Mail"
"teambition": "Teambition"
"contact": "Contact"
"mobile": "Mobile phone"
"bind": "Bind"
"unbind": "Unbind"
"personal-profile": "Personal profile"
"account-binding": "Account"
"display-and-notification": "Display and notification"
"turn-on": "Turn on"
"turn-off": "Turn off"
"edit-avatar": "Edit avatar"
"edit-name": "Edit name"
"edit-contact": "Edit contact"
"edit-email": "Edit e-mail"
"not-binded-teambition": "You haven't connected with any Teambition account"
"not-binded-mobile": "You haven't binded with any phone number"
"email-not-bound": "You haven't binded with any email"
"enter-name": "Enter name"
"enter-contact": "Enter contact"
"enter-email": "Enter e-mail"
"warning": "Warning"
"unbind-warning-confirm": "Are you sure to unbind this account?"
"invite-people": "Invitation"
"enter-mobile-or-email": "Enter phone number or email address"
"not-actived": "Invitee"
"change-mobile-warning": "Are you sure to change binded phone number?"
"setting-team-sync": "Sync from Teambition"
"email-invalid": "Invalid e-mail"
"sync-from-teambition": "After syncing, you can import your teams in Teambition"
"sync-team": "Sync Team"
"sync-team-warning": "Are you sure to sync team \"%s\" from Teambition?"
"sync-teambition-placeholder": "No team yet."
"sync-success": "Sync success"
"sync-fail": "Sync failed"
"team-syncone": "Sync"
"team-syncone-again": "Sync Again"
"teambition-sync-tip": "Member info won't be synced automatically after this syncing, so if anything changed, sync again."
"bind-teambition": "Bind to Teambition"
"unbind-success": "Unbind success"
"unbind-failure": "Unbind failure"
"unbind-teambition-confirm": "Unbind Teambition account"
"unbind-teambition-intro": "After unbinding Teambition account, you will be unable to sign in with Teambition account, but without affect of teams"
"change-mobile-confirm": "Change binded phone number"
"change-mobile-intro": "After changing phone number, you will be unable to sign in with the original, but without affect of teams"
"bind-mobile-confirm": "Bind phone number"
"no-teambition-team": "You have no Teambition team"
"invite-member-to-talk": "Invite members to Talk"
"attachments": "Attachments"
"notify-all": "Notify All"
"notify-related": "Notify Related"
"topic-not-exists": "Topic does not exist"
"force-logout": 'Session timeout, logging out in 3 seconds ...'
"correct-guest-url": "A correct address to guest room should be like:"
"topic-%s-removed": "Topic \"%s\" is being removed."
"removed-from-team-%s": "You are removed from team \"%s\"."
"removed-from-topic-%s": "You are removed from topic \"%s\"."
"topic-%s-archived": "Topic \"%s\" is being archied."
"topic-%s-changed-private": "Topic \"%s\" is changed to a private one."
"file-delete": "File has been deleted"
"message-deleted": "Message has been deleted."
"succeed-removing-invitation": "remove invitation succeed"
"initializing-connection": "Initializing connection..."
"topic-name-existed": "topic name exists"
"rotate-left": "Rotate left"
"rotate-right": "Rotate right"
"page-missing-may-feedback": "Page not found. Send feedback to %s or %s."
"back-to-app": "go back to app"
"feedback": "Feedback"
"room": "Topic"
"create-room": "Create topic"
"filter": "Filter"
"setting": "Setting"
"type-file": "File"
"type-rtf": "RTF"
"type-url": "URL"
"type-snippet": "Snippet"
"info-upload-files": "Upload files"
"channel-placeholder-title": "Created by {{name}} on {{time}}."
"load-more": "Load More"
"loading": "Loading..."
"no-fill-in": "Unknown"
"wrap": "Wrap"
"info-remove-message": "Removed message"
"member-change-done": "Change member success"
"member-change-fail": "Change member failed"
"info-pin-notification": "Pinned the notification"
"info-unpin-notification": "Unpinned the notification"
"info-create-story": "shared a story"
"info-invite-story-member": "invited member"
"info-remove-story-member": "removed member"
"info-update-story": "updated the story"
"info-leave-story": "left"
"info-new-speech": "sent a audio"
"info-invite-you": "invited you"
"launch-jianliao": "Start"
"create-a-story": "You can create a idea."
"find-a-channel": "Find a channel."
"all-channels": "All"
"all-rooms": "Group"
"all-chats": "Member"
"all-stories": "Post"
"more": "More"
"leave-story": "Leave story"
"trash-story": "Delete story"
"manage-member": "Manage member"
"team-shortname": "Team domain name"
"team-shorturl": "Team link"
"team-shortname-placeholder": "Get a nice domain name for team link."
"generate-shorturl": "Generate"
"invalid-team-shortname": "Allows only letters, underscores, hyphens."
"team-qrcode": "QRCode"
"scan-qrcode-to-join": "Scan QRCode to join %s."
"noBinding": "No binded account"
"addBinding": "Add account"
"changeBinding": "Change account"
"send-us-feedback1": "If you have any idea on making Jianliao better, please tell us:"
"send-us-feedback2": ""
"return-visit-email": "Your Email:"
"user-feedback": "Feedback from user"
"manageAccounts": "Manage accounts"
"create-at": "Created on {{time}}"
"update-at": "Updated on {{time}}"
"placeholder-enter-url": "Enter URL"
"placeholder-enter-desc": "Enter description"
"placeholder-enter-title": "Enter title"
"placeholder-enter-filename": "Enter file name"
"no-matching-members": "No matching members"
"no-matching-topics": "No matching topics"
"type-chat": "Chat"
"type-topic": "Topic"
"type-idea": "Idea"
"type-link": "Link"
"reset-form": "Reset"
"create-story": "Create"
"search": "Search"
"publish-at": "Publised on {{time}}"
"team-groups": "Team groups"
"team-group-create": "Create a group"
"team-group-name": "Group name"
"team-group-name-placeholder": "Choose a name"
"team-group-delete-msg": "Delete this group?"
"team-group-name-min-length": "Group name needed"
"team-group-name-max-length": "Group name should be less than 24 characters in length"
"team-group-name-exists": "Group name already exists"
"team-group-no-change": "Nothing changed"
"team-group-placeholder": "No groups yet, only team owner and administrators can create and manage team groups."
"create-group": "Create"
"create": "Create"
"return": "Back"
'shared': 'shared'
"empty-group": "Have no group in this team."
"topic-joined-num": "You have joined {{num}} topics"
"topic-quit-num": "You can join {{num}} topics"
"topic-archived-num": "There are {{num}} archived topics"
"instant-search": "Instant Search"
"empty-contact": "Have no contact in this team."
"everybody": "All"
"invite-member": "Invite member"
"read-link-failure": "Failed to read url"
"private-topic": "Private Topic"
"contacts": "Contacts"
"feedback-success": "Thank you for your feedback, we will take a look at it asap."
"share-story-title-placeholder": "I have an idea to share"
"share-story-desc-placeholder": "Detailed description of your idea"
"share-link-title-placeholder": "Enter or paste a link"
"token-for-validation": "A token for validation"
"channel-main-created": "This post is created by {{name}} at {{time}}."
"info-invite-members": "invite"
"info-remove-members": "remove"
"details": "Details"
"tour-guide-start-button": "Let's go!"
"tour-guide-cancel-button": "No thank you"
"tour-guide-next-button": "Next"
"tour-guide-complete-button": "Talk, start from here."
"tour-guide-start-title": "Talk v3.0, refurbished design and improved features"
"tour-guide-start-text": "Take a look"
"tour-guide-team-sidebar-title": 'Notifications'
"tour-guide-team-sidebar-text": 'A completely new sidebar, all your new notifications will be at the top, making your navigation more efficient. You can use the instant search to quickly find a person to talk to.'
"tour-guide-message-editor-title": 'Message Editor'
"tour-guide-message-editor-text": 'A cleaner message editor. You can send files, rich texts, code snippets or markdowns.'
"tour-guide-launch-button-title": 'Start Talk'
"tour-guide-launch-button-text": 'You can start Talk from here. Join or create an interesting topic, share an idea, or find someone to talk to.'
"robot-id": "Robot id"
"errored-integration": "This integration has an error, please reconfigure: "
"null-target-message": "Sorry, we cannot find this message"
"no-mentions": "No one has mentioned you yet."
"mentioned-me": "Mentions"
"config-github-by": "Configure with WebHook:"
"about-github-webhook": "You may also create a WebHook url to connect GitHub events."
"config-github-manually": "Fill in the table"
"config-github-webhook": "Create a WebHook"
"time-range-one-day": "Last day"
"time-range-one-week": "Last week"
"time-range-one-month": "Last month"
"time-range-quarter": "Last three month"
"enter-hint-tooltip": "Toggle enter method"
"cancel-upload": "Cancel upload"
'member-card-entrance': 'Start conversation'
'member-card-quit-hint': '(Quitted member)'
'return-to-app': 'Return to app'
'not-found-tip': 'Mmm...Have you tried turning it off and on again?'
'contact-us': 'Report an issue'
'read-by': 'Read by'
'read-by-all': 'Read by all'
'talk-home-page': 'Home Page'
'file-preview-error': 'File preview error, please try and download this file'
"activities": "Team Activities"
"info-create-file-story": "shared a file"
"info-create-link-story": "shared a link"
"info-create-room": "create a topic"
"info-create-topic-story": "shared an idea"
"info-invite-team-member": "invited new member"
"invite-new-members": "Invite new members"
"no-activities-yet": "There are no activities yet, maybe create a new topic?"
"team-activities": "Team activities"
"team-description": "Description"
"team-description-placeholder": "Description"
"team-lastest-activities": "Lastest activities from this team"
"team-logo": "Team logo"
"colon": ": "
"forward-menu-team": "Team"
"forward-menu-team-switch": "Switch Team"
'connect-to-trello': 'Connect to Trello'
'loading-failure': 'Failed to load'
'load-again': 'Again'
"help-center": "Help Center"
'delete-activity-confirm': 'Delete this activity?'
'team-info': 'Team Infomation'
| 213317 | module.exports =
"about-guest-email": "If you need to save %s, there will be a record sent to your mailbox。"
"about-guest-talk": "Now you can participate in discussions. As a visitor, you are only allowed to view the page in this conversation."
"about-integrations": "Talk can help you aggregate informations scattered in various places into one place, and facilitate swift access to information, to initiate discussions."
"about-private-topic": "Private topic(only topic members see it)"
"about-public-topic": "Public topic(all members can see it)"
"about-talk": "About Talk"
"add": "Add"
"add-coding": "Add Coding.net"
"add-firim": "Connect to FIR.im"
"add-github": "Connect to GitHub"
"add-gitlab": "Connect to GitLab"
"add-jiankongbao": "Connect Jiankongbao"
"add-jinshuju": "Add jinshuju.net"
"add-rss": "Add RSS"
"add-service": "Add integrations"
"add-weibo": "Add Weibo"
"admin": "Administrator"
"ai-robot": "Talk AI"
"all-members": "All"
"archived-topics": "Archived topics"
"archived-topic": "Archived topic"
"mention": "@me"
"batch-invite-textarea": "Enter emails. Use space, semicolon or newline to divide"
"blog": "Blog"
'by-mail-integrations': 'Integrations by email'
"cancel": "Cancel"
"change": "Change"
"choose-repo": "Choose a GitHub repo:"
"choose-a-topic": "Choose a topic"
"choose-topic": "Choose a topic"
"choose-topic-for-integration": "Choose the topic to connect with:"
"close": "Close"
"coding": "Coding.net"
"coding-url-guide": "Open your project settings on Coding.net, select the WebHook settings, add a WebHook address to your project to receive push notifications."
"comma": ", "
"comment": "Comments"
"comming-soon": "Coming soon"
"config-github": "Config GitHub"
"confirm": "Confirm"
"confirm-adding": "Confirm add"
"confirm-delete-topic": "All records in this topic will be permanently deleted. Confirm to delete."
"confirm-delete-topic-member": "Confirm to remove member."
"connect-to-firim": "Connect to FIR.im:"
"connect-to-github": "Connect to GitHub: "
"connect-to-weibo": "Connect to Weibo: "
"connected": "Network connected, welcome back"
"contact-quitted": "Quitted member"
"create-team": "Create a new team"
"created-updated-time": "created on {{created}}, updated on {{updated}}"
"custom-robot": "Custom Robot"
"custom-service": "Customize service"
"default-default-style": "Default style"
"delete": "Delete"
"desktop-notifications": "Desktop notifications"
"disable–guest-mode": "Disable guest access"
"disable-topic-notifications": "Disable push notification"
"enable-topic-notifications": "Enable push notification"
"dismiss": "Dismiss"
"display-settings": "Display settings"
"dnd-guide": "Drop file here to upload."
"dot": ". "
"douban": "Douban"
"download": "Download"
"download-apps": "Download Apps"
"download-file": "Download file"
"edit": "Edit"
"inte-email": "Email"
"inte-email-details": "More"
"inte-email-select-topic": "Select a topic"
"inte-email-select-topic-description": "or, create one"
"inte-email-address": "Email address"
"inte-email-address-description": "You may send emails to this address to push messages into the selected topic."
"inte-email-ifttt-tutorial": "How to get more integrations through IFTTT."
"inte-email-summary": "Push messages to a specific topic."
"inte-email-description": "Push messages to a specific topic."
"email-%s-message": "You may send emails to %s, which will push messages to this topic"
"email-message": "Send messages with email"
"email-message-%s": "You may send emails to the address below to push messages into %s"
"email-notifications": "Email notifications"
"email-optional": "Email(Optional)"
"emoji-deluxe": "Emoji Deluxe"
"end-of-history": "No more history messages"
"end-of-recent": "No more recent messages"
"error": "Sorry, something error!"
"failed-adding-rss": "Failed to add RSS integration."
"feedback-mail": "Send feedback to "
"fill-in-callback-token": "Fill in with a callback token(optional)"
"fill-repo-name": "account/repo (one that you have the \"write\" permission)"
"firim": "FIR.im"
"fold": "Fold"
"generate-webhook": "Generate WebHook url"
"generate–guest-link": "Generate guest access url"
"github": "GitHub"
"github-title-commit_comment": "Any time a Commit is commented on"
"github-title-create": "Any time a Branch or Tag is created"
"github-title-delete": "Any time a Branch or Tag is deleted"
"github-title-fork": "Any time a Repository is forked"
"github-title-issue_comment": "Any time an Issue is commented on"
"github-title-issues": "Any time an Issue is assigned, unassigned, labelled, unlabelled, opened, closed, or reopened"
"github-title-pull_request": "Any time a Pull Request is assigned, unassigned, labelled, unlabelled, opened, closed, reopened, or synchronized (updated due to a new push in the branch that the pull request is tracking)"
"github-title-pull_request_review_comment": "Any time a Commit is commented on while inside a Pull Request review (the Files Changed tab)"
"github-title-push": "Any Git push to a Repository, including editing tags or branches. Commits via API actions that update references are also counted. This is the default event"
"gitlab": "GitLab"
"gitlab-url-guide": "Copy this WebHook to your GitLab repo to use it. You may also find this url in the manager tab."
"guest-mode": "Guest mode"
"guest-mode-intro": "With Guest mode is turned on, visitors can join the discussion by visiting the url, but they can't see your message history."
"guest-mode-opened": "Guest mode is on. You can turn it off when you finish the conversation."
"guest-views-history": "Guest sees history messages"
"guide-point-contacts": "\"SyncTalk\" is a communication space featured by security and pleasure. Just invite your team member to join the discussion, you are guaranteed away from any disturbance."
"guide-point-guide": "Tip"
"guide-point-members": "Find members in this topic."
"guide-point-switch": "Click here to share your documents with all who have been involved in this topic, or just try to drag you documents into the window directly?"
"guide-point-topic": "To make the discussion more specific, launch various topics for various objects. For instance: “the internal share” or “propaganda plan discussion” etc."
"guide-point-upload": "Click here to create a new team, or just select another team."
"hide": "Hide"
"hide-content": "Hide content"
"history-invisible-to-guests": "Topic history is now hidden from guests"
"history-visible-to-guests": "Topic history is now visible to guests"
"home": "Home"
"html5AudioNotSupport": "You browser does not support this audio"
"html5VideoNotSupport": "You browser does not support this video"
"info-coding-new-event": "Event from Coding.net"
"info-comment": "comment"
"info-commit_comment": "Comment on commit"
"info-create": "Create branch or tag"
"info-create-integration": "Created integration"
"info-created-file": "Uploaded file"
"info-created-snippet": "Created snippet"
"info-created-task": "Created task"
"info-delete": "Delete branch or tag"
"info-disable-guest": "Guest mode disabled"
"info-enable-guest": "Guest mode enabled"
"info-firim-message": "Message from FIR.im"
"info-fork": "Fork"
"info-github-new-event": "Event from GitHub"
"info-gitlab-new-event": "Event from GitLab"
"info-integration-error": "integration error"
"info-issue_comment": "Comment on issue"
"info-issues": "Issues"
"info-jiankongbao-new-event": "Event from Jiankongbao"
"info-jinshuju-new-event": "Event from Jinshuju"
"info-join-room": "Joined topic"
"info-join-team": "Joined team"
"info-leave-room": "Left topic"
"info-leave-team": "Left team"
"info-mention": "mention"
"info-mergeRequest": "Merge"
"info-merge_request": "Merge"
"info-message": "Messages"
"info-new-mail-message": "Shared from email: "
"info-pull_request": "PR"
"info-pull_request_review_comment": "Commit on PR"
"info-push": "Push"
"info-remove-integration": "Removed integration"
"info-repost": "repost"
"info-rss-new-item": "New RSS item:"
"info-topic": "topic"
"info-update-integration": "Updated integration"
"info-update-purpose": "Updated purpose: "
"info-update-topic": "Updated topic: "
"info-weibo-new-comment": "Comment from Weibo:"
"info-weibo-new-mention": "Mention from Weibo:"
"info-weibo-new-repost": "Repost from Weibo:"
"integration-notifications": "Send notifications on these occasions:"
"integrations": "Integrations"
"inte-guide": "User Guide"
"invalid-length": "Invalid content length"
"invite": "Invite"
"invite-members": "Invite members"
"issues": "Issues"
"jiankongbao": "Jiankongbao"
"jiankongbao-url-guide": "Copy this WebHook to your Jiankongbao to use it. You may also find this url in the manager tab."
"jinshuju": "jinshuju.net"
"jinshuju-url-guide": "At the bottom of the page \"Settings -- Data\" you may find \"Sends the data in JSON format to third parties\", fill out the webhook address to receive push notifications."
"join-topic": "Join topic"
"join-survey": "Join in our online survey"
"joined": "Joined"
"jump": "Jump"
"jump-to-origin": "Visit original page"
"just-now": "just now"
"landing-app": "Landing Talk"
"language": "Language"
"last-read-here": "Where you left off"
"left-member": "a member who left"
"login": "Log in"
"login-failed": "Login failed"
"logout": "Logout"
"manage-service": "Manage integrations"
"may-email-conversation": "Talk.ai may email you this conversation"
"me": "Me"
"member": "Member"
"member-menu": "Members Menu"
"members-list": "Members"
"merge": "Merge"
"message-deleter-confirm": "Are you sure about deleting this message?"
"message-deleter-title": "Delete message"
"message-editor-content": "What's the message?"
"message-editor-title": "Edit message"
"message-input-text": "Write something..."
"message-stars": "Message stars"
"message-style": "Message style"
"more-teams": "More teams..."
"more-topics": "More topics"
"name": "Name"
"nature": "Nature"
"need-notification": "Need to select at least one event for notifications"
"need-topic": "Need to specify a topic"
"need-weibo": "Need to bind a Weibo account"
"%s-new-messages": "%s new messages"
"new-topic": "New topic"
"new-version": "Update detected, "
"no-email": "No Email"
"no-matching-results": "No matching topic or member"
"no-more-results": "No more results"
"no-permission": "Only team's owner and administrator can edit!"
"no-phone": "No phone number"
"no-results": "No message found"
"no-more-search-results": "No more search results"
"no-rss-found": "Sorry, no feed it found, please try another link."
"no-starred-messages": "No starred messages"
"not-ready": "Sorry, service is not ready"
"notifications-disabled": "Push notification disabled"
"notification-preferences": " Notification preferences"
"notifications-not-supported": "Desktop notifications is not supported in this browser"
"notify-disabled": "Desktop notification was disabled in browser."
"objects": "Objects"
"on-new-message": "New messages"
"openness": "Openness"
"osx-app": "Mac App"
"other-settings": "Other settings"
"owner": "Owner"
"page-fallback": "Probably wrong link."
"paste-rss-url": "Paste RSS url here"
"people": "People"
"phone": "Phone"
"pin": "Pin"
"places": "Places"
"post": "Post"
"previewerConfirmDelete": "Do you want to delete this file permanently?"
"previewerDeleteFile": "Delete File"
"previewerDownload": "Download"
"previewerDownloadCollection": "Download all"
"previewerDownloadFile": "Download File"
"previewerEnterCollection": "Enter collection"
"previewerFileDeleted": "The file has been deleted."
"previewerMove": "Move"
"previewerOpenLink": "Open Link"
"previewerPictureDeleted": "The picture has been deleted"
"previewerReload": "Click to reload"
"previewerUpdate": "Update"
"private-message": "Private messages"
"push": "Push"
"quit-team": "Quit this team"
"quote-guest": "(Guest)"
"recognizing": "Recognizing"
"recover": "Recover"
"regenerate-guest-link": "Regenerate url"
"remove": "Remove"
"reply-to-mail": "Reply it"
"repost": "Repost"
"reset": "Reset"
"restricted-notifications": "Only direct messages & mentions"
"robot-welcome-note": "I am the assistant from Talk to help you solve problems you might encounter. I also bring you the latest features from Talk."
"room-archived": "Topic is archived by the administrator"
"room-archived-empty": "Sorry, no topic is archived."
"room-disabled": "Guest mode of this topic is disabled"
"room-general": "General"
"room-main-beginning": "This is a general topic, you can broadcast notices from here."
"room-main-contact": "This is the very beginning of your direct message history. Direct messages are private between the two of you."
"room-main-created": "This is topic was created by {{name}} on {{time}}."
"room-main-created2": "This is topic was created by {{name}} on {{time}}. The purpose is \"{{purpose}}\"."
"room-main-desc": "Begin talking"
"room-main-download": "Download our Apps: "
"room-main-history": "All history is here."
"invite-friends": "Invite friends to this topic"
"room-members-invited": "Already Invited"
"room-members-added": "Added team member"
"room-members-already": "Already joined"
"room-members-contact": "Add members"
"room-members-do": "Invite"
"room-members-error": "Failed to send invite"
"room-members-exceed-maximum": "Exceeds maximum email number"
"room-members-exists": "Already joined"
"room-members-hint": "Topic Members"
"room-members-input": "Add and invite other members"
"room-members-invalid": "Not a valid account"
"room-members-members": "Members in this topic"
"room-members-no-contacts": "Add team members that have joined"
"room-members-success": "Invite sent"
"room-messages-loaded": "All messages are loaded"
"room-messages-loading": "Loading history..."
"room-missing": "Topic not found, check your url"
"rss": "RSS"
"rss-required": "RSS url is required!"
"rss-url-invalid": "Url is invalid!"
"rss-url-to-integrate": "Please paste the link you want to subscribe:"
"save": "Save"
"saved": "Saved"
"search-%s": "Search conversations about \"%s\""
"search-with-keywords": "Search"
"send-guest-email": "submit your email"
"service": "Service"
"service-empty": "Integrations service not connected"
"show": "Show"
"show-usage-guide": "Show usage guide"
"side-contacts-invite": "Invite friends"
"side-rooms-header": "Topics list"
"signup": "Sign up"
"slim-default-style": "Slim style"
"someone": "Someone"
"stared-at": "Stared at"
"starred-tip": "Unstar message"
"success": "Success"
"switch-team": "Switch team"
"switch-teams": "Switch teams"
"symbols": "Symbols"
"talk": "Talk"
"talk-to-him": "Talk to him..."
"team": "team"
"team-color": "Team's color"
"team-configs": "Basic informations"
"team-contacts": "Team members"
"team-contacts-admin": "Admin"
"team-contacts-batch-invite": "Batch invite friends"
"team-contacts-batch-invite-link": "Batch invite"
"team-contacts-demote": "Cancel admin"
"team-contacts-do": "Invite"
"team-contacts-guide": "Current members"
"team-contacts-hint": "Team members"
"team-contacts-input": "Invite friends via Email"
"team-contacts-link": "Invite friends to this team via link: "
"team-contacts-member": "Member"
"team-contacts-owner": "Owner"
"team-contacts-promote": "Set as admin"
"team-contacts-remove": "Remove member"
"team-create-hint": "Create a new team"
"team-create-submit": "Create"
"team-created": "New team created"
"team-entrance-create": "Create or join a team"
"team-entrance-invite": "Invite members"
"team-invite-action": "Invite"
"team-invite-header": "Invite your friends to "
"team-invite-input": "Invite friends via Email"
"team-invite-invited": "People invited"
"team-invite-jump": "Jump this step"
"team-invite-know": "People you may know:"
"team-invite-next": "Next"
"team-menu": "Team Menu"
"team-name": "Team's name"
"team-name-placeholder": "A nice name for the team"
"team-rooms-create": "New topic"
"team-rooms-description": "{{name}} created this topic on {{time}}"
"team-rooms-preview": "Preview"
"team-rooms-joined": "Topics already joined"
"team-rooms-more": "More topics to join"
"team-rooms-nomore": "No more topics to join"
"team-settings": "Team settings"
"third-party-services": "Third-party services"
"this-member-left": "This member has left team"
"this-topic": "this topic"
"today": "Today"
"topic": "Topic"
"topic-archive": "Archive topic"
"topic-color": "Topic color"
"topic-configs": "Topic configs"
"topic-create": "Create topic"
"topic-details": "Topic settings"
"topic-leave": "Leave topic"
"topic-remove": "Remove topic"
"topic-remove-member-success": "Member removed from topic"
"topic-list": "Topic list"
"topic-members": "Topic members"
"topic-menu": "Topic menu"
"topic-name": "Topic name"
"topic-name-placeholder": "A name for this topic"
"topic-notifications-preferences": "Push notifications for this topic will be turned on/off on desktop and mobile devices respectively"
"topic-notifications-disabled": "Push notification disabled"
"topic-notifications-enabled": "Push notification enabled"
"topic-purpose": "Topic purpose"
"topic-purpose-placeholder": "Describe the topic"
"topic-required": "Topic is required!"
"topic-settings": "Advanced settings"
"topic-owner": "Topic creator"
"unfold": "Unfold"
"unknown-date": "Unknown date"
"unpin": "Unpin"
"unstarred-tip": "Star message"
"update": "Update"
"upload-files": "Upload files"
"uploader-error": "Failed to upload"
"uploader-error-unauthorized": "Failed to upload. Unauthorized!"
"uploader-files-duplicate": "Files duplicated"
"uploader-files-exceed-number": "Files exceed number limit"
"uploader-files-exceed-size": "Files exceed size limit (1G)"
"uploader-files-limit-size": "Cannot upload multiple files"
"uploader-files-not-accept": "File type is not supported or its size is 0"
"uploader-type-not-allowed": "File type is not supported"
"uploading-file": "Uploading file"
"usage-guide": "Usage guide"
"user-preferences": "Personal preferences"
"user-setting-blocked": "Desktop Notification is blocked in browser"
"user-settings-guide": "New users guide"
"user-settings-show-guide": "Show guide"
"version": "Version"
"visiting-guest": "You are about to visit a topic"
"visiting-topic": "You are about to visit topic \"%s\""
"warning-quit-team": "Once you quit the team, you will not be able to view any of the team chats. Please contact the team administrator if you want to rejoin."
"weibo": "Weibo"
"welcome-to-talk": "Welcome to Talk"
"will-update": "%s seconds later this page will reload"
"wish-talk": "Wish more support?"
"your-name": "Your name"
"join-%s-room": "topic %s joined"
"firim-url-guide": "Copy this WebHook to your Fir.im account to use it. You may also find this url in the manager tab."
"failed-create-integration": "Failed to create integration"
"keep-members-synced": "Sync members"
"enable-syncing": "Enable syncing"
"enable-syncing-tip": "After syncing, the current member list will be completely replaced by %sa, are sure to turn on syncing?"
"disable-syncing": "Disable syncing"
"member-syncing-on": "Member syncing is enable, "
"member-syncing-after": "After turning on syncing, "
"organization": "organization"
"member-syncing": "Member syncing"
"redirect-syncing-member": "Members syncing is on, you can not add or remove members here. Please go to %s in %s. Or you can choose turning off %s."
"filter-members": "Filter members"
"connect-with-webhook": "Connect with WebHooks"
"return-integrations-list": "Back"
"webhook-url": "Webhook Url"
"optional": "Optional"
"custom-name": "Custom name"
"about-custom-name": "Messages from this integration will use this name"
"custom-description": "Custom description"
"about-custom-description": "Description is optional"
"custom-icon-url": "Custom icon"
"about-custom-icon-url": "Upload jpg, png as an icon"
"upload": "Upload"
"save-changes": "Save changes"
"remove-integration": "Remove integration"
"or-comma": "Or, "
"create-a-topic": "Create a topic"
"new-added": "New"
"no-description": "No description"
"current-service-empty": "No connected integrations service in current topic"
"create-topic-success": "Topic created"
"remove-topic-success": "Topic removed"
"incoming-webhooks": "Incoming Webhooks"
"jiankongbao-token": "<KEY> <PASSWORD> <KEY>"
"enter-and-shift": "Shift + Enter for line break, Enter to send"
"rich-text-editor": "Rich text"
"rich-text-editor-placeholder": "Write your content",
"send": "Send"
"show-full-post": "Show full post"
"about-rich-text": "Rich text mode supports long post, text styles, images."
"read-instructions": "Read instructions"
"howto-style-text": "How to add style to text"
"about-post-toolbar": "Write some text, %s, you will see the toolbar"
"selected-text": "select some of them"
"howto-insert-image": "How to insert images"
"insert-image-method-1": "1 Click the image button %s and select an image"
"insert-image-method-2": "2 Drag an image and drop into this box"
"insert-image-method-3": "3 Paste the image into this box"
"no-attachment-here": "Go back and send attachment as a message"
"save-draft": "Save draft"
"read-guide": "Read guide"
"about-incoming-short": "Incoming Webhook makes use of normal HTTP requests with a JSON payload."
"about-weibo-short": "Weibo is one of the most popular social network in China."
"about-rss-short": "RSS automatically syncs the latest site contents."
"about-github-short": "GitHub offers online source code hosting for Git projects."
"about-firim-short": "FIR.im is a beta testing platform that distribute beta versions of your apps and get feedback from users."
"about-gitlab-short": "GitLab is a web-based Git repository manager with wiki and issue tracking features."
"about-coding-short": "Coding.net is a developer-oriented cloud development platform, provides a running space, quality control, providing code hosting, project management, and other functions."
"about-jinshuju-short": "Jinshuju.net is an online form design, data collection, statistics and sharing tools."
"about-jiankongbao-short": "Jiankongbao is able to monitor website, servers, network, database, API, applications, performance, etc."
"about-incoming-long": "Incoming Webhook makes use of normal HTTP requests with a JSON payload. Copy your webhook address to third-party services to configure push notifications."
"about-weibo-long": "Weibo is one of the most popular social network in China. This integration allows you to receive mentions, reposts and replies."
"about-rss-long": "RSS automatically syncs the latest site contents. This integration allows you read RSS feed without leaving Talk."
"about-github-long": "GitHub offers online source code hosting for Git projects. This integration allows you receive GitHub comments, pull request, etc. "
"about-firim-long": "FIR.im is a beta testing platform that distribute beta versions of your apps and get feedback from users. This integration allows you receive notifications from FIR.im."
"about-gitlab-long": "GitLab is a web-based Git repository manager with wiki and issue tracking features. This integration allows you receive notification from GitLab."
"about-coding-long": "Coding.net is a developer-oriented cloud development platform, provides a running space, quality control, providing code hosting, project management, and other functions. When you Git version of the repository on the Coding.net when there is a new Push, you'll catch up on Talk received this Push on and information about the repository."
"about-jinshuju-long": "Jinshuju.net is an online form design, data collection, statistics and sharing tools. Fill in the data form setting Webhook address, you can simply receive new topics within a form to fill out log notification in Talk."
"about-jiankongbao-long": "Jiankongbao is able to monitor website, servers, network, database, API, applications, performance, etc. Add after Jiankongbao aggregation for a topic, you can catch up on Talk received the warning notice."
"add-integrations": "Add integrations"
"start-using-talk": "Start using Talk!"
"join-more-topics": "Join more topics"
"create-topic": "Create topic"
"join": "Join"
"need-to-login": "Request failed, please log in again!"
"windows-app": "Windows client"
"group-is-empty": "This group is empty"
"topped": "Pinned"
"find-by-name": "Find by name"
"find-by-name-or-service": "Find by topic name or integration name"
"integrations-banner": "Talk helps you receive third party notification in one place."
"team-members-syncing": "Team members syncing is enabled, cannot add members."
"no-in-topic": "(Not in topic)"
"previewing-topic": "You haven't joined %s topic yet"
"joined-topic": "Joined topic"
"you-may-invite": "%s,you mentioned %s, but he/she is not in this topic. Would you like to %sinvite him/her to join%s.(Only you can see this message)"
"invite-url-reset": "Reset invite url"
"topic-list-empty": "There are no topics for you to join."
"fail-send-empty": "Failed to send empty message"
"images-only": "[Image]"
"advanced-settings": "Advanced settings"
"attachments-collection": "Attachments collection"
"category-file": "Files"
"category-link": "Links"
"category-post": "Rich text"
"automatic-collection": "Message Types"
"all-positions": "All positions"
"conversation": "Conversation"
"type-keywords": "Enter keywords"
"show-more": "Show more"
"all-types": "All types"
"images": "Images"
"multimedia": "Multimedia"
"documents": "Documents"
"others": "Others"
"link": "Link"
"about-collection": "Files, rich text and links from this topic will automatically appear here."
"rich-text-conversion": "Convert to rich text"
"view-all-members": "View all members"
"search-members": "Search in members"
"search-topics": "Search in topics"
"search-groups": "Search in groups"
"new-message": "New messages."
"topics-to-join": "Topic to join"
"search-%s-in-current-talk": "Search \"%s\" in current talk"
"search-%s-in-all-talk": "Search \"%s\" in all talk"
"search-%s-in-story": "Search \"%s\" in Stories"
"conversation-messages": "Conversation messages"
"file-removed": "File removed"
"api-failed": "API failed"
"token": "Token"
"select-project": "Choose a project"
"on-select-project": "Choose the topic to receive messages"
"project-name": "Project name"
"failed-update-integration": "Failed to configure integration"
"team-prefs-edit": "Edit team preferences"
"hide-mobile-phone": "Hide phone number"
"contact-info": "Phone Number"
"nickname": "Nickname"
"enter-nickname": "Enter a nickname..."
"nickname-setting-tips": "The nickname can replace name displayed in the team"
"or": " or "
"favorite": "Favorite"
"collection": "Favorite"
"my-favorites": "Favorites"
"favorite-page": "Favorite Page"
"favorite-deleter-tip": "confirm delete"
"favorite-placeholder": "Your favorites will show up here."
"favorite-syncing": "Syncing your favorites"
"favorite-syncing-tip": "when added to favorites, the message will automatically save to the related account"
"message-favorited": "message favorited"
"message-favorited-failed": "favorite failed"
"tag-placeholder": "Messages with tags will show up here."
"failed-save-unread": "Failed to save unread information"
"intelligent-response": "Intelligent response"
"open-res-successed": "Opened intelligent response"
"close-res-successed": "Closed intelligent response"
"robot-first-res": "I only speak Chinese at the moment :-("
"no-contact-result": "no contact found"
"no-favorite": "no favorite found"
"no-favorite-tip": "You can add favorites during conversations"
"cancel-favorite": "Cancel this favorite"
"favorite-cancelled": 'Favorite cancelled'
"favorite-cancelled-failed": 'Action failed'
"snippet-editor": "Snippet editor"
"snippet-editor-placeholder": "Code Here..."
"snippet-editor-title-placeholder": "Title"
"post-editor-title-placeholder": "Title"
"snippet-send-empty": "Failed to send empty snippet"
"category-snippet": "Code snippet"
"tag": "Tags"
"open-tag-page": "Show all"
"enter-tag-name": "Enter tag name"
"edit-tags": "Edit Tags"
"edit-tag": "Edit Tag"
"finish-edit": "Finish Editing"
"all-tags": "All"
"tag-name": "Tag Name"
"no-tag": "No tag in current team"
"filter-tag-name": "Enter tag name..."
"save-tag-edit": "Save Changes"
"remove-tag": "Delete Tag"
"add-tag": "Add tags"
"tag-deleter-message": "This tag will be removed from all your messages."
"tag-modify-fail-message": "Existed or invalid tag name"
"no-results-need-keywords": "Change keywords and try again"
"too-long-text-submit": "You have exceeded the 1000 words limit, please send with rich text box"
"text-download-failed": "Failed to load file"
"no-tag-filter": "No filter"
"websocket-reconnect": "Websocket has disconnected, attempting to reconnect ..."
"websocket-end": "Websocket disconnected, please try and refresh the page"
"send-later": "Currently offline, please send later"
"forward": "Forward"
"forward-message": "Forward message"
"forward-number": "Forward (%s)"
"search-for-channel": "Search for topics or contacts"
"success-forwarding-message": "Forward succeeded"
"failed-forwarding-message": "Forward failed"
"complete-personal-profile": "Personal profile"
"setting-rookie": "Add personal profile"
"setting-team-create": "Create Team"
"setting-teams": "Choose Team"
"complete": "Complete"
"enter-your-name": "Enter Your Name"
"enter-team-name": "Team Name"
"create-new-team": "Create new team"
"create-new-team-sub": "Create a team that you own"
"sync-with-teambition": "Sync with Teambition Pro"
"sync-with-teambition-sub": "Sync all Teambition Pro teams to Talk"
"enter": "Enter"
"profile-page": "Profile Setting"
"notify-on-related": "Only direct messages"
"avatar": "Avatar"
"email": "E-Mail"
"teambition": "Teambition"
"contact": "Contact"
"mobile": "Mobile phone"
"bind": "Bind"
"unbind": "Unbind"
"personal-profile": "Personal profile"
"account-binding": "Account"
"display-and-notification": "Display and notification"
"turn-on": "Turn on"
"turn-off": "Turn off"
"edit-avatar": "Edit avatar"
"edit-name": "Edit name"
"edit-contact": "Edit contact"
"edit-email": "Edit e-mail"
"not-binded-teambition": "You haven't connected with any Teambition account"
"not-binded-mobile": "You haven't binded with any phone number"
"email-not-bound": "You haven't binded with any email"
"enter-name": "Enter name"
"enter-contact": "Enter contact"
"enter-email": "Enter e-mail"
"warning": "Warning"
"unbind-warning-confirm": "Are you sure to unbind this account?"
"invite-people": "Invitation"
"enter-mobile-or-email": "Enter phone number or email address"
"not-actived": "Invitee"
"change-mobile-warning": "Are you sure to change binded phone number?"
"setting-team-sync": "Sync from Teambition"
"email-invalid": "Invalid e-mail"
"sync-from-teambition": "After syncing, you can import your teams in Teambition"
"sync-team": "Sync Team"
"sync-team-warning": "Are you sure to sync team \"%s\" from Teambition?"
"sync-teambition-placeholder": "No team yet."
"sync-success": "Sync success"
"sync-fail": "Sync failed"
"team-syncone": "Sync"
"team-syncone-again": "Sync Again"
"teambition-sync-tip": "Member info won't be synced automatically after this syncing, so if anything changed, sync again."
"bind-teambition": "Bind to Teambition"
"unbind-success": "Unbind success"
"unbind-failure": "Unbind failure"
"unbind-teambition-confirm": "Unbind Teambition account"
"unbind-teambition-intro": "After unbinding Teambition account, you will be unable to sign in with Teambition account, but without affect of teams"
"change-mobile-confirm": "Change binded phone number"
"change-mobile-intro": "After changing phone number, you will be unable to sign in with the original, but without affect of teams"
"bind-mobile-confirm": "Bind phone number"
"no-teambition-team": "You have no Teambition team"
"invite-member-to-talk": "Invite members to Talk"
"attachments": "Attachments"
"notify-all": "Notify All"
"notify-related": "Notify Related"
"topic-not-exists": "Topic does not exist"
"force-logout": 'Session timeout, logging out in 3 seconds ...'
"correct-guest-url": "A correct address to guest room should be like:"
"topic-%s-removed": "Topic \"%s\" is being removed."
"removed-from-team-%s": "You are removed from team \"%s\"."
"removed-from-topic-%s": "You are removed from topic \"%s\"."
"topic-%s-archived": "Topic \"%s\" is being archied."
"topic-%s-changed-private": "Topic \"%s\" is changed to a private one."
"file-delete": "File has been deleted"
"message-deleted": "Message has been deleted."
"succeed-removing-invitation": "remove invitation succeed"
"initializing-connection": "Initializing connection..."
"topic-name-existed": "topic name exists"
"rotate-left": "Rotate left"
"rotate-right": "Rotate right"
"page-missing-may-feedback": "Page not found. Send feedback to %s or %s."
"back-to-app": "go back to app"
"feedback": "Feedback"
"room": "Topic"
"create-room": "Create topic"
"filter": "Filter"
"setting": "Setting"
"type-file": "File"
"type-rtf": "RTF"
"type-url": "URL"
"type-snippet": "Snippet"
"info-upload-files": "Upload files"
"channel-placeholder-title": "Created by {{name}} on {{time}}."
"load-more": "Load More"
"loading": "Loading..."
"no-fill-in": "Unknown"
"wrap": "Wrap"
"info-remove-message": "Removed message"
"member-change-done": "Change member success"
"member-change-fail": "Change member failed"
"info-pin-notification": "Pinned the notification"
"info-unpin-notification": "Unpinned the notification"
"info-create-story": "shared a story"
"info-invite-story-member": "invited member"
"info-remove-story-member": "removed member"
"info-update-story": "updated the story"
"info-leave-story": "left"
"info-new-speech": "sent a audio"
"info-invite-you": "invited you"
"launch-jianliao": "Start"
"create-a-story": "You can create a idea."
"find-a-channel": "Find a channel."
"all-channels": "All"
"all-rooms": "Group"
"all-chats": "Member"
"all-stories": "Post"
"more": "More"
"leave-story": "Leave story"
"trash-story": "Delete story"
"manage-member": "Manage member"
"team-shortname": "Team domain name"
"team-shorturl": "Team link"
"team-shortname-placeholder": "Get a nice domain name for team link."
"generate-shorturl": "Generate"
"invalid-team-shortname": "Allows only letters, underscores, hyphens."
"team-qrcode": "QRCode"
"scan-qrcode-to-join": "Scan QRCode to join %s."
"noBinding": "No binded account"
"addBinding": "Add account"
"changeBinding": "Change account"
"send-us-feedback1": "If you have any idea on making Jianliao better, please tell us:"
"send-us-feedback2": ""
"return-visit-email": "Your Email:"
"user-feedback": "Feedback from user"
"manageAccounts": "Manage accounts"
"create-at": "Created on {{time}}"
"update-at": "Updated on {{time}}"
"placeholder-enter-url": "Enter URL"
"placeholder-enter-desc": "Enter description"
"placeholder-enter-title": "Enter title"
"placeholder-enter-filename": "Enter file name"
"no-matching-members": "No matching members"
"no-matching-topics": "No matching topics"
"type-chat": "Chat"
"type-topic": "Topic"
"type-idea": "Idea"
"type-link": "Link"
"reset-form": "Reset"
"create-story": "Create"
"search": "Search"
"publish-at": "Publised on {{time}}"
"team-groups": "Team groups"
"team-group-create": "Create a group"
"team-group-name": "Group name"
"team-group-name-placeholder": "Choose a name"
"team-group-delete-msg": "Delete this group?"
"team-group-name-min-length": "Group name needed"
"team-group-name-max-length": "Group name should be less than 24 characters in length"
"team-group-name-exists": "Group name already exists"
"team-group-no-change": "Nothing changed"
"team-group-placeholder": "No groups yet, only team owner and administrators can create and manage team groups."
"create-group": "Create"
"create": "Create"
"return": "Back"
'shared': 'shared'
"empty-group": "Have no group in this team."
"topic-joined-num": "You have joined {{num}} topics"
"topic-quit-num": "You can join {{num}} topics"
"topic-archived-num": "There are {{num}} archived topics"
"instant-search": "Instant Search"
"empty-contact": "Have no contact in this team."
"everybody": "All"
"invite-member": "Invite member"
"read-link-failure": "Failed to read url"
"private-topic": "Private Topic"
"contacts": "Contacts"
"feedback-success": "Thank you for your feedback, we will take a look at it asap."
"share-story-title-placeholder": "I have an idea to share"
"share-story-desc-placeholder": "Detailed description of your idea"
"share-link-title-placeholder": "Enter or paste a link"
"token-for-validation": "A token for validation"
"channel-main-created": "This post is created by {{name}} at {{time}}."
"info-invite-members": "invite"
"info-remove-members": "remove"
"details": "Details"
"tour-guide-start-button": "Let's go!"
"tour-guide-cancel-button": "No thank you"
"tour-guide-next-button": "Next"
"tour-guide-complete-button": "Talk, start from here."
"tour-guide-start-title": "Talk v3.0, refurbished design and improved features"
"tour-guide-start-text": "Take a look"
"tour-guide-team-sidebar-title": 'Notifications'
"tour-guide-team-sidebar-text": 'A completely new sidebar, all your new notifications will be at the top, making your navigation more efficient. You can use the instant search to quickly find a person to talk to.'
"tour-guide-message-editor-title": 'Message Editor'
"tour-guide-message-editor-text": 'A cleaner message editor. You can send files, rich texts, code snippets or markdowns.'
"tour-guide-launch-button-title": 'Start Talk'
"tour-guide-launch-button-text": 'You can start Talk from here. Join or create an interesting topic, share an idea, or find someone to talk to.'
"robot-id": "Robot id"
"errored-integration": "This integration has an error, please reconfigure: "
"null-target-message": "Sorry, we cannot find this message"
"no-mentions": "No one has mentioned you yet."
"mentioned-me": "Mentions"
"config-github-by": "Configure with WebHook:"
"about-github-webhook": "You may also create a WebHook url to connect GitHub events."
"config-github-manually": "Fill in the table"
"config-github-webhook": "Create a WebHook"
"time-range-one-day": "Last day"
"time-range-one-week": "Last week"
"time-range-one-month": "Last month"
"time-range-quarter": "Last three month"
"enter-hint-tooltip": "Toggle enter method"
"cancel-upload": "Cancel upload"
'member-card-entrance': 'Start conversation'
'member-card-quit-hint': '(Quitted member)'
'return-to-app': 'Return to app'
'not-found-tip': 'Mmm...Have you tried turning it off and on again?'
'contact-us': 'Report an issue'
'read-by': 'Read by'
'read-by-all': 'Read by all'
'talk-home-page': 'Home Page'
'file-preview-error': 'File preview error, please try and download this file'
"activities": "Team Activities"
"info-create-file-story": "shared a file"
"info-create-link-story": "shared a link"
"info-create-room": "create a topic"
"info-create-topic-story": "shared an idea"
"info-invite-team-member": "invited new member"
"invite-new-members": "Invite new members"
"no-activities-yet": "There are no activities yet, maybe create a new topic?"
"team-activities": "Team activities"
"team-description": "Description"
"team-description-placeholder": "Description"
"team-lastest-activities": "Lastest activities from this team"
"team-logo": "Team logo"
"colon": ": "
"forward-menu-team": "Team"
"forward-menu-team-switch": "Switch Team"
'connect-to-trello': 'Connect to Trello'
'loading-failure': 'Failed to load'
'load-again': 'Again'
"help-center": "Help Center"
'delete-activity-confirm': 'Delete this activity?'
'team-info': 'Team Infomation'
| true | module.exports =
"about-guest-email": "If you need to save %s, there will be a record sent to your mailbox。"
"about-guest-talk": "Now you can participate in discussions. As a visitor, you are only allowed to view the page in this conversation."
"about-integrations": "Talk can help you aggregate informations scattered in various places into one place, and facilitate swift access to information, to initiate discussions."
"about-private-topic": "Private topic(only topic members see it)"
"about-public-topic": "Public topic(all members can see it)"
"about-talk": "About Talk"
"add": "Add"
"add-coding": "Add Coding.net"
"add-firim": "Connect to FIR.im"
"add-github": "Connect to GitHub"
"add-gitlab": "Connect to GitLab"
"add-jiankongbao": "Connect Jiankongbao"
"add-jinshuju": "Add jinshuju.net"
"add-rss": "Add RSS"
"add-service": "Add integrations"
"add-weibo": "Add Weibo"
"admin": "Administrator"
"ai-robot": "Talk AI"
"all-members": "All"
"archived-topics": "Archived topics"
"archived-topic": "Archived topic"
"mention": "@me"
"batch-invite-textarea": "Enter emails. Use space, semicolon or newline to divide"
"blog": "Blog"
'by-mail-integrations': 'Integrations by email'
"cancel": "Cancel"
"change": "Change"
"choose-repo": "Choose a GitHub repo:"
"choose-a-topic": "Choose a topic"
"choose-topic": "Choose a topic"
"choose-topic-for-integration": "Choose the topic to connect with:"
"close": "Close"
"coding": "Coding.net"
"coding-url-guide": "Open your project settings on Coding.net, select the WebHook settings, add a WebHook address to your project to receive push notifications."
"comma": ", "
"comment": "Comments"
"comming-soon": "Coming soon"
"config-github": "Config GitHub"
"confirm": "Confirm"
"confirm-adding": "Confirm add"
"confirm-delete-topic": "All records in this topic will be permanently deleted. Confirm to delete."
"confirm-delete-topic-member": "Confirm to remove member."
"connect-to-firim": "Connect to FIR.im:"
"connect-to-github": "Connect to GitHub: "
"connect-to-weibo": "Connect to Weibo: "
"connected": "Network connected, welcome back"
"contact-quitted": "Quitted member"
"create-team": "Create a new team"
"created-updated-time": "created on {{created}}, updated on {{updated}}"
"custom-robot": "Custom Robot"
"custom-service": "Customize service"
"default-default-style": "Default style"
"delete": "Delete"
"desktop-notifications": "Desktop notifications"
"disable–guest-mode": "Disable guest access"
"disable-topic-notifications": "Disable push notification"
"enable-topic-notifications": "Enable push notification"
"dismiss": "Dismiss"
"display-settings": "Display settings"
"dnd-guide": "Drop file here to upload."
"dot": ". "
"douban": "Douban"
"download": "Download"
"download-apps": "Download Apps"
"download-file": "Download file"
"edit": "Edit"
"inte-email": "Email"
"inte-email-details": "More"
"inte-email-select-topic": "Select a topic"
"inte-email-select-topic-description": "or, create one"
"inte-email-address": "Email address"
"inte-email-address-description": "You may send emails to this address to push messages into the selected topic."
"inte-email-ifttt-tutorial": "How to get more integrations through IFTTT."
"inte-email-summary": "Push messages to a specific topic."
"inte-email-description": "Push messages to a specific topic."
"email-%s-message": "You may send emails to %s, which will push messages to this topic"
"email-message": "Send messages with email"
"email-message-%s": "You may send emails to the address below to push messages into %s"
"email-notifications": "Email notifications"
"email-optional": "Email(Optional)"
"emoji-deluxe": "Emoji Deluxe"
"end-of-history": "No more history messages"
"end-of-recent": "No more recent messages"
"error": "Sorry, something error!"
"failed-adding-rss": "Failed to add RSS integration."
"feedback-mail": "Send feedback to "
"fill-in-callback-token": "Fill in with a callback token(optional)"
"fill-repo-name": "account/repo (one that you have the \"write\" permission)"
"firim": "FIR.im"
"fold": "Fold"
"generate-webhook": "Generate WebHook url"
"generate–guest-link": "Generate guest access url"
"github": "GitHub"
"github-title-commit_comment": "Any time a Commit is commented on"
"github-title-create": "Any time a Branch or Tag is created"
"github-title-delete": "Any time a Branch or Tag is deleted"
"github-title-fork": "Any time a Repository is forked"
"github-title-issue_comment": "Any time an Issue is commented on"
"github-title-issues": "Any time an Issue is assigned, unassigned, labelled, unlabelled, opened, closed, or reopened"
"github-title-pull_request": "Any time a Pull Request is assigned, unassigned, labelled, unlabelled, opened, closed, reopened, or synchronized (updated due to a new push in the branch that the pull request is tracking)"
"github-title-pull_request_review_comment": "Any time a Commit is commented on while inside a Pull Request review (the Files Changed tab)"
"github-title-push": "Any Git push to a Repository, including editing tags or branches. Commits via API actions that update references are also counted. This is the default event"
"gitlab": "GitLab"
"gitlab-url-guide": "Copy this WebHook to your GitLab repo to use it. You may also find this url in the manager tab."
"guest-mode": "Guest mode"
"guest-mode-intro": "With Guest mode is turned on, visitors can join the discussion by visiting the url, but they can't see your message history."
"guest-mode-opened": "Guest mode is on. You can turn it off when you finish the conversation."
"guest-views-history": "Guest sees history messages"
"guide-point-contacts": "\"SyncTalk\" is a communication space featured by security and pleasure. Just invite your team member to join the discussion, you are guaranteed away from any disturbance."
"guide-point-guide": "Tip"
"guide-point-members": "Find members in this topic."
"guide-point-switch": "Click here to share your documents with all who have been involved in this topic, or just try to drag you documents into the window directly?"
"guide-point-topic": "To make the discussion more specific, launch various topics for various objects. For instance: “the internal share” or “propaganda plan discussion” etc."
"guide-point-upload": "Click here to create a new team, or just select another team."
"hide": "Hide"
"hide-content": "Hide content"
"history-invisible-to-guests": "Topic history is now hidden from guests"
"history-visible-to-guests": "Topic history is now visible to guests"
"home": "Home"
"html5AudioNotSupport": "You browser does not support this audio"
"html5VideoNotSupport": "You browser does not support this video"
"info-coding-new-event": "Event from Coding.net"
"info-comment": "comment"
"info-commit_comment": "Comment on commit"
"info-create": "Create branch or tag"
"info-create-integration": "Created integration"
"info-created-file": "Uploaded file"
"info-created-snippet": "Created snippet"
"info-created-task": "Created task"
"info-delete": "Delete branch or tag"
"info-disable-guest": "Guest mode disabled"
"info-enable-guest": "Guest mode enabled"
"info-firim-message": "Message from FIR.im"
"info-fork": "Fork"
"info-github-new-event": "Event from GitHub"
"info-gitlab-new-event": "Event from GitLab"
"info-integration-error": "integration error"
"info-issue_comment": "Comment on issue"
"info-issues": "Issues"
"info-jiankongbao-new-event": "Event from Jiankongbao"
"info-jinshuju-new-event": "Event from Jinshuju"
"info-join-room": "Joined topic"
"info-join-team": "Joined team"
"info-leave-room": "Left topic"
"info-leave-team": "Left team"
"info-mention": "mention"
"info-mergeRequest": "Merge"
"info-merge_request": "Merge"
"info-message": "Messages"
"info-new-mail-message": "Shared from email: "
"info-pull_request": "PR"
"info-pull_request_review_comment": "Commit on PR"
"info-push": "Push"
"info-remove-integration": "Removed integration"
"info-repost": "repost"
"info-rss-new-item": "New RSS item:"
"info-topic": "topic"
"info-update-integration": "Updated integration"
"info-update-purpose": "Updated purpose: "
"info-update-topic": "Updated topic: "
"info-weibo-new-comment": "Comment from Weibo:"
"info-weibo-new-mention": "Mention from Weibo:"
"info-weibo-new-repost": "Repost from Weibo:"
"integration-notifications": "Send notifications on these occasions:"
"integrations": "Integrations"
"inte-guide": "User Guide"
"invalid-length": "Invalid content length"
"invite": "Invite"
"invite-members": "Invite members"
"issues": "Issues"
"jiankongbao": "Jiankongbao"
"jiankongbao-url-guide": "Copy this WebHook to your Jiankongbao to use it. You may also find this url in the manager tab."
"jinshuju": "jinshuju.net"
"jinshuju-url-guide": "At the bottom of the page \"Settings -- Data\" you may find \"Sends the data in JSON format to third parties\", fill out the webhook address to receive push notifications."
"join-topic": "Join topic"
"join-survey": "Join in our online survey"
"joined": "Joined"
"jump": "Jump"
"jump-to-origin": "Visit original page"
"just-now": "just now"
"landing-app": "Landing Talk"
"language": "Language"
"last-read-here": "Where you left off"
"left-member": "a member who left"
"login": "Log in"
"login-failed": "Login failed"
"logout": "Logout"
"manage-service": "Manage integrations"
"may-email-conversation": "Talk.ai may email you this conversation"
"me": "Me"
"member": "Member"
"member-menu": "Members Menu"
"members-list": "Members"
"merge": "Merge"
"message-deleter-confirm": "Are you sure about deleting this message?"
"message-deleter-title": "Delete message"
"message-editor-content": "What's the message?"
"message-editor-title": "Edit message"
"message-input-text": "Write something..."
"message-stars": "Message stars"
"message-style": "Message style"
"more-teams": "More teams..."
"more-topics": "More topics"
"name": "Name"
"nature": "Nature"
"need-notification": "Need to select at least one event for notifications"
"need-topic": "Need to specify a topic"
"need-weibo": "Need to bind a Weibo account"
"%s-new-messages": "%s new messages"
"new-topic": "New topic"
"new-version": "Update detected, "
"no-email": "No Email"
"no-matching-results": "No matching topic or member"
"no-more-results": "No more results"
"no-permission": "Only team's owner and administrator can edit!"
"no-phone": "No phone number"
"no-results": "No message found"
"no-more-search-results": "No more search results"
"no-rss-found": "Sorry, no feed it found, please try another link."
"no-starred-messages": "No starred messages"
"not-ready": "Sorry, service is not ready"
"notifications-disabled": "Push notification disabled"
"notification-preferences": " Notification preferences"
"notifications-not-supported": "Desktop notifications is not supported in this browser"
"notify-disabled": "Desktop notification was disabled in browser."
"objects": "Objects"
"on-new-message": "New messages"
"openness": "Openness"
"osx-app": "Mac App"
"other-settings": "Other settings"
"owner": "Owner"
"page-fallback": "Probably wrong link."
"paste-rss-url": "Paste RSS url here"
"people": "People"
"phone": "Phone"
"pin": "Pin"
"places": "Places"
"post": "Post"
"previewerConfirmDelete": "Do you want to delete this file permanently?"
"previewerDeleteFile": "Delete File"
"previewerDownload": "Download"
"previewerDownloadCollection": "Download all"
"previewerDownloadFile": "Download File"
"previewerEnterCollection": "Enter collection"
"previewerFileDeleted": "The file has been deleted."
"previewerMove": "Move"
"previewerOpenLink": "Open Link"
"previewerPictureDeleted": "The picture has been deleted"
"previewerReload": "Click to reload"
"previewerUpdate": "Update"
"private-message": "Private messages"
"push": "Push"
"quit-team": "Quit this team"
"quote-guest": "(Guest)"
"recognizing": "Recognizing"
"recover": "Recover"
"regenerate-guest-link": "Regenerate url"
"remove": "Remove"
"reply-to-mail": "Reply it"
"repost": "Repost"
"reset": "Reset"
"restricted-notifications": "Only direct messages & mentions"
"robot-welcome-note": "I am the assistant from Talk to help you solve problems you might encounter. I also bring you the latest features from Talk."
"room-archived": "Topic is archived by the administrator"
"room-archived-empty": "Sorry, no topic is archived."
"room-disabled": "Guest mode of this topic is disabled"
"room-general": "General"
"room-main-beginning": "This is a general topic, you can broadcast notices from here."
"room-main-contact": "This is the very beginning of your direct message history. Direct messages are private between the two of you."
"room-main-created": "This is topic was created by {{name}} on {{time}}."
"room-main-created2": "This is topic was created by {{name}} on {{time}}. The purpose is \"{{purpose}}\"."
"room-main-desc": "Begin talking"
"room-main-download": "Download our Apps: "
"room-main-history": "All history is here."
"invite-friends": "Invite friends to this topic"
"room-members-invited": "Already Invited"
"room-members-added": "Added team member"
"room-members-already": "Already joined"
"room-members-contact": "Add members"
"room-members-do": "Invite"
"room-members-error": "Failed to send invite"
"room-members-exceed-maximum": "Exceeds maximum email number"
"room-members-exists": "Already joined"
"room-members-hint": "Topic Members"
"room-members-input": "Add and invite other members"
"room-members-invalid": "Not a valid account"
"room-members-members": "Members in this topic"
"room-members-no-contacts": "Add team members that have joined"
"room-members-success": "Invite sent"
"room-messages-loaded": "All messages are loaded"
"room-messages-loading": "Loading history..."
"room-missing": "Topic not found, check your url"
"rss": "RSS"
"rss-required": "RSS url is required!"
"rss-url-invalid": "Url is invalid!"
"rss-url-to-integrate": "Please paste the link you want to subscribe:"
"save": "Save"
"saved": "Saved"
"search-%s": "Search conversations about \"%s\""
"search-with-keywords": "Search"
"send-guest-email": "submit your email"
"service": "Service"
"service-empty": "Integrations service not connected"
"show": "Show"
"show-usage-guide": "Show usage guide"
"side-contacts-invite": "Invite friends"
"side-rooms-header": "Topics list"
"signup": "Sign up"
"slim-default-style": "Slim style"
"someone": "Someone"
"stared-at": "Stared at"
"starred-tip": "Unstar message"
"success": "Success"
"switch-team": "Switch team"
"switch-teams": "Switch teams"
"symbols": "Symbols"
"talk": "Talk"
"talk-to-him": "Talk to him..."
"team": "team"
"team-color": "Team's color"
"team-configs": "Basic informations"
"team-contacts": "Team members"
"team-contacts-admin": "Admin"
"team-contacts-batch-invite": "Batch invite friends"
"team-contacts-batch-invite-link": "Batch invite"
"team-contacts-demote": "Cancel admin"
"team-contacts-do": "Invite"
"team-contacts-guide": "Current members"
"team-contacts-hint": "Team members"
"team-contacts-input": "Invite friends via Email"
"team-contacts-link": "Invite friends to this team via link: "
"team-contacts-member": "Member"
"team-contacts-owner": "Owner"
"team-contacts-promote": "Set as admin"
"team-contacts-remove": "Remove member"
"team-create-hint": "Create a new team"
"team-create-submit": "Create"
"team-created": "New team created"
"team-entrance-create": "Create or join a team"
"team-entrance-invite": "Invite members"
"team-invite-action": "Invite"
"team-invite-header": "Invite your friends to "
"team-invite-input": "Invite friends via Email"
"team-invite-invited": "People invited"
"team-invite-jump": "Jump this step"
"team-invite-know": "People you may know:"
"team-invite-next": "Next"
"team-menu": "Team Menu"
"team-name": "Team's name"
"team-name-placeholder": "A nice name for the team"
"team-rooms-create": "New topic"
"team-rooms-description": "{{name}} created this topic on {{time}}"
"team-rooms-preview": "Preview"
"team-rooms-joined": "Topics already joined"
"team-rooms-more": "More topics to join"
"team-rooms-nomore": "No more topics to join"
"team-settings": "Team settings"
"third-party-services": "Third-party services"
"this-member-left": "This member has left team"
"this-topic": "this topic"
"today": "Today"
"topic": "Topic"
"topic-archive": "Archive topic"
"topic-color": "Topic color"
"topic-configs": "Topic configs"
"topic-create": "Create topic"
"topic-details": "Topic settings"
"topic-leave": "Leave topic"
"topic-remove": "Remove topic"
"topic-remove-member-success": "Member removed from topic"
"topic-list": "Topic list"
"topic-members": "Topic members"
"topic-menu": "Topic menu"
"topic-name": "Topic name"
"topic-name-placeholder": "A name for this topic"
"topic-notifications-preferences": "Push notifications for this topic will be turned on/off on desktop and mobile devices respectively"
"topic-notifications-disabled": "Push notification disabled"
"topic-notifications-enabled": "Push notification enabled"
"topic-purpose": "Topic purpose"
"topic-purpose-placeholder": "Describe the topic"
"topic-required": "Topic is required!"
"topic-settings": "Advanced settings"
"topic-owner": "Topic creator"
"unfold": "Unfold"
"unknown-date": "Unknown date"
"unpin": "Unpin"
"unstarred-tip": "Star message"
"update": "Update"
"upload-files": "Upload files"
"uploader-error": "Failed to upload"
"uploader-error-unauthorized": "Failed to upload. Unauthorized!"
"uploader-files-duplicate": "Files duplicated"
"uploader-files-exceed-number": "Files exceed number limit"
"uploader-files-exceed-size": "Files exceed size limit (1G)"
"uploader-files-limit-size": "Cannot upload multiple files"
"uploader-files-not-accept": "File type is not supported or its size is 0"
"uploader-type-not-allowed": "File type is not supported"
"uploading-file": "Uploading file"
"usage-guide": "Usage guide"
"user-preferences": "Personal preferences"
"user-setting-blocked": "Desktop Notification is blocked in browser"
"user-settings-guide": "New users guide"
"user-settings-show-guide": "Show guide"
"version": "Version"
"visiting-guest": "You are about to visit a topic"
"visiting-topic": "You are about to visit topic \"%s\""
"warning-quit-team": "Once you quit the team, you will not be able to view any of the team chats. Please contact the team administrator if you want to rejoin."
"weibo": "Weibo"
"welcome-to-talk": "Welcome to Talk"
"will-update": "%s seconds later this page will reload"
"wish-talk": "Wish more support?"
"your-name": "Your name"
"join-%s-room": "topic %s joined"
"firim-url-guide": "Copy this WebHook to your Fir.im account to use it. You may also find this url in the manager tab."
"failed-create-integration": "Failed to create integration"
"keep-members-synced": "Sync members"
"enable-syncing": "Enable syncing"
"enable-syncing-tip": "After syncing, the current member list will be completely replaced by %sa, are sure to turn on syncing?"
"disable-syncing": "Disable syncing"
"member-syncing-on": "Member syncing is enable, "
"member-syncing-after": "After turning on syncing, "
"organization": "organization"
"member-syncing": "Member syncing"
"redirect-syncing-member": "Members syncing is on, you can not add or remove members here. Please go to %s in %s. Or you can choose turning off %s."
"filter-members": "Filter members"
"connect-with-webhook": "Connect with WebHooks"
"return-integrations-list": "Back"
"webhook-url": "Webhook Url"
"optional": "Optional"
"custom-name": "Custom name"
"about-custom-name": "Messages from this integration will use this name"
"custom-description": "Custom description"
"about-custom-description": "Description is optional"
"custom-icon-url": "Custom icon"
"about-custom-icon-url": "Upload jpg, png as an icon"
"upload": "Upload"
"save-changes": "Save changes"
"remove-integration": "Remove integration"
"or-comma": "Or, "
"create-a-topic": "Create a topic"
"new-added": "New"
"no-description": "No description"
"current-service-empty": "No connected integrations service in current topic"
"create-topic-success": "Topic created"
"remove-topic-success": "Topic removed"
"incoming-webhooks": "Incoming Webhooks"
"jiankongbao-token": "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI"
"enter-and-shift": "Shift + Enter for line break, Enter to send"
"rich-text-editor": "Rich text"
"rich-text-editor-placeholder": "Write your content",
"send": "Send"
"show-full-post": "Show full post"
"about-rich-text": "Rich text mode supports long post, text styles, images."
"read-instructions": "Read instructions"
"howto-style-text": "How to add style to text"
"about-post-toolbar": "Write some text, %s, you will see the toolbar"
"selected-text": "select some of them"
"howto-insert-image": "How to insert images"
"insert-image-method-1": "1 Click the image button %s and select an image"
"insert-image-method-2": "2 Drag an image and drop into this box"
"insert-image-method-3": "3 Paste the image into this box"
"no-attachment-here": "Go back and send attachment as a message"
"save-draft": "Save draft"
"read-guide": "Read guide"
"about-incoming-short": "Incoming Webhook makes use of normal HTTP requests with a JSON payload."
"about-weibo-short": "Weibo is one of the most popular social network in China."
"about-rss-short": "RSS automatically syncs the latest site contents."
"about-github-short": "GitHub offers online source code hosting for Git projects."
"about-firim-short": "FIR.im is a beta testing platform that distribute beta versions of your apps and get feedback from users."
"about-gitlab-short": "GitLab is a web-based Git repository manager with wiki and issue tracking features."
"about-coding-short": "Coding.net is a developer-oriented cloud development platform, provides a running space, quality control, providing code hosting, project management, and other functions."
"about-jinshuju-short": "Jinshuju.net is an online form design, data collection, statistics and sharing tools."
"about-jiankongbao-short": "Jiankongbao is able to monitor website, servers, network, database, API, applications, performance, etc."
"about-incoming-long": "Incoming Webhook makes use of normal HTTP requests with a JSON payload. Copy your webhook address to third-party services to configure push notifications."
"about-weibo-long": "Weibo is one of the most popular social network in China. This integration allows you to receive mentions, reposts and replies."
"about-rss-long": "RSS automatically syncs the latest site contents. This integration allows you read RSS feed without leaving Talk."
"about-github-long": "GitHub offers online source code hosting for Git projects. This integration allows you receive GitHub comments, pull request, etc. "
"about-firim-long": "FIR.im is a beta testing platform that distribute beta versions of your apps and get feedback from users. This integration allows you receive notifications from FIR.im."
"about-gitlab-long": "GitLab is a web-based Git repository manager with wiki and issue tracking features. This integration allows you receive notification from GitLab."
"about-coding-long": "Coding.net is a developer-oriented cloud development platform, provides a running space, quality control, providing code hosting, project management, and other functions. When you Git version of the repository on the Coding.net when there is a new Push, you'll catch up on Talk received this Push on and information about the repository."
"about-jinshuju-long": "Jinshuju.net is an online form design, data collection, statistics and sharing tools. Fill in the data form setting Webhook address, you can simply receive new topics within a form to fill out log notification in Talk."
"about-jiankongbao-long": "Jiankongbao is able to monitor website, servers, network, database, API, applications, performance, etc. Add after Jiankongbao aggregation for a topic, you can catch up on Talk received the warning notice."
"add-integrations": "Add integrations"
"start-using-talk": "Start using Talk!"
"join-more-topics": "Join more topics"
"create-topic": "Create topic"
"join": "Join"
"need-to-login": "Request failed, please log in again!"
"windows-app": "Windows client"
"group-is-empty": "This group is empty"
"topped": "Pinned"
"find-by-name": "Find by name"
"find-by-name-or-service": "Find by topic name or integration name"
"integrations-banner": "Talk helps you receive third party notification in one place."
"team-members-syncing": "Team members syncing is enabled, cannot add members."
"no-in-topic": "(Not in topic)"
"previewing-topic": "You haven't joined %s topic yet"
"joined-topic": "Joined topic"
"you-may-invite": "%s,you mentioned %s, but he/she is not in this topic. Would you like to %sinvite him/her to join%s.(Only you can see this message)"
"invite-url-reset": "Reset invite url"
"topic-list-empty": "There are no topics for you to join."
"fail-send-empty": "Failed to send empty message"
"images-only": "[Image]"
"advanced-settings": "Advanced settings"
"attachments-collection": "Attachments collection"
"category-file": "Files"
"category-link": "Links"
"category-post": "Rich text"
"automatic-collection": "Message Types"
"all-positions": "All positions"
"conversation": "Conversation"
"type-keywords": "Enter keywords"
"show-more": "Show more"
"all-types": "All types"
"images": "Images"
"multimedia": "Multimedia"
"documents": "Documents"
"others": "Others"
"link": "Link"
"about-collection": "Files, rich text and links from this topic will automatically appear here."
"rich-text-conversion": "Convert to rich text"
"view-all-members": "View all members"
"search-members": "Search in members"
"search-topics": "Search in topics"
"search-groups": "Search in groups"
"new-message": "New messages."
"topics-to-join": "Topic to join"
"search-%s-in-current-talk": "Search \"%s\" in current talk"
"search-%s-in-all-talk": "Search \"%s\" in all talk"
"search-%s-in-story": "Search \"%s\" in Stories"
"conversation-messages": "Conversation messages"
"file-removed": "File removed"
"api-failed": "API failed"
"token": "Token"
"select-project": "Choose a project"
"on-select-project": "Choose the topic to receive messages"
"project-name": "Project name"
"failed-update-integration": "Failed to configure integration"
"team-prefs-edit": "Edit team preferences"
"hide-mobile-phone": "Hide phone number"
"contact-info": "Phone Number"
"nickname": "Nickname"
"enter-nickname": "Enter a nickname..."
"nickname-setting-tips": "The nickname can replace name displayed in the team"
"or": " or "
"favorite": "Favorite"
"collection": "Favorite"
"my-favorites": "Favorites"
"favorite-page": "Favorite Page"
"favorite-deleter-tip": "confirm delete"
"favorite-placeholder": "Your favorites will show up here."
"favorite-syncing": "Syncing your favorites"
"favorite-syncing-tip": "when added to favorites, the message will automatically save to the related account"
"message-favorited": "message favorited"
"message-favorited-failed": "favorite failed"
"tag-placeholder": "Messages with tags will show up here."
"failed-save-unread": "Failed to save unread information"
"intelligent-response": "Intelligent response"
"open-res-successed": "Opened intelligent response"
"close-res-successed": "Closed intelligent response"
"robot-first-res": "I only speak Chinese at the moment :-("
"no-contact-result": "no contact found"
"no-favorite": "no favorite found"
"no-favorite-tip": "You can add favorites during conversations"
"cancel-favorite": "Cancel this favorite"
"favorite-cancelled": 'Favorite cancelled'
"favorite-cancelled-failed": 'Action failed'
"snippet-editor": "Snippet editor"
"snippet-editor-placeholder": "Code Here..."
"snippet-editor-title-placeholder": "Title"
"post-editor-title-placeholder": "Title"
"snippet-send-empty": "Failed to send empty snippet"
"category-snippet": "Code snippet"
"tag": "Tags"
"open-tag-page": "Show all"
"enter-tag-name": "Enter tag name"
"edit-tags": "Edit Tags"
"edit-tag": "Edit Tag"
"finish-edit": "Finish Editing"
"all-tags": "All"
"tag-name": "Tag Name"
"no-tag": "No tag in current team"
"filter-tag-name": "Enter tag name..."
"save-tag-edit": "Save Changes"
"remove-tag": "Delete Tag"
"add-tag": "Add tags"
"tag-deleter-message": "This tag will be removed from all your messages."
"tag-modify-fail-message": "Existed or invalid tag name"
"no-results-need-keywords": "Change keywords and try again"
"too-long-text-submit": "You have exceeded the 1000 words limit, please send with rich text box"
"text-download-failed": "Failed to load file"
"no-tag-filter": "No filter"
"websocket-reconnect": "Websocket has disconnected, attempting to reconnect ..."
"websocket-end": "Websocket disconnected, please try and refresh the page"
"send-later": "Currently offline, please send later"
"forward": "Forward"
"forward-message": "Forward message"
"forward-number": "Forward (%s)"
"search-for-channel": "Search for topics or contacts"
"success-forwarding-message": "Forward succeeded"
"failed-forwarding-message": "Forward failed"
"complete-personal-profile": "Personal profile"
"setting-rookie": "Add personal profile"
"setting-team-create": "Create Team"
"setting-teams": "Choose Team"
"complete": "Complete"
"enter-your-name": "Enter Your Name"
"enter-team-name": "Team Name"
"create-new-team": "Create new team"
"create-new-team-sub": "Create a team that you own"
"sync-with-teambition": "Sync with Teambition Pro"
"sync-with-teambition-sub": "Sync all Teambition Pro teams to Talk"
"enter": "Enter"
"profile-page": "Profile Setting"
"notify-on-related": "Only direct messages"
"avatar": "Avatar"
"email": "E-Mail"
"teambition": "Teambition"
"contact": "Contact"
"mobile": "Mobile phone"
"bind": "Bind"
"unbind": "Unbind"
"personal-profile": "Personal profile"
"account-binding": "Account"
"display-and-notification": "Display and notification"
"turn-on": "Turn on"
"turn-off": "Turn off"
"edit-avatar": "Edit avatar"
"edit-name": "Edit name"
"edit-contact": "Edit contact"
"edit-email": "Edit e-mail"
"not-binded-teambition": "You haven't connected with any Teambition account"
"not-binded-mobile": "You haven't binded with any phone number"
"email-not-bound": "You haven't binded with any email"
"enter-name": "Enter name"
"enter-contact": "Enter contact"
"enter-email": "Enter e-mail"
"warning": "Warning"
"unbind-warning-confirm": "Are you sure to unbind this account?"
"invite-people": "Invitation"
"enter-mobile-or-email": "Enter phone number or email address"
"not-actived": "Invitee"
"change-mobile-warning": "Are you sure to change binded phone number?"
"setting-team-sync": "Sync from Teambition"
"email-invalid": "Invalid e-mail"
"sync-from-teambition": "After syncing, you can import your teams in Teambition"
"sync-team": "Sync Team"
"sync-team-warning": "Are you sure to sync team \"%s\" from Teambition?"
"sync-teambition-placeholder": "No team yet."
"sync-success": "Sync success"
"sync-fail": "Sync failed"
"team-syncone": "Sync"
"team-syncone-again": "Sync Again"
"teambition-sync-tip": "Member info won't be synced automatically after this syncing, so if anything changed, sync again."
"bind-teambition": "Bind to Teambition"
"unbind-success": "Unbind success"
"unbind-failure": "Unbind failure"
"unbind-teambition-confirm": "Unbind Teambition account"
"unbind-teambition-intro": "After unbinding Teambition account, you will be unable to sign in with Teambition account, but without affect of teams"
"change-mobile-confirm": "Change binded phone number"
"change-mobile-intro": "After changing phone number, you will be unable to sign in with the original, but without affect of teams"
"bind-mobile-confirm": "Bind phone number"
"no-teambition-team": "You have no Teambition team"
"invite-member-to-talk": "Invite members to Talk"
"attachments": "Attachments"
"notify-all": "Notify All"
"notify-related": "Notify Related"
"topic-not-exists": "Topic does not exist"
"force-logout": 'Session timeout, logging out in 3 seconds ...'
"correct-guest-url": "A correct address to guest room should be like:"
"topic-%s-removed": "Topic \"%s\" is being removed."
"removed-from-team-%s": "You are removed from team \"%s\"."
"removed-from-topic-%s": "You are removed from topic \"%s\"."
"topic-%s-archived": "Topic \"%s\" is being archied."
"topic-%s-changed-private": "Topic \"%s\" is changed to a private one."
"file-delete": "File has been deleted"
"message-deleted": "Message has been deleted."
"succeed-removing-invitation": "remove invitation succeed"
"initializing-connection": "Initializing connection..."
"topic-name-existed": "topic name exists"
"rotate-left": "Rotate left"
"rotate-right": "Rotate right"
"page-missing-may-feedback": "Page not found. Send feedback to %s or %s."
"back-to-app": "go back to app"
"feedback": "Feedback"
"room": "Topic"
"create-room": "Create topic"
"filter": "Filter"
"setting": "Setting"
"type-file": "File"
"type-rtf": "RTF"
"type-url": "URL"
"type-snippet": "Snippet"
"info-upload-files": "Upload files"
"channel-placeholder-title": "Created by {{name}} on {{time}}."
"load-more": "Load More"
"loading": "Loading..."
"no-fill-in": "Unknown"
"wrap": "Wrap"
"info-remove-message": "Removed message"
"member-change-done": "Change member success"
"member-change-fail": "Change member failed"
"info-pin-notification": "Pinned the notification"
"info-unpin-notification": "Unpinned the notification"
"info-create-story": "shared a story"
"info-invite-story-member": "invited member"
"info-remove-story-member": "removed member"
"info-update-story": "updated the story"
"info-leave-story": "left"
"info-new-speech": "sent a audio"
"info-invite-you": "invited you"
"launch-jianliao": "Start"
"create-a-story": "You can create a idea."
"find-a-channel": "Find a channel."
"all-channels": "All"
"all-rooms": "Group"
"all-chats": "Member"
"all-stories": "Post"
"more": "More"
"leave-story": "Leave story"
"trash-story": "Delete story"
"manage-member": "Manage member"
"team-shortname": "Team domain name"
"team-shorturl": "Team link"
"team-shortname-placeholder": "Get a nice domain name for team link."
"generate-shorturl": "Generate"
"invalid-team-shortname": "Allows only letters, underscores, hyphens."
"team-qrcode": "QRCode"
"scan-qrcode-to-join": "Scan QRCode to join %s."
"noBinding": "No binded account"
"addBinding": "Add account"
"changeBinding": "Change account"
"send-us-feedback1": "If you have any idea on making Jianliao better, please tell us:"
"send-us-feedback2": ""
"return-visit-email": "Your Email:"
"user-feedback": "Feedback from user"
"manageAccounts": "Manage accounts"
"create-at": "Created on {{time}}"
"update-at": "Updated on {{time}}"
"placeholder-enter-url": "Enter URL"
"placeholder-enter-desc": "Enter description"
"placeholder-enter-title": "Enter title"
"placeholder-enter-filename": "Enter file name"
"no-matching-members": "No matching members"
"no-matching-topics": "No matching topics"
"type-chat": "Chat"
"type-topic": "Topic"
"type-idea": "Idea"
"type-link": "Link"
"reset-form": "Reset"
"create-story": "Create"
"search": "Search"
"publish-at": "Publised on {{time}}"
"team-groups": "Team groups"
"team-group-create": "Create a group"
"team-group-name": "Group name"
"team-group-name-placeholder": "Choose a name"
"team-group-delete-msg": "Delete this group?"
"team-group-name-min-length": "Group name needed"
"team-group-name-max-length": "Group name should be less than 24 characters in length"
"team-group-name-exists": "Group name already exists"
"team-group-no-change": "Nothing changed"
"team-group-placeholder": "No groups yet, only team owner and administrators can create and manage team groups."
"create-group": "Create"
"create": "Create"
"return": "Back"
'shared': 'shared'
"empty-group": "Have no group in this team."
"topic-joined-num": "You have joined {{num}} topics"
"topic-quit-num": "You can join {{num}} topics"
"topic-archived-num": "There are {{num}} archived topics"
"instant-search": "Instant Search"
"empty-contact": "Have no contact in this team."
"everybody": "All"
"invite-member": "Invite member"
"read-link-failure": "Failed to read url"
"private-topic": "Private Topic"
"contacts": "Contacts"
"feedback-success": "Thank you for your feedback, we will take a look at it asap."
"share-story-title-placeholder": "I have an idea to share"
"share-story-desc-placeholder": "Detailed description of your idea"
"share-link-title-placeholder": "Enter or paste a link"
"token-for-validation": "A token for validation"
"channel-main-created": "This post is created by {{name}} at {{time}}."
"info-invite-members": "invite"
"info-remove-members": "remove"
"details": "Details"
"tour-guide-start-button": "Let's go!"
"tour-guide-cancel-button": "No thank you"
"tour-guide-next-button": "Next"
"tour-guide-complete-button": "Talk, start from here."
"tour-guide-start-title": "Talk v3.0, refurbished design and improved features"
"tour-guide-start-text": "Take a look"
"tour-guide-team-sidebar-title": 'Notifications'
"tour-guide-team-sidebar-text": 'A completely new sidebar, all your new notifications will be at the top, making your navigation more efficient. You can use the instant search to quickly find a person to talk to.'
"tour-guide-message-editor-title": 'Message Editor'
"tour-guide-message-editor-text": 'A cleaner message editor. You can send files, rich texts, code snippets or markdowns.'
"tour-guide-launch-button-title": 'Start Talk'
"tour-guide-launch-button-text": 'You can start Talk from here. Join or create an interesting topic, share an idea, or find someone to talk to.'
"robot-id": "Robot id"
"errored-integration": "This integration has an error, please reconfigure: "
"null-target-message": "Sorry, we cannot find this message"
"no-mentions": "No one has mentioned you yet."
"mentioned-me": "Mentions"
"config-github-by": "Configure with WebHook:"
"about-github-webhook": "You may also create a WebHook url to connect GitHub events."
"config-github-manually": "Fill in the table"
"config-github-webhook": "Create a WebHook"
"time-range-one-day": "Last day"
"time-range-one-week": "Last week"
"time-range-one-month": "Last month"
"time-range-quarter": "Last three month"
"enter-hint-tooltip": "Toggle enter method"
"cancel-upload": "Cancel upload"
'member-card-entrance': 'Start conversation'
'member-card-quit-hint': '(Quitted member)'
'return-to-app': 'Return to app'
'not-found-tip': 'Mmm...Have you tried turning it off and on again?'
'contact-us': 'Report an issue'
'read-by': 'Read by'
'read-by-all': 'Read by all'
'talk-home-page': 'Home Page'
'file-preview-error': 'File preview error, please try and download this file'
"activities": "Team Activities"
"info-create-file-story": "shared a file"
"info-create-link-story": "shared a link"
"info-create-room": "create a topic"
"info-create-topic-story": "shared an idea"
"info-invite-team-member": "invited new member"
"invite-new-members": "Invite new members"
"no-activities-yet": "There are no activities yet, maybe create a new topic?"
"team-activities": "Team activities"
"team-description": "Description"
"team-description-placeholder": "Description"
"team-lastest-activities": "Lastest activities from this team"
"team-logo": "Team logo"
"colon": ": "
"forward-menu-team": "Team"
"forward-menu-team-switch": "Switch Team"
'connect-to-trello': 'Connect to Trello'
'loading-failure': 'Failed to load'
'load-again': 'Again'
"help-center": "Help Center"
'delete-activity-confirm': 'Delete this activity?'
'team-info': 'Team Infomation'
|
[
{
"context": " name\"\"\"\n\n # https://api.spotify.com/v1/search?q=Ryan+Adams&type=artist&market=US&limit=1&offset=0\n\n result ",
"end": 835,
"score": 0.9982496500015259,
"start": 825,
"tag": "NAME",
"value": "Ryan+Adams"
}
] | index.coffee | ccheever/spotify-ranked-tracks | 11 | express = require 'express'
fibrous = require 'use-global-fibrous'
request = require 'request'
{
pluck
sortBy
} = require 'lodash-node'
market = 'US'
_apiUrl = (method, params) ->
"""The URL for an API call"""
host = "api.spotify.com"
version = "v1"
paramList = []
for key, val of params
paramList.push "#{ encodeURIComponent key }=#{ encodeURIComponent val }"
"""https://#{ host }/#{ version }/#{ method }?#{ paramList.join '&' }"""
apiCall = fibrous (method, params) ->
"""Calls Spotify's API"""
url = _apiUrl method, params
console.log "Spotify API call: ", url
response = request.sync url
try
JSON.parse response.body
catch
null
artistId = fibrous (artistName) ->
"""Gets a Spotify artistId from a search query for artist name"""
# https://api.spotify.com/v1/search?q=Ryan+Adams&type=artist&market=US&limit=1&offset=0
result = apiCall.sync 'search',
q: artistName
type: 'artist'
market: market
limit: 1
offset: 0
result?.artists?.items?[0]?.id
allAlbumIds = fibrous (artistId) ->
"""Gets all the albums on Spotify of a given artist"""
# https://api.spotify.com/v1/artists/2qc41rNTtdLK0tV3mJn2Pm/albums?market=US&limit=50&offset=0
result = apiCall.sync "artists/#{ artistId }/albums",
market: market
limit: 50
offset: 0
albums = result?.items
if albums?
(a.id for a in albums)
else
[]
segment = (list, step) ->
"""Segments a list of things into a series of lists of length at most `step`"""
(list[offset...offset + step] for offset in (i for i in [0...list.length] by step))
allTracksFromAlbumIds = fibrous (albumIds) ->
"""Gets all the track ids from a bunch of albumIds"""
segments = segment albumIds, 20
futures = []
for s in segments
# https://api.spotify.com/v1/albums?ids=6JNlf8swWaLPW6PpQA9ghW,5FV8d3DhSoArvwr0Qqgzq3,6R2ec7b25hSZrF19oj3yRG
futures.push apiCall.future 'albums',
ids: s.join ','
trackIds = (x.id for x in Array::concat (t for t in Array::concat(((a?.tracks?.items for a in b?.albums) for b in fibrous.wait futures)...))...)
segments = segment trackIds, 50
futures = []
for s in segments
futures.push apiCall.future 'tracks',
ids: s.join ','
tracks = ({
id: t.id
name: t.name
href: t.href
uri: t.uri
popularity: t.popularity
} for t in Array::concat (x?.tracks for x in fibrous.wait futures)...)
popularTracks = sortBy tracks, 'popularity'
popularTracks.reverse()
popularTracksByArtist = fibrous (artistName) ->
"""Given an artist name, list all their tracks"""
_artistId = artistId.sync artistName
albumIds = allAlbumIds.sync _artistId
allTracksFromAlbumIds.sync albumIds
_escape = (text) ->
"""HTML escape"""
text.toString().replace(/&/g,'&' ).replace(/</g,'<').
replace(/"/g,'"').replace(/'/g,''')
htmlForTracks = (tracks) ->
"""Returns HTML for a bunch of tracks"""
fields = ['id', 'popularity', 'name', 'uri']
html = "<style>BODY { font-family: Helvetica; font-size: 10pt; }</style><table><tr><th>#</th>"
for f in fields
html += "<th>#{ f }</th>"
html += "</tr>"
n = 0
for t in tracks
html += "<tr>"
n++
html += "<td>#{ n }</td>"
for f in fields
x = t[f]
if ':' in x
val = """<a href="#{ x }">#{ x }</a>"""
else
val = _escape x
html += "<td>#{ val }</td>"
html += "</tr>"
html += "</table>"
if require.main is module
app = express()
app.get '/', (req, res) ->
res.send "Hello world!"
app.get "/tracks/:artistName", (req, res) ->
fibrous.run ->
tracks = popularTracksByArtist.sync req.params.artistName
res.send htmlForTracks tracks
server = app.listen 3000, ->
host = server.address().address
port = server.address().port
console.log "Top tracks app listening at http://%s:%s", host, port
module.exports = {
htmlForTracks
popularTracksByArtist
allTracksFromAlbumIds
allAlbumIds
artistId
apiCall
_apiUrl
}
| 161993 | express = require 'express'
fibrous = require 'use-global-fibrous'
request = require 'request'
{
pluck
sortBy
} = require 'lodash-node'
market = 'US'
_apiUrl = (method, params) ->
"""The URL for an API call"""
host = "api.spotify.com"
version = "v1"
paramList = []
for key, val of params
paramList.push "#{ encodeURIComponent key }=#{ encodeURIComponent val }"
"""https://#{ host }/#{ version }/#{ method }?#{ paramList.join '&' }"""
apiCall = fibrous (method, params) ->
"""Calls Spotify's API"""
url = _apiUrl method, params
console.log "Spotify API call: ", url
response = request.sync url
try
JSON.parse response.body
catch
null
artistId = fibrous (artistName) ->
"""Gets a Spotify artistId from a search query for artist name"""
# https://api.spotify.com/v1/search?q=<NAME>&type=artist&market=US&limit=1&offset=0
result = apiCall.sync 'search',
q: artistName
type: 'artist'
market: market
limit: 1
offset: 0
result?.artists?.items?[0]?.id
allAlbumIds = fibrous (artistId) ->
"""Gets all the albums on Spotify of a given artist"""
# https://api.spotify.com/v1/artists/2qc41rNTtdLK0tV3mJn2Pm/albums?market=US&limit=50&offset=0
result = apiCall.sync "artists/#{ artistId }/albums",
market: market
limit: 50
offset: 0
albums = result?.items
if albums?
(a.id for a in albums)
else
[]
segment = (list, step) ->
"""Segments a list of things into a series of lists of length at most `step`"""
(list[offset...offset + step] for offset in (i for i in [0...list.length] by step))
allTracksFromAlbumIds = fibrous (albumIds) ->
"""Gets all the track ids from a bunch of albumIds"""
segments = segment albumIds, 20
futures = []
for s in segments
# https://api.spotify.com/v1/albums?ids=6JNlf8swWaLPW6PpQA9ghW,5FV8d3DhSoArvwr0Qqgzq3,6R2ec7b25hSZrF19oj3yRG
futures.push apiCall.future 'albums',
ids: s.join ','
trackIds = (x.id for x in Array::concat (t for t in Array::concat(((a?.tracks?.items for a in b?.albums) for b in fibrous.wait futures)...))...)
segments = segment trackIds, 50
futures = []
for s in segments
futures.push apiCall.future 'tracks',
ids: s.join ','
tracks = ({
id: t.id
name: t.name
href: t.href
uri: t.uri
popularity: t.popularity
} for t in Array::concat (x?.tracks for x in fibrous.wait futures)...)
popularTracks = sortBy tracks, 'popularity'
popularTracks.reverse()
popularTracksByArtist = fibrous (artistName) ->
"""Given an artist name, list all their tracks"""
_artistId = artistId.sync artistName
albumIds = allAlbumIds.sync _artistId
allTracksFromAlbumIds.sync albumIds
_escape = (text) ->
"""HTML escape"""
text.toString().replace(/&/g,'&' ).replace(/</g,'<').
replace(/"/g,'"').replace(/'/g,''')
htmlForTracks = (tracks) ->
"""Returns HTML for a bunch of tracks"""
fields = ['id', 'popularity', 'name', 'uri']
html = "<style>BODY { font-family: Helvetica; font-size: 10pt; }</style><table><tr><th>#</th>"
for f in fields
html += "<th>#{ f }</th>"
html += "</tr>"
n = 0
for t in tracks
html += "<tr>"
n++
html += "<td>#{ n }</td>"
for f in fields
x = t[f]
if ':' in x
val = """<a href="#{ x }">#{ x }</a>"""
else
val = _escape x
html += "<td>#{ val }</td>"
html += "</tr>"
html += "</table>"
if require.main is module
app = express()
app.get '/', (req, res) ->
res.send "Hello world!"
app.get "/tracks/:artistName", (req, res) ->
fibrous.run ->
tracks = popularTracksByArtist.sync req.params.artistName
res.send htmlForTracks tracks
server = app.listen 3000, ->
host = server.address().address
port = server.address().port
console.log "Top tracks app listening at http://%s:%s", host, port
module.exports = {
htmlForTracks
popularTracksByArtist
allTracksFromAlbumIds
allAlbumIds
artistId
apiCall
_apiUrl
}
| true | express = require 'express'
fibrous = require 'use-global-fibrous'
request = require 'request'
{
pluck
sortBy
} = require 'lodash-node'
market = 'US'
_apiUrl = (method, params) ->
"""The URL for an API call"""
host = "api.spotify.com"
version = "v1"
paramList = []
for key, val of params
paramList.push "#{ encodeURIComponent key }=#{ encodeURIComponent val }"
"""https://#{ host }/#{ version }/#{ method }?#{ paramList.join '&' }"""
apiCall = fibrous (method, params) ->
"""Calls Spotify's API"""
url = _apiUrl method, params
console.log "Spotify API call: ", url
response = request.sync url
try
JSON.parse response.body
catch
null
artistId = fibrous (artistName) ->
"""Gets a Spotify artistId from a search query for artist name"""
# https://api.spotify.com/v1/search?q=PI:NAME:<NAME>END_PI&type=artist&market=US&limit=1&offset=0
result = apiCall.sync 'search',
q: artistName
type: 'artist'
market: market
limit: 1
offset: 0
result?.artists?.items?[0]?.id
allAlbumIds = fibrous (artistId) ->
"""Gets all the albums on Spotify of a given artist"""
# https://api.spotify.com/v1/artists/2qc41rNTtdLK0tV3mJn2Pm/albums?market=US&limit=50&offset=0
result = apiCall.sync "artists/#{ artistId }/albums",
market: market
limit: 50
offset: 0
albums = result?.items
if albums?
(a.id for a in albums)
else
[]
segment = (list, step) ->
"""Segments a list of things into a series of lists of length at most `step`"""
(list[offset...offset + step] for offset in (i for i in [0...list.length] by step))
allTracksFromAlbumIds = fibrous (albumIds) ->
"""Gets all the track ids from a bunch of albumIds"""
segments = segment albumIds, 20
futures = []
for s in segments
# https://api.spotify.com/v1/albums?ids=6JNlf8swWaLPW6PpQA9ghW,5FV8d3DhSoArvwr0Qqgzq3,6R2ec7b25hSZrF19oj3yRG
futures.push apiCall.future 'albums',
ids: s.join ','
trackIds = (x.id for x in Array::concat (t for t in Array::concat(((a?.tracks?.items for a in b?.albums) for b in fibrous.wait futures)...))...)
segments = segment trackIds, 50
futures = []
for s in segments
futures.push apiCall.future 'tracks',
ids: s.join ','
tracks = ({
id: t.id
name: t.name
href: t.href
uri: t.uri
popularity: t.popularity
} for t in Array::concat (x?.tracks for x in fibrous.wait futures)...)
popularTracks = sortBy tracks, 'popularity'
popularTracks.reverse()
popularTracksByArtist = fibrous (artistName) ->
"""Given an artist name, list all their tracks"""
_artistId = artistId.sync artistName
albumIds = allAlbumIds.sync _artistId
allTracksFromAlbumIds.sync albumIds
_escape = (text) ->
"""HTML escape"""
text.toString().replace(/&/g,'&' ).replace(/</g,'<').
replace(/"/g,'"').replace(/'/g,''')
htmlForTracks = (tracks) ->
"""Returns HTML for a bunch of tracks"""
fields = ['id', 'popularity', 'name', 'uri']
html = "<style>BODY { font-family: Helvetica; font-size: 10pt; }</style><table><tr><th>#</th>"
for f in fields
html += "<th>#{ f }</th>"
html += "</tr>"
n = 0
for t in tracks
html += "<tr>"
n++
html += "<td>#{ n }</td>"
for f in fields
x = t[f]
if ':' in x
val = """<a href="#{ x }">#{ x }</a>"""
else
val = _escape x
html += "<td>#{ val }</td>"
html += "</tr>"
html += "</table>"
if require.main is module
app = express()
app.get '/', (req, res) ->
res.send "Hello world!"
app.get "/tracks/:artistName", (req, res) ->
fibrous.run ->
tracks = popularTracksByArtist.sync req.params.artistName
res.send htmlForTracks tracks
server = app.listen 3000, ->
host = server.address().address
port = server.address().port
console.log "Top tracks app listening at http://%s:%s", host, port
module.exports = {
htmlForTracks
popularTracksByArtist
allTracksFromAlbumIds
allAlbumIds
artistId
apiCall
_apiUrl
}
|
[
{
"context": "ther assistance please contact the Species team on species@unep-wcmc.org')\n error: (error) ->\n console.log(err",
"end": 477,
"score": 0.9999313354492188,
"start": 456,
"tag": "EMAIL",
"value": "species@unep-wcmc.org"
}
] | app/assets/javascripts/trade/views/confirm_button_component.js.coffee | unepwcmc/SAPI | 6 | Trade.ConfirmButtonComponent = Ember.Component.extend
layoutName: 'trade/components/confirm-button'
userCanEdit: (callback) ->
$.ajax({
type: 'GET'
url: "/trade/user_can_edit"
data: {}
dataType: 'json'
success: (response) =>
if response.can_edit
callback()
else
alert('It is not possible to perform this action. If you require further assistance please contact the Species team on species@unep-wcmc.org')
error: (error) ->
console.log(error)
})
actions:
showConfirmation: () ->
@userCanEdit( =>
if confirm("Secondary errors detected. Save anyway?")
@sendAction('action', @get('shipment'), true)
)
confirm: () ->
@userCanEdit( =>
@sendAction('action', @get('shipment'), false)
)
| 14630 | Trade.ConfirmButtonComponent = Ember.Component.extend
layoutName: 'trade/components/confirm-button'
userCanEdit: (callback) ->
$.ajax({
type: 'GET'
url: "/trade/user_can_edit"
data: {}
dataType: 'json'
success: (response) =>
if response.can_edit
callback()
else
alert('It is not possible to perform this action. If you require further assistance please contact the Species team on <EMAIL>')
error: (error) ->
console.log(error)
})
actions:
showConfirmation: () ->
@userCanEdit( =>
if confirm("Secondary errors detected. Save anyway?")
@sendAction('action', @get('shipment'), true)
)
confirm: () ->
@userCanEdit( =>
@sendAction('action', @get('shipment'), false)
)
| true | Trade.ConfirmButtonComponent = Ember.Component.extend
layoutName: 'trade/components/confirm-button'
userCanEdit: (callback) ->
$.ajax({
type: 'GET'
url: "/trade/user_can_edit"
data: {}
dataType: 'json'
success: (response) =>
if response.can_edit
callback()
else
alert('It is not possible to perform this action. If you require further assistance please contact the Species team on PI:EMAIL:<EMAIL>END_PI')
error: (error) ->
console.log(error)
})
actions:
showConfirmation: () ->
@userCanEdit( =>
if confirm("Secondary errors detected. Save anyway?")
@sendAction('action', @get('shipment'), true)
)
confirm: () ->
@userCanEdit( =>
@sendAction('action', @get('shipment'), false)
)
|
[
{
"context": "# MODIFIED FROM: https://github.com/probonogeek/knockout-ace\n# Based on Knockout Bindings for Tin",
"end": 47,
"score": 0.9938532114028931,
"start": 36,
"tag": "USERNAME",
"value": "probonogeek"
},
{
"context": "nockout Bindings for TinyMCE\n# https://github.com/SteveSanderson/knockout/wiki/Bindings---tinyMCE\n# Initial versio",
"end": 137,
"score": 0.9989306330680847,
"start": 123,
"tag": "USERNAME",
"value": "SteveSanderson"
},
{
"context": "ckout/wiki/Bindings---tinyMCE\n# Initial version by Ryan Niemeyer. Updated by Scott Messinger, Frederik Raabye, Tho",
"end": 205,
"score": 0.9998984932899475,
"start": 192,
"tag": "NAME",
"value": "Ryan Niemeyer"
},
{
"context": "MCE\n# Initial version by Ryan Niemeyer. Updated by Scott Messinger, Frederik Raabye, Thomas Hallock, Drew Freyling, ",
"end": 233,
"score": 0.9998738765716553,
"start": 218,
"tag": "NAME",
"value": "Scott Messinger"
},
{
"context": "sion by Ryan Niemeyer. Updated by Scott Messinger, Frederik Raabye, Thomas Hallock, Drew Freyling, and Shane Carr.\n\n",
"end": 250,
"score": 0.9998703002929688,
"start": 235,
"tag": "NAME",
"value": "Frederik Raabye"
},
{
"context": "eyer. Updated by Scott Messinger, Frederik Raabye, Thomas Hallock, Drew Freyling, and Shane Carr.\n\ndo ->\n instance",
"end": 266,
"score": 0.9998446106910706,
"start": 252,
"tag": "NAME",
"value": "Thomas Hallock"
},
{
"context": " Scott Messinger, Frederik Raabye, Thomas Hallock, Drew Freyling, and Shane Carr.\n\ndo ->\n instances_by_id = {}\n ",
"end": 281,
"score": 0.9998513460159302,
"start": 268,
"tag": "NAME",
"value": "Drew Freyling"
},
{
"context": "rederik Raabye, Thomas Hallock, Drew Freyling, and Shane Carr.\n\ndo ->\n instances_by_id = {}\n init_id = 0\n # ",
"end": 297,
"score": 0.9998583793640137,
"start": 287,
"tag": "NAME",
"value": "Shane Carr"
}
] | vendor/assets/javascripts/knockout-ace/knockout-ace.coffee | enterstudio/precisionFDA | 57 | # MODIFIED FROM: https://github.com/probonogeek/knockout-ace
# Based on Knockout Bindings for TinyMCE
# https://github.com/SteveSanderson/knockout/wiki/Bindings---tinyMCE
# Initial version by Ryan Niemeyer. Updated by Scott Messinger, Frederik Raabye, Thomas Hallock, Drew Freyling, and Shane Carr.
do ->
instances_by_id = {}
init_id = 0
# generated id increment storage
ko.bindingHandlers.ace =
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
options = allBindingsAccessor().aceOptions or {}
value = ko.utils.unwrapObservable(valueAccessor()) ? ""
# Ace attaches to the element by DOM id, so we need to make one for the element if it doesn't have one already.
if !element.id
element.id = 'knockout-ace-' + init_id
init_id = init_id + 1
ace.require("ace/ext/language_tools")
editor = ace.edit(element.id)
editor.$blockScrolling = Infinity
editor.setTheme 'ace/theme/' + options.theme if options.theme
editor.getSession().setMode 'ace/mode/' + options.mode if options.mode
editor.setReadOnly true if options.readOnly
editor.renderer.setShowPrintMargin(options.checked ? false)
editor.getSession().setTabSize(2)
editor.setOptions _.defaults({
enableBasicAutocompletion: true
enableSnippets: true,
enableLiveAutocompletion: false
}, options.opts)
editor.setValue value
editor.gotoLine 0
editor.getSession().on 'change', (delta) ->
if ko.isWriteableObservable(valueAccessor())
valueAccessor()(editor.getValue())
instances_by_id[element.id] = editor
# destroy the editor instance when the element is removed
ko.utils.domNodeDisposal.addDisposeCallback element, ->
editor.destroy()
delete instances_by_id[element.id]
update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
value = ko.utils.unwrapObservable(valueAccessor()) ? ""
id = element.id
#handle programmatic updates to the observable
# also makes sure it doesn't update it if it's the same.
# otherwise, it will reload the instance, causing the cursor to jump.
if id != undefined and id != '' and instances_by_id.hasOwnProperty(id)
editor = instances_by_id[id]
content = editor.getValue()
if content != value
editor.setValue(value)
editor.gotoLine 0
ko.aceEditors =
resizeAll: ->
for id of instances_by_id
if !instances_by_id.hasOwnProperty(id)
continue
editor = instances_by_id[id]
editor.resize()
return
get: (id) ->
instances_by_id[id]
| 109429 | # MODIFIED FROM: https://github.com/probonogeek/knockout-ace
# Based on Knockout Bindings for TinyMCE
# https://github.com/SteveSanderson/knockout/wiki/Bindings---tinyMCE
# Initial version by <NAME>. Updated by <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>.
do ->
instances_by_id = {}
init_id = 0
# generated id increment storage
ko.bindingHandlers.ace =
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
options = allBindingsAccessor().aceOptions or {}
value = ko.utils.unwrapObservable(valueAccessor()) ? ""
# Ace attaches to the element by DOM id, so we need to make one for the element if it doesn't have one already.
if !element.id
element.id = 'knockout-ace-' + init_id
init_id = init_id + 1
ace.require("ace/ext/language_tools")
editor = ace.edit(element.id)
editor.$blockScrolling = Infinity
editor.setTheme 'ace/theme/' + options.theme if options.theme
editor.getSession().setMode 'ace/mode/' + options.mode if options.mode
editor.setReadOnly true if options.readOnly
editor.renderer.setShowPrintMargin(options.checked ? false)
editor.getSession().setTabSize(2)
editor.setOptions _.defaults({
enableBasicAutocompletion: true
enableSnippets: true,
enableLiveAutocompletion: false
}, options.opts)
editor.setValue value
editor.gotoLine 0
editor.getSession().on 'change', (delta) ->
if ko.isWriteableObservable(valueAccessor())
valueAccessor()(editor.getValue())
instances_by_id[element.id] = editor
# destroy the editor instance when the element is removed
ko.utils.domNodeDisposal.addDisposeCallback element, ->
editor.destroy()
delete instances_by_id[element.id]
update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
value = ko.utils.unwrapObservable(valueAccessor()) ? ""
id = element.id
#handle programmatic updates to the observable
# also makes sure it doesn't update it if it's the same.
# otherwise, it will reload the instance, causing the cursor to jump.
if id != undefined and id != '' and instances_by_id.hasOwnProperty(id)
editor = instances_by_id[id]
content = editor.getValue()
if content != value
editor.setValue(value)
editor.gotoLine 0
ko.aceEditors =
resizeAll: ->
for id of instances_by_id
if !instances_by_id.hasOwnProperty(id)
continue
editor = instances_by_id[id]
editor.resize()
return
get: (id) ->
instances_by_id[id]
| true | # MODIFIED FROM: https://github.com/probonogeek/knockout-ace
# Based on Knockout Bindings for TinyMCE
# https://github.com/SteveSanderson/knockout/wiki/Bindings---tinyMCE
# Initial version by PI:NAME:<NAME>END_PI. Updated by PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI.
do ->
instances_by_id = {}
init_id = 0
# generated id increment storage
ko.bindingHandlers.ace =
init: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
options = allBindingsAccessor().aceOptions or {}
value = ko.utils.unwrapObservable(valueAccessor()) ? ""
# Ace attaches to the element by DOM id, so we need to make one for the element if it doesn't have one already.
if !element.id
element.id = 'knockout-ace-' + init_id
init_id = init_id + 1
ace.require("ace/ext/language_tools")
editor = ace.edit(element.id)
editor.$blockScrolling = Infinity
editor.setTheme 'ace/theme/' + options.theme if options.theme
editor.getSession().setMode 'ace/mode/' + options.mode if options.mode
editor.setReadOnly true if options.readOnly
editor.renderer.setShowPrintMargin(options.checked ? false)
editor.getSession().setTabSize(2)
editor.setOptions _.defaults({
enableBasicAutocompletion: true
enableSnippets: true,
enableLiveAutocompletion: false
}, options.opts)
editor.setValue value
editor.gotoLine 0
editor.getSession().on 'change', (delta) ->
if ko.isWriteableObservable(valueAccessor())
valueAccessor()(editor.getValue())
instances_by_id[element.id] = editor
# destroy the editor instance when the element is removed
ko.utils.domNodeDisposal.addDisposeCallback element, ->
editor.destroy()
delete instances_by_id[element.id]
update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) ->
value = ko.utils.unwrapObservable(valueAccessor()) ? ""
id = element.id
#handle programmatic updates to the observable
# also makes sure it doesn't update it if it's the same.
# otherwise, it will reload the instance, causing the cursor to jump.
if id != undefined and id != '' and instances_by_id.hasOwnProperty(id)
editor = instances_by_id[id]
content = editor.getValue()
if content != value
editor.setValue(value)
editor.gotoLine 0
ko.aceEditors =
resizeAll: ->
for id of instances_by_id
if !instances_by_id.hasOwnProperty(id)
continue
editor = instances_by_id[id]
editor.resize()
return
get: (id) ->
instances_by_id[id]
|
[
{
"context": "h ->\n\t\t@project_id = \"321l3j1kjkjl\"\n\t\t@user_id = \"user-id-123\"\n\t\t@project =\n\t\t\tname: \"project\"\n\t\t\tdescription: ",
"end": 438,
"score": 0.5053415298461914,
"start": 427,
"tag": "USERNAME",
"value": "user-id-123"
},
{
"context": "okens:\n\t\t\t\t\t\treadOnly: 'aaa'\n\t\t\t\t\t\treadAndWrite: '42bbb'\n\t\t\t\t\t\treadAndWritePrefix: '42'\n\t\t\t\t@ProjectGette",
"end": 10482,
"score": 0.6371085047721863,
"start": 10477,
"tag": "KEY",
"value": "42bbb"
},
{
"context": "sArgWith(2, null, @project)\n\t\t\t\t@readOnlyToken = 'abc'\n\t\t\t\t@readAndWriteToken = '42def'\n\t\t\t\t@readAndWri",
"end": 11537,
"score": 0.9159150123596191,
"start": 11534,
"tag": "KEY",
"value": "abc"
},
{
"context": "\t@readOnlyToken = 'abc'\n\t\t\t\t@readAndWriteToken = '42def'\n\t\t\t\t@readAndWriteTokenPrefix = '42'\n\t\t\t\t@Pro",
"end": 11566,
"score": 0.5298032164573669,
"start": 11565,
"tag": "KEY",
"value": "4"
},
{
"context": "@readOnlyToken = 'abc'\n\t\t\t\t@readAndWriteToken = '42def'\n\t\t\t\t@readAndWriteTokenPrefix = '42'\n\t\t\t\t@Project",
"end": 11570,
"score": 0.5595700740814209,
"start": 11566,
"tag": "PASSWORD",
"value": "2def"
},
{
"context": "teToken = '42def'\n\t\t\t\t@readAndWriteTokenPrefix = '42'\n\t\t\t\t@ProjectTokenGenerator.generateUniqueReadOn",
"end": 11605,
"score": 0.6823321580886841,
"start": 11604,
"tag": "KEY",
"value": "4"
}
] | test/unit/coffee/Project/ProjectDetailsHandlerTests.coffee | shyoshyo/web-sharelatex | 1 | should = require('chai').should()
modulePath = "../../../../app/js/Features/Project/ProjectDetailsHandler"
Errors = require "../../../../app/js/Features/Errors/Errors"
SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
assert = require("chai").assert
expect = require("chai").expect
require('chai').should()
describe 'ProjectDetailsHandler', ->
beforeEach ->
@project_id = "321l3j1kjkjl"
@user_id = "user-id-123"
@project =
name: "project"
description: "this is a great project"
something:"should not exist"
compiler: "latexxxxxx"
owner_ref: @user_id
@user =
features: "mock-features"
@ProjectGetter =
getProjectWithoutDocLines: sinon.stub().callsArgWith(1, null, @project)
getProject: sinon.stub().callsArgWith(2, null, @project)
@ProjectModel =
update: sinon.stub()
findOne: sinon.stub()
@UserGetter =
getUser: sinon.stub().callsArgWith(1, null, @user)
@tpdsUpdateSender =
moveEntity:sinon.stub().callsArgWith 1
@handler = SandboxedModule.require modulePath, requires:
"./ProjectGetter":@ProjectGetter
'../../models/Project': Project:@ProjectModel
"../User/UserGetter": @UserGetter
'../ThirdPartyDataStore/TpdsUpdateSender':@tpdsUpdateSender
'logger-sharelatex':
log:->
err:->
'./ProjectTokenGenerator': @ProjectTokenGenerator = {}
'settings-sharelatex': @settings =
defaultFeatures: 'default-features'
describe "getDetails", ->
it "should find the project and owner", (done)->
@handler.getDetails @project_id, (err, details)=>
details.name.should.equal @project.name
details.description.should.equal @project.description
details.compiler.should.equal @project.compiler
details.features.should.equal @user.features
assert.equal(details.something, undefined)
done()
it "should find overleaf metadata if it exists", (done)->
@project.overleaf = { id: 'id' }
@handler.getDetails @project_id, (err, details)=>
details.overleaf.should.equal @project.overleaf
assert.equal(details.something, undefined)
done()
it "should return an error for a non-existent project", (done)->
@ProjectGetter.getProject.callsArg(2, null, null)
err = new Errors.NotFoundError("project not found")
@handler.getDetails "0123456789012345678901234", (error, details) =>
err.should.eql error
done()
it 'should return the default features if no owner found', (done) ->
@UserGetter.getUser.callsArgWith(1, null, null)
@handler.getDetails @project_id, (err, details)=>
details.features.should.equal @settings.defaultFeatures
done()
it "should return the error", (done)->
error = "some error"
@ProjectGetter.getProject.callsArgWith(2, error)
@handler.getDetails @project_id, (err)=>
err.should.equal error
done()
describe "getProjectDescription", ->
it "should make a call to mongo just for the description", (done)->
@ProjectGetter.getProject.callsArgWith(2)
@handler.getProjectDescription @project_id, (err, description)=>
@ProjectGetter.getProject
.calledWith(@project_id, description: true)
.should.equal true
done()
it "should return what the mongo call returns", (done)->
err = "error"
description = "cool project"
@ProjectGetter.getProject.callsArgWith(2, err, {description:description})
@handler.getProjectDescription @project_id, (returnedErr, returnedDescription)=>
err.should.equal returnedErr
description.should.equal returnedDescription
done()
describe "setProjectDescription", ->
beforeEach ->
@description = "updated teh description"
it "should update the project detials", (done)->
@ProjectModel.update.callsArgWith(2)
@handler.setProjectDescription @project_id, @description, =>
@ProjectModel.update.calledWith({_id:@project_id}, {description:@description}).should.equal true
done()
describe "renameProject", ->
beforeEach ->
@handler.validateProjectName = sinon.stub().yields()
@ProjectModel.update.callsArgWith(2)
@newName = "new name here"
it "should update the project with the new name", (done)->
newName = "new name here"
@handler.renameProject @project_id, @newName, =>
@ProjectModel.update.calledWith({_id: @project_id}, {name: @newName}).should.equal true
done()
it "should tell the tpdsUpdateSender", (done)->
@handler.renameProject @project_id, @newName, =>
@tpdsUpdateSender.moveEntity.calledWith({project_id:@project_id, project_name:@project.name, newProjectName:@newName}).should.equal true
done()
it "should not do anything with an invalid name", (done) ->
@handler.validateProjectName = sinon.stub().yields(new Error("invalid name"))
@handler.renameProject @project_id, @newName, =>
@tpdsUpdateSender.moveEntity.called.should.equal false
@ProjectModel.update.called.should.equal false
done()
describe "validateProjectName", ->
it "should reject undefined names", (done) ->
@handler.validateProjectName undefined, (error) ->
expect(error).to.exist
done()
it "should reject empty names", (done) ->
@handler.validateProjectName "", (error) ->
expect(error).to.exist
done()
it "should reject names with /s", (done) ->
@handler.validateProjectName "foo/bar", (error) ->
expect(error).to.exist
done()
it "should reject names with \\s", (done) ->
@handler.validateProjectName "foo\\bar", (error) ->
expect(error).to.exist
done()
it "should reject long names", (done) ->
@handler.validateProjectName new Array(1000).join("a"), (error) ->
expect(error).to.exist
done()
it "should accept normal names", (done) ->
@handler.validateProjectName "foobar", (error) ->
expect(error).to.not.exist
done()
describe "ensureProjectNameIsUnique", ->
beforeEach ->
@result = {
owned: [{_id: 1, name:"name"}, {_id: 2, name: "name1"}, {_id: 3, name: "name11"}, {_id: 100, name: "numeric"}]
readAndWrite: [{_id: 4, name:"name2"}, {_id: 5, name:"name22"}]
readOnly: [{_id:6, name:"name3"}, {_id:7, name: "name33"}]
tokenReadAndWrite: [{_id:8, name:"name4"}, {_id:9, name:"name44"}]
tokenReadOnly: [{_id:10, name:"name5"}, {_id:11, name:"name55"}, {_id:12, name:"x".repeat(15)}]
}
for i in [1..20].concat([30..40])
@result.owned.push {_id: 100 + i, name: "numeric (#{i})"}
@ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, @result)
it "should leave a unique name unchanged", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "unique-name", ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "unique-name"
expect(changed).to.equal false
done()
it "should append a suffix to an existing name", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "name1-test-suffix"
expect(changed).to.equal true
done()
it "should fallback to a second suffix when needed", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", ["1", "-test-suffix"], (error, name, changed) ->
expect(name).to.equal "name1-test-suffix"
expect(changed).to.equal true
done()
it "should truncate the name when append a suffix if the result is too long", (done) ->
@handler.MAX_PROJECT_NAME_LENGTH = 20
@handler.ensureProjectNameIsUnique @user_id, "x".repeat(15), ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "x".repeat(8) + "-test-suffix"
expect(changed).to.equal true
done()
it "should use a numeric index if no suffix is supplied", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", [], (error, name, changed) ->
expect(name).to.equal "name1 (1)"
expect(changed).to.equal true
done()
it "should use a numeric index if all suffixes are exhausted", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name", ["1", "11"], (error, name, changed) ->
expect(name).to.equal "name (1)"
expect(changed).to.equal true
done()
it "should find the next lowest available numeric index for the base name", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric", [], (error, name, changed) ->
expect(name).to.equal "numeric (21)"
expect(changed).to.equal true
done()
it "should find the next available numeric index when a numeric index is already present", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric (5)", [], (error, name, changed) ->
expect(name).to.equal "numeric (21)"
expect(changed).to.equal true
done()
it "should not find a numeric index lower than the one already present", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric (31)", [], (error, name, changed) ->
expect(name).to.equal "numeric (41)"
expect(changed).to.equal true
done()
describe "fixProjectName", ->
it "should change empty names to Untitled", () ->
expect(@handler.fixProjectName "").to.equal "Untitled"
it "should replace / with -", () ->
expect(@handler.fixProjectName "foo/bar").to.equal "foo-bar"
it "should replace \\ with ''", () ->
expect(@handler.fixProjectName "foo \\ bar").to.equal "foo bar"
it "should truncate long names", () ->
expect(@handler.fixProjectName new Array(1000).join("a")).to.equal "a".repeat(150)
it "should accept normal names", () ->
expect(@handler.fixProjectName "foobar").to.equal "foobar"
describe "setPublicAccessLevel", ->
beforeEach ->
@ProjectModel.update.callsArgWith(2)
@accessLevel = "readOnly"
it "should update the project with the new level", (done)->
@handler.setPublicAccessLevel @project_id, @accessLevel, =>
@ProjectModel.update.calledWith({_id: @project_id}, {publicAccesLevel: @accessLevel}).should.equal true
done()
it 'should not produce an error', (done) ->
@handler.setPublicAccessLevel @project_id, @accessLevel, (err) =>
expect(err).to.not.exist
done()
describe 'when update produces an error', ->
beforeEach ->
@ProjectModel.update.callsArgWith(2, new Error('woops'))
it 'should produce an error', (done) ->
@handler.setPublicAccessLevel @project_id, @accessLevel, (err) =>
expect(err).to.exist
expect(err).to.be.instanceof Error
done()
describe "ensureTokensArePresent", ->
beforeEach ->
describe 'when the project has tokens', ->
beforeEach ->
@project =
_id: @project_id
tokens:
readOnly: 'aaa'
readAndWrite: '42bbb'
readAndWritePrefix: '42'
@ProjectGetter.getProject = sinon.stub()
.callsArgWith(2, null, @project)
@ProjectModel.update = sinon.stub()
it 'should get the project', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectGetter.getProject.callCount).to.equal 1
expect(@ProjectGetter.getProject.calledWith(@project_id, {tokens: 1}))
.to.equal true
done()
it 'should not update the project with new tokens', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectModel.update.callCount).to.equal 0
done()
it 'should produce the tokens without error', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(err).to.not.exist
expect(tokens).to.deep.equal @project.tokens
done()
describe 'when tokens are missing', ->
beforeEach ->
@project =
_id: @project_id
@ProjectGetter.getProject = sinon.stub()
.callsArgWith(2, null, @project)
@readOnlyToken = 'abc'
@readAndWriteToken = '42def'
@readAndWriteTokenPrefix = '42'
@ProjectTokenGenerator.generateUniqueReadOnlyToken = sinon.stub().callsArgWith(0, null, @readOnlyToken)
@ProjectTokenGenerator.readAndWriteToken = sinon.stub().returns({
token: @readAndWriteToken
numericPrefix: @readAndWriteTokenPrefix
})
@ProjectModel.update = sinon.stub()
.callsArgWith(2, null)
it 'should get the project', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectGetter.getProject.callCount).to.equal 1
expect(@ProjectGetter.getProject.calledWith(@project_id, {tokens: 1}))
.to.equal true
done()
it 'should update the project with new tokens', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectTokenGenerator.generateUniqueReadOnlyToken.callCount)
.to.equal 1
expect(@ProjectTokenGenerator.readAndWriteToken.callCount)
.to.equal 1
expect(@ProjectModel.update.callCount).to.equal 1
expect(@ProjectModel.update.calledWith(
{_id: @project_id},
{
$set: {
tokens: {
readOnly: @readOnlyToken,
readAndWrite: @readAndWriteToken,
readAndWritePrefix: @readAndWriteTokenPrefix
}
}
}
)).to.equal true
done()
it 'should produce the tokens without error', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(err).to.not.exist
expect(tokens).to.deep.equal {
readOnly: @readOnlyToken,
readAndWrite: @readAndWriteToken,
readAndWritePrefix: @readAndWriteTokenPrefix
}
done()
| 56577 | should = require('chai').should()
modulePath = "../../../../app/js/Features/Project/ProjectDetailsHandler"
Errors = require "../../../../app/js/Features/Errors/Errors"
SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
assert = require("chai").assert
expect = require("chai").expect
require('chai').should()
describe 'ProjectDetailsHandler', ->
beforeEach ->
@project_id = "321l3j1kjkjl"
@user_id = "user-id-123"
@project =
name: "project"
description: "this is a great project"
something:"should not exist"
compiler: "latexxxxxx"
owner_ref: @user_id
@user =
features: "mock-features"
@ProjectGetter =
getProjectWithoutDocLines: sinon.stub().callsArgWith(1, null, @project)
getProject: sinon.stub().callsArgWith(2, null, @project)
@ProjectModel =
update: sinon.stub()
findOne: sinon.stub()
@UserGetter =
getUser: sinon.stub().callsArgWith(1, null, @user)
@tpdsUpdateSender =
moveEntity:sinon.stub().callsArgWith 1
@handler = SandboxedModule.require modulePath, requires:
"./ProjectGetter":@ProjectGetter
'../../models/Project': Project:@ProjectModel
"../User/UserGetter": @UserGetter
'../ThirdPartyDataStore/TpdsUpdateSender':@tpdsUpdateSender
'logger-sharelatex':
log:->
err:->
'./ProjectTokenGenerator': @ProjectTokenGenerator = {}
'settings-sharelatex': @settings =
defaultFeatures: 'default-features'
describe "getDetails", ->
it "should find the project and owner", (done)->
@handler.getDetails @project_id, (err, details)=>
details.name.should.equal @project.name
details.description.should.equal @project.description
details.compiler.should.equal @project.compiler
details.features.should.equal @user.features
assert.equal(details.something, undefined)
done()
it "should find overleaf metadata if it exists", (done)->
@project.overleaf = { id: 'id' }
@handler.getDetails @project_id, (err, details)=>
details.overleaf.should.equal @project.overleaf
assert.equal(details.something, undefined)
done()
it "should return an error for a non-existent project", (done)->
@ProjectGetter.getProject.callsArg(2, null, null)
err = new Errors.NotFoundError("project not found")
@handler.getDetails "0123456789012345678901234", (error, details) =>
err.should.eql error
done()
it 'should return the default features if no owner found', (done) ->
@UserGetter.getUser.callsArgWith(1, null, null)
@handler.getDetails @project_id, (err, details)=>
details.features.should.equal @settings.defaultFeatures
done()
it "should return the error", (done)->
error = "some error"
@ProjectGetter.getProject.callsArgWith(2, error)
@handler.getDetails @project_id, (err)=>
err.should.equal error
done()
describe "getProjectDescription", ->
it "should make a call to mongo just for the description", (done)->
@ProjectGetter.getProject.callsArgWith(2)
@handler.getProjectDescription @project_id, (err, description)=>
@ProjectGetter.getProject
.calledWith(@project_id, description: true)
.should.equal true
done()
it "should return what the mongo call returns", (done)->
err = "error"
description = "cool project"
@ProjectGetter.getProject.callsArgWith(2, err, {description:description})
@handler.getProjectDescription @project_id, (returnedErr, returnedDescription)=>
err.should.equal returnedErr
description.should.equal returnedDescription
done()
describe "setProjectDescription", ->
beforeEach ->
@description = "updated teh description"
it "should update the project detials", (done)->
@ProjectModel.update.callsArgWith(2)
@handler.setProjectDescription @project_id, @description, =>
@ProjectModel.update.calledWith({_id:@project_id}, {description:@description}).should.equal true
done()
describe "renameProject", ->
beforeEach ->
@handler.validateProjectName = sinon.stub().yields()
@ProjectModel.update.callsArgWith(2)
@newName = "new name here"
it "should update the project with the new name", (done)->
newName = "new name here"
@handler.renameProject @project_id, @newName, =>
@ProjectModel.update.calledWith({_id: @project_id}, {name: @newName}).should.equal true
done()
it "should tell the tpdsUpdateSender", (done)->
@handler.renameProject @project_id, @newName, =>
@tpdsUpdateSender.moveEntity.calledWith({project_id:@project_id, project_name:@project.name, newProjectName:@newName}).should.equal true
done()
it "should not do anything with an invalid name", (done) ->
@handler.validateProjectName = sinon.stub().yields(new Error("invalid name"))
@handler.renameProject @project_id, @newName, =>
@tpdsUpdateSender.moveEntity.called.should.equal false
@ProjectModel.update.called.should.equal false
done()
describe "validateProjectName", ->
it "should reject undefined names", (done) ->
@handler.validateProjectName undefined, (error) ->
expect(error).to.exist
done()
it "should reject empty names", (done) ->
@handler.validateProjectName "", (error) ->
expect(error).to.exist
done()
it "should reject names with /s", (done) ->
@handler.validateProjectName "foo/bar", (error) ->
expect(error).to.exist
done()
it "should reject names with \\s", (done) ->
@handler.validateProjectName "foo\\bar", (error) ->
expect(error).to.exist
done()
it "should reject long names", (done) ->
@handler.validateProjectName new Array(1000).join("a"), (error) ->
expect(error).to.exist
done()
it "should accept normal names", (done) ->
@handler.validateProjectName "foobar", (error) ->
expect(error).to.not.exist
done()
describe "ensureProjectNameIsUnique", ->
beforeEach ->
@result = {
owned: [{_id: 1, name:"name"}, {_id: 2, name: "name1"}, {_id: 3, name: "name11"}, {_id: 100, name: "numeric"}]
readAndWrite: [{_id: 4, name:"name2"}, {_id: 5, name:"name22"}]
readOnly: [{_id:6, name:"name3"}, {_id:7, name: "name33"}]
tokenReadAndWrite: [{_id:8, name:"name4"}, {_id:9, name:"name44"}]
tokenReadOnly: [{_id:10, name:"name5"}, {_id:11, name:"name55"}, {_id:12, name:"x".repeat(15)}]
}
for i in [1..20].concat([30..40])
@result.owned.push {_id: 100 + i, name: "numeric (#{i})"}
@ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, @result)
it "should leave a unique name unchanged", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "unique-name", ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "unique-name"
expect(changed).to.equal false
done()
it "should append a suffix to an existing name", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "name1-test-suffix"
expect(changed).to.equal true
done()
it "should fallback to a second suffix when needed", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", ["1", "-test-suffix"], (error, name, changed) ->
expect(name).to.equal "name1-test-suffix"
expect(changed).to.equal true
done()
it "should truncate the name when append a suffix if the result is too long", (done) ->
@handler.MAX_PROJECT_NAME_LENGTH = 20
@handler.ensureProjectNameIsUnique @user_id, "x".repeat(15), ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "x".repeat(8) + "-test-suffix"
expect(changed).to.equal true
done()
it "should use a numeric index if no suffix is supplied", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", [], (error, name, changed) ->
expect(name).to.equal "name1 (1)"
expect(changed).to.equal true
done()
it "should use a numeric index if all suffixes are exhausted", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name", ["1", "11"], (error, name, changed) ->
expect(name).to.equal "name (1)"
expect(changed).to.equal true
done()
it "should find the next lowest available numeric index for the base name", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric", [], (error, name, changed) ->
expect(name).to.equal "numeric (21)"
expect(changed).to.equal true
done()
it "should find the next available numeric index when a numeric index is already present", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric (5)", [], (error, name, changed) ->
expect(name).to.equal "numeric (21)"
expect(changed).to.equal true
done()
it "should not find a numeric index lower than the one already present", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric (31)", [], (error, name, changed) ->
expect(name).to.equal "numeric (41)"
expect(changed).to.equal true
done()
describe "fixProjectName", ->
it "should change empty names to Untitled", () ->
expect(@handler.fixProjectName "").to.equal "Untitled"
it "should replace / with -", () ->
expect(@handler.fixProjectName "foo/bar").to.equal "foo-bar"
it "should replace \\ with ''", () ->
expect(@handler.fixProjectName "foo \\ bar").to.equal "foo bar"
it "should truncate long names", () ->
expect(@handler.fixProjectName new Array(1000).join("a")).to.equal "a".repeat(150)
it "should accept normal names", () ->
expect(@handler.fixProjectName "foobar").to.equal "foobar"
describe "setPublicAccessLevel", ->
beforeEach ->
@ProjectModel.update.callsArgWith(2)
@accessLevel = "readOnly"
it "should update the project with the new level", (done)->
@handler.setPublicAccessLevel @project_id, @accessLevel, =>
@ProjectModel.update.calledWith({_id: @project_id}, {publicAccesLevel: @accessLevel}).should.equal true
done()
it 'should not produce an error', (done) ->
@handler.setPublicAccessLevel @project_id, @accessLevel, (err) =>
expect(err).to.not.exist
done()
describe 'when update produces an error', ->
beforeEach ->
@ProjectModel.update.callsArgWith(2, new Error('woops'))
it 'should produce an error', (done) ->
@handler.setPublicAccessLevel @project_id, @accessLevel, (err) =>
expect(err).to.exist
expect(err).to.be.instanceof Error
done()
describe "ensureTokensArePresent", ->
beforeEach ->
describe 'when the project has tokens', ->
beforeEach ->
@project =
_id: @project_id
tokens:
readOnly: 'aaa'
readAndWrite: '<KEY>'
readAndWritePrefix: '42'
@ProjectGetter.getProject = sinon.stub()
.callsArgWith(2, null, @project)
@ProjectModel.update = sinon.stub()
it 'should get the project', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectGetter.getProject.callCount).to.equal 1
expect(@ProjectGetter.getProject.calledWith(@project_id, {tokens: 1}))
.to.equal true
done()
it 'should not update the project with new tokens', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectModel.update.callCount).to.equal 0
done()
it 'should produce the tokens without error', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(err).to.not.exist
expect(tokens).to.deep.equal @project.tokens
done()
describe 'when tokens are missing', ->
beforeEach ->
@project =
_id: @project_id
@ProjectGetter.getProject = sinon.stub()
.callsArgWith(2, null, @project)
@readOnlyToken = '<KEY>'
@readAndWriteToken = '<KEY> <PASSWORD>'
@readAndWriteTokenPrefix = '<KEY>2'
@ProjectTokenGenerator.generateUniqueReadOnlyToken = sinon.stub().callsArgWith(0, null, @readOnlyToken)
@ProjectTokenGenerator.readAndWriteToken = sinon.stub().returns({
token: @readAndWriteToken
numericPrefix: @readAndWriteTokenPrefix
})
@ProjectModel.update = sinon.stub()
.callsArgWith(2, null)
it 'should get the project', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectGetter.getProject.callCount).to.equal 1
expect(@ProjectGetter.getProject.calledWith(@project_id, {tokens: 1}))
.to.equal true
done()
it 'should update the project with new tokens', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectTokenGenerator.generateUniqueReadOnlyToken.callCount)
.to.equal 1
expect(@ProjectTokenGenerator.readAndWriteToken.callCount)
.to.equal 1
expect(@ProjectModel.update.callCount).to.equal 1
expect(@ProjectModel.update.calledWith(
{_id: @project_id},
{
$set: {
tokens: {
readOnly: @readOnlyToken,
readAndWrite: @readAndWriteToken,
readAndWritePrefix: @readAndWriteTokenPrefix
}
}
}
)).to.equal true
done()
it 'should produce the tokens without error', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(err).to.not.exist
expect(tokens).to.deep.equal {
readOnly: @readOnlyToken,
readAndWrite: @readAndWriteToken,
readAndWritePrefix: @readAndWriteTokenPrefix
}
done()
| true | should = require('chai').should()
modulePath = "../../../../app/js/Features/Project/ProjectDetailsHandler"
Errors = require "../../../../app/js/Features/Errors/Errors"
SandboxedModule = require('sandboxed-module')
sinon = require('sinon')
assert = require("chai").assert
expect = require("chai").expect
require('chai').should()
describe 'ProjectDetailsHandler', ->
beforeEach ->
@project_id = "321l3j1kjkjl"
@user_id = "user-id-123"
@project =
name: "project"
description: "this is a great project"
something:"should not exist"
compiler: "latexxxxxx"
owner_ref: @user_id
@user =
features: "mock-features"
@ProjectGetter =
getProjectWithoutDocLines: sinon.stub().callsArgWith(1, null, @project)
getProject: sinon.stub().callsArgWith(2, null, @project)
@ProjectModel =
update: sinon.stub()
findOne: sinon.stub()
@UserGetter =
getUser: sinon.stub().callsArgWith(1, null, @user)
@tpdsUpdateSender =
moveEntity:sinon.stub().callsArgWith 1
@handler = SandboxedModule.require modulePath, requires:
"./ProjectGetter":@ProjectGetter
'../../models/Project': Project:@ProjectModel
"../User/UserGetter": @UserGetter
'../ThirdPartyDataStore/TpdsUpdateSender':@tpdsUpdateSender
'logger-sharelatex':
log:->
err:->
'./ProjectTokenGenerator': @ProjectTokenGenerator = {}
'settings-sharelatex': @settings =
defaultFeatures: 'default-features'
describe "getDetails", ->
it "should find the project and owner", (done)->
@handler.getDetails @project_id, (err, details)=>
details.name.should.equal @project.name
details.description.should.equal @project.description
details.compiler.should.equal @project.compiler
details.features.should.equal @user.features
assert.equal(details.something, undefined)
done()
it "should find overleaf metadata if it exists", (done)->
@project.overleaf = { id: 'id' }
@handler.getDetails @project_id, (err, details)=>
details.overleaf.should.equal @project.overleaf
assert.equal(details.something, undefined)
done()
it "should return an error for a non-existent project", (done)->
@ProjectGetter.getProject.callsArg(2, null, null)
err = new Errors.NotFoundError("project not found")
@handler.getDetails "0123456789012345678901234", (error, details) =>
err.should.eql error
done()
it 'should return the default features if no owner found', (done) ->
@UserGetter.getUser.callsArgWith(1, null, null)
@handler.getDetails @project_id, (err, details)=>
details.features.should.equal @settings.defaultFeatures
done()
it "should return the error", (done)->
error = "some error"
@ProjectGetter.getProject.callsArgWith(2, error)
@handler.getDetails @project_id, (err)=>
err.should.equal error
done()
describe "getProjectDescription", ->
it "should make a call to mongo just for the description", (done)->
@ProjectGetter.getProject.callsArgWith(2)
@handler.getProjectDescription @project_id, (err, description)=>
@ProjectGetter.getProject
.calledWith(@project_id, description: true)
.should.equal true
done()
it "should return what the mongo call returns", (done)->
err = "error"
description = "cool project"
@ProjectGetter.getProject.callsArgWith(2, err, {description:description})
@handler.getProjectDescription @project_id, (returnedErr, returnedDescription)=>
err.should.equal returnedErr
description.should.equal returnedDescription
done()
describe "setProjectDescription", ->
beforeEach ->
@description = "updated teh description"
it "should update the project detials", (done)->
@ProjectModel.update.callsArgWith(2)
@handler.setProjectDescription @project_id, @description, =>
@ProjectModel.update.calledWith({_id:@project_id}, {description:@description}).should.equal true
done()
describe "renameProject", ->
beforeEach ->
@handler.validateProjectName = sinon.stub().yields()
@ProjectModel.update.callsArgWith(2)
@newName = "new name here"
it "should update the project with the new name", (done)->
newName = "new name here"
@handler.renameProject @project_id, @newName, =>
@ProjectModel.update.calledWith({_id: @project_id}, {name: @newName}).should.equal true
done()
it "should tell the tpdsUpdateSender", (done)->
@handler.renameProject @project_id, @newName, =>
@tpdsUpdateSender.moveEntity.calledWith({project_id:@project_id, project_name:@project.name, newProjectName:@newName}).should.equal true
done()
it "should not do anything with an invalid name", (done) ->
@handler.validateProjectName = sinon.stub().yields(new Error("invalid name"))
@handler.renameProject @project_id, @newName, =>
@tpdsUpdateSender.moveEntity.called.should.equal false
@ProjectModel.update.called.should.equal false
done()
describe "validateProjectName", ->
it "should reject undefined names", (done) ->
@handler.validateProjectName undefined, (error) ->
expect(error).to.exist
done()
it "should reject empty names", (done) ->
@handler.validateProjectName "", (error) ->
expect(error).to.exist
done()
it "should reject names with /s", (done) ->
@handler.validateProjectName "foo/bar", (error) ->
expect(error).to.exist
done()
it "should reject names with \\s", (done) ->
@handler.validateProjectName "foo\\bar", (error) ->
expect(error).to.exist
done()
it "should reject long names", (done) ->
@handler.validateProjectName new Array(1000).join("a"), (error) ->
expect(error).to.exist
done()
it "should accept normal names", (done) ->
@handler.validateProjectName "foobar", (error) ->
expect(error).to.not.exist
done()
describe "ensureProjectNameIsUnique", ->
beforeEach ->
@result = {
owned: [{_id: 1, name:"name"}, {_id: 2, name: "name1"}, {_id: 3, name: "name11"}, {_id: 100, name: "numeric"}]
readAndWrite: [{_id: 4, name:"name2"}, {_id: 5, name:"name22"}]
readOnly: [{_id:6, name:"name3"}, {_id:7, name: "name33"}]
tokenReadAndWrite: [{_id:8, name:"name4"}, {_id:9, name:"name44"}]
tokenReadOnly: [{_id:10, name:"name5"}, {_id:11, name:"name55"}, {_id:12, name:"x".repeat(15)}]
}
for i in [1..20].concat([30..40])
@result.owned.push {_id: 100 + i, name: "numeric (#{i})"}
@ProjectGetter.findAllUsersProjects = sinon.stub().callsArgWith(2, null, @result)
it "should leave a unique name unchanged", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "unique-name", ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "unique-name"
expect(changed).to.equal false
done()
it "should append a suffix to an existing name", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "name1-test-suffix"
expect(changed).to.equal true
done()
it "should fallback to a second suffix when needed", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", ["1", "-test-suffix"], (error, name, changed) ->
expect(name).to.equal "name1-test-suffix"
expect(changed).to.equal true
done()
it "should truncate the name when append a suffix if the result is too long", (done) ->
@handler.MAX_PROJECT_NAME_LENGTH = 20
@handler.ensureProjectNameIsUnique @user_id, "x".repeat(15), ["-test-suffix"], (error, name, changed) ->
expect(name).to.equal "x".repeat(8) + "-test-suffix"
expect(changed).to.equal true
done()
it "should use a numeric index if no suffix is supplied", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name1", [], (error, name, changed) ->
expect(name).to.equal "name1 (1)"
expect(changed).to.equal true
done()
it "should use a numeric index if all suffixes are exhausted", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "name", ["1", "11"], (error, name, changed) ->
expect(name).to.equal "name (1)"
expect(changed).to.equal true
done()
it "should find the next lowest available numeric index for the base name", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric", [], (error, name, changed) ->
expect(name).to.equal "numeric (21)"
expect(changed).to.equal true
done()
it "should find the next available numeric index when a numeric index is already present", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric (5)", [], (error, name, changed) ->
expect(name).to.equal "numeric (21)"
expect(changed).to.equal true
done()
it "should not find a numeric index lower than the one already present", (done) ->
@handler.ensureProjectNameIsUnique @user_id, "numeric (31)", [], (error, name, changed) ->
expect(name).to.equal "numeric (41)"
expect(changed).to.equal true
done()
describe "fixProjectName", ->
it "should change empty names to Untitled", () ->
expect(@handler.fixProjectName "").to.equal "Untitled"
it "should replace / with -", () ->
expect(@handler.fixProjectName "foo/bar").to.equal "foo-bar"
it "should replace \\ with ''", () ->
expect(@handler.fixProjectName "foo \\ bar").to.equal "foo bar"
it "should truncate long names", () ->
expect(@handler.fixProjectName new Array(1000).join("a")).to.equal "a".repeat(150)
it "should accept normal names", () ->
expect(@handler.fixProjectName "foobar").to.equal "foobar"
describe "setPublicAccessLevel", ->
beforeEach ->
@ProjectModel.update.callsArgWith(2)
@accessLevel = "readOnly"
it "should update the project with the new level", (done)->
@handler.setPublicAccessLevel @project_id, @accessLevel, =>
@ProjectModel.update.calledWith({_id: @project_id}, {publicAccesLevel: @accessLevel}).should.equal true
done()
it 'should not produce an error', (done) ->
@handler.setPublicAccessLevel @project_id, @accessLevel, (err) =>
expect(err).to.not.exist
done()
describe 'when update produces an error', ->
beforeEach ->
@ProjectModel.update.callsArgWith(2, new Error('woops'))
it 'should produce an error', (done) ->
@handler.setPublicAccessLevel @project_id, @accessLevel, (err) =>
expect(err).to.exist
expect(err).to.be.instanceof Error
done()
describe "ensureTokensArePresent", ->
beforeEach ->
describe 'when the project has tokens', ->
beforeEach ->
@project =
_id: @project_id
tokens:
readOnly: 'aaa'
readAndWrite: 'PI:KEY:<KEY>END_PI'
readAndWritePrefix: '42'
@ProjectGetter.getProject = sinon.stub()
.callsArgWith(2, null, @project)
@ProjectModel.update = sinon.stub()
it 'should get the project', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectGetter.getProject.callCount).to.equal 1
expect(@ProjectGetter.getProject.calledWith(@project_id, {tokens: 1}))
.to.equal true
done()
it 'should not update the project with new tokens', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectModel.update.callCount).to.equal 0
done()
it 'should produce the tokens without error', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(err).to.not.exist
expect(tokens).to.deep.equal @project.tokens
done()
describe 'when tokens are missing', ->
beforeEach ->
@project =
_id: @project_id
@ProjectGetter.getProject = sinon.stub()
.callsArgWith(2, null, @project)
@readOnlyToken = 'PI:KEY:<KEY>END_PI'
@readAndWriteToken = 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
@readAndWriteTokenPrefix = 'PI:KEY:<KEY>END_PI2'
@ProjectTokenGenerator.generateUniqueReadOnlyToken = sinon.stub().callsArgWith(0, null, @readOnlyToken)
@ProjectTokenGenerator.readAndWriteToken = sinon.stub().returns({
token: @readAndWriteToken
numericPrefix: @readAndWriteTokenPrefix
})
@ProjectModel.update = sinon.stub()
.callsArgWith(2, null)
it 'should get the project', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectGetter.getProject.callCount).to.equal 1
expect(@ProjectGetter.getProject.calledWith(@project_id, {tokens: 1}))
.to.equal true
done()
it 'should update the project with new tokens', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(@ProjectTokenGenerator.generateUniqueReadOnlyToken.callCount)
.to.equal 1
expect(@ProjectTokenGenerator.readAndWriteToken.callCount)
.to.equal 1
expect(@ProjectModel.update.callCount).to.equal 1
expect(@ProjectModel.update.calledWith(
{_id: @project_id},
{
$set: {
tokens: {
readOnly: @readOnlyToken,
readAndWrite: @readAndWriteToken,
readAndWritePrefix: @readAndWriteTokenPrefix
}
}
}
)).to.equal true
done()
it 'should produce the tokens without error', (done) ->
@handler.ensureTokensArePresent @project_id, (err, tokens) =>
expect(err).to.not.exist
expect(tokens).to.deep.equal {
readOnly: @readOnlyToken,
readAndWrite: @readAndWriteToken,
readAndWritePrefix: @readAndWriteTokenPrefix
}
done()
|
[
{
"context": " assert.equal 0, compareIps '1.1.1.1', '1.1.1.1'\n\n it 'greater than', ->\n assert.equal 1",
"end": 306,
"score": 0.9393923282623291,
"start": 306,
"tag": "IP_ADDRESS",
"value": ""
},
{
"context": " it 'equal', ->\n assert.equal 0, compareIps '2601:8:b380:3f3:540b:fdbf:bc5:a6bf', '2601:8:b380:3f3:540b:fdbf:bc5:a6bf'\n\n it 'g",
"end": 592,
"score": 0.9997460842132568,
"start": 558,
"tag": "IP_ADDRESS",
"value": "2601:8:b380:3f3:540b:fdbf:bc5:a6bf"
},
{
"context": "compareIps '2601:8:b380:3f3:540b:fdbf:bc5:a6bf', '2601:8:b380:3f3:540b:fdbf:bc5:a6bf'\n\n it 'greater than', ->\n assert.equal 1,",
"end": 630,
"score": 0.9997261166572571,
"start": 596,
"tag": "IP_ADDRESS",
"value": "2601:8:b380:3f3:540b:fdbf:bc5:a6bf"
},
{
"context": "eater than', ->\n assert.equal 1, compareIps '2600:8:b380:3f3:540b:fdbf:bc5:a6bf', '2600:8:b380:3f3:540b:fdbf:bc5:a6be'\n\n it 'l",
"end": 727,
"score": 0.9997499585151672,
"start": 693,
"tag": "IP_ADDRESS",
"value": "2600:8:b380:3f3:540b:fdbf:bc5:a6bf"
},
{
"context": "compareIps '2600:8:b380:3f3:540b:fdbf:bc5:a6bf', '2600:8:b380:3f3:540b:fdbf:bc5:a6be'\n\n it 'less than', ->\n assert.equal -1, c",
"end": 765,
"score": 0.9997201561927795,
"start": 731,
"tag": "IP_ADDRESS",
"value": "2600:8:b380:3f3:540b:fdbf:bc5:a6be"
},
{
"context": "less than', ->\n assert.equal -1, compareIps '2600:8:b380:3f3:540b:fdbf:bc5:a6be', '2601:8:b380:3f3:540b:fdbf:bc5:a6bf'\n\n describ",
"end": 860,
"score": 0.9997243881225586,
"start": 826,
"tag": "IP_ADDRESS",
"value": "2600:8:b380:3f3:540b:fdbf:bc5:a6be"
},
{
"context": "compareIps '2600:8:b380:3f3:540b:fdbf:bc5:a6be', '2601:8:b380:3f3:540b:fdbf:bc5:a6bf'\n\n describe 'isIpInRange ipv4', ->\n\n it 'ip i",
"end": 898,
"score": 0.9997236132621765,
"start": 864,
"tag": "IP_ADDRESS",
"value": "2601:8:b380:3f3:540b:fdbf:bc5:a6bf"
},
{
"context": "ip in range', ->\n assert.isTrue isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.255']\n\n it 'i",
"end": 1009,
"score": 0.9997411370277405,
"start": 994,
"tag": "IP_ADDRESS",
"value": "123.123.123.123"
},
{
"context": " assert.isTrue isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.255']\n\n it 'ip less than range'",
"end": 1027,
"score": 0.9997288584709167,
"start": 1014,
"tag": "IP_ADDRESS",
"value": "123.123.123.0"
},
{
"context": "isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.255']\n\n it 'ip less than range', ->\n assert.i",
"end": 1046,
"score": 0.9996168613433838,
"start": 1031,
"tag": "IP_ADDRESS",
"value": "123.123.123.255"
},
{
"context": "than range', ->\n assert.isFalse isIpInRange '123.123.122.123', ['123.123.123.0', '123.123.123.123']\n\n it 'i",
"end": 1131,
"score": 0.9996833205223083,
"start": 1116,
"tag": "IP_ADDRESS",
"value": "123.123.122.123"
},
{
"context": " assert.isFalse isIpInRange '123.123.122.123', ['123.123.123.0', '123.123.123.123']\n\n it 'ip greater than ran",
"end": 1149,
"score": 0.9997498393058777,
"start": 1136,
"tag": "IP_ADDRESS",
"value": "123.123.123.0"
},
{
"context": "isIpInRange '123.123.122.123', ['123.123.123.0', '123.123.123.123']\n\n it 'ip greater than range', ->\n asser",
"end": 1168,
"score": 0.999721884727478,
"start": 1153,
"tag": "IP_ADDRESS",
"value": "123.123.123.123"
},
{
"context": "than range', ->\n assert.isFalse isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.122']\n\n it 'i",
"end": 1256,
"score": 0.9996426701545715,
"start": 1241,
"tag": "IP_ADDRESS",
"value": "123.123.123.123"
},
{
"context": " assert.isFalse isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.122']\n\n it 'ip in cidr range', ",
"end": 1274,
"score": 0.9997411966323853,
"start": 1261,
"tag": "IP_ADDRESS",
"value": "123.123.123.0"
},
{
"context": "isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.122']\n\n it 'ip in cidr range', ->\n assert.isT",
"end": 1293,
"score": 0.9997272491455078,
"start": 1278,
"tag": "IP_ADDRESS",
"value": "123.123.123.122"
},
{
"context": " cidr range', ->\n assert.isTrue isIpInRange '123.123.123.123', '123.123.0.0/16'\n\n it 'ip is not in cidr ran",
"end": 1375,
"score": 0.9997349381446838,
"start": 1360,
"tag": "IP_ADDRESS",
"value": "123.123.123.123"
},
{
"context": " assert.isTrue isIpInRange '123.123.123.123', '123.123.0.0/16'\n\n it 'ip is not in cidr range', ->\n a",
"end": 1390,
"score": 0.9997169971466064,
"start": 1379,
"tag": "IP_ADDRESS",
"value": "123.123.0.0"
},
{
"context": "cidr range', ->\n assert.isFalse isIpInRange '123.123.124.1', '123.123.123.0/24'\n\n describe 'isIpInRange ipv",
"end": 1480,
"score": 0.9997556209564209,
"start": 1467,
"tag": "IP_ADDRESS",
"value": "123.123.124.1"
},
{
"context": " assert.isFalse isIpInRange '123.123.124.1', '123.123.123.0/24'\n\n describe 'isIpInRange ipv6', ->\n\n it 'i",
"end": 1497,
"score": 0.9997357130050659,
"start": 1484,
"tag": "IP_ADDRESS",
"value": "123.123.123.0"
},
{
"context": "v6 in range', ->\n assert.isTrue isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0000', '00",
"end": 1637,
"score": 0.9997726678848267,
"start": 1598,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:0000:0001"
},
{
"context": "ange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0000', '0000:0000:0000:0000:0000:0000:0000:0002']\n\n ",
"end": 1681,
"score": 0.9997824430465698,
"start": 1642,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:0000:0000"
},
{
"context": "01', ['0000:0000:0000:0000:0000:0000:0000:0000', '0000:0000:0000:0000:0000:0000:0000:0002']\n\n it 'ipv6 not in range', ->\n assert.is",
"end": 1724,
"score": 0.999767005443573,
"start": 1685,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:0000:0002"
},
{
"context": "t in range', ->\n assert.isFalse isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0002', '00",
"end": 1832,
"score": 0.9997854232788086,
"start": 1793,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:0000:0001"
},
{
"context": "ange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0002', '0000:0000:0000:0000:0000:0000:0000:0003']\n\n ",
"end": 1876,
"score": 0.9997894167900085,
"start": 1837,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:0000:0002"
},
{
"context": "01', ['0000:0000:0000:0000:0000:0000:0000:0002', '0000:0000:0000:0000:0000:0000:0000:0003']\n\n it 'ipv4 in ipv6 range', ->\n assert.i",
"end": 1919,
"score": 0.999770998954773,
"start": 1880,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:0000:0003"
},
{
"context": " ipv6 range', ->\n assert.isTrue isIpInRange '127.0.0.1', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:",
"end": 1997,
"score": 0.9997603893280029,
"start": 1988,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "->\n assert.isTrue isIpInRange '127.0.0.1', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']\n\n it 'ipv4 not in i",
"end": 2023,
"score": 0.9997313022613525,
"start": 2002,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:ffff:7f00:1"
},
{
"context": "IpInRange '127.0.0.1', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']\n\n it 'ipv4 not in ipv6 range', ->\n asse",
"end": 2048,
"score": 0.9996876120567322,
"start": 2027,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:ffff:7f00:2"
},
{
"context": "ipv6 range', ->\n assert.isFalse isIpInRange '127.0.0.3', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:",
"end": 2131,
"score": 0.9997521638870239,
"start": 2122,
"tag": "IP_ADDRESS",
"value": "127.0.0.3"
},
{
"context": ">\n assert.isFalse isIpInRange '127.0.0.3', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']\n\n it 'ipv6 in ipv6 ",
"end": 2157,
"score": 0.999735951423645,
"start": 2136,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:ffff:7f00:1"
},
{
"context": "IpInRange '127.0.0.3', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']\n\n it 'ipv6 in ipv6 cidr', ->\n assert.is",
"end": 2182,
"score": 0.9996741414070129,
"start": 2161,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:ffff:7f00:2"
},
{
"context": "n ipv6 cidr', ->\n assert.isTrue isIpInRange '0000:0000:0000:0000:0000:0000:1000:0005', '0000:0000:0000:0000:0000:0000:1000:0000/112'\n\n",
"end": 2289,
"score": 0.999562680721283,
"start": 2250,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000:1000:0005"
},
{
"context": "Range '0000:0000:0000:0000:0000:0000:1000:0005', '0000:0000:0000:0000:0000:0000:1000:0000/112'\n\n it 'ipv6 in ipv4 cidr', ->\n ",
"end": 2322,
"score": 0.9730386734008789,
"start": 2293,
"tag": "IP_ADDRESS",
"value": "0000:0000:0000:0000:0000:0000"
},
{
"context": "n ipv4 cidr', ->\n assert.isTrue isIpInRange '0:0:0:0:0:ffff:8e33:1', '142.51.0.0/16'\n\n it 'ipv6 not in ipv4 cidr'",
"end": 2424,
"score": 0.9996445775032043,
"start": 2403,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:ffff:8e33:1"
},
{
"context": "sert.isTrue isIpInRange '0:0:0:0:0:ffff:8e33:1', '142.51.0.0/16'\n\n it 'ipv6 not in ipv4 cidr', ->\n ass",
"end": 2438,
"score": 0.9997243881225586,
"start": 2428,
"tag": "IP_ADDRESS",
"value": "142.51.0.0"
},
{
"context": " ipv4 cidr', ->\n assert.isFalse isIpInRange '0:0:0:0:0:ffff:8e34:1', '142.51.0.0/16'\n\n describe 'isIpInAnyRange', -",
"end": 2534,
"score": 0.999618411064148,
"start": 2513,
"tag": "IP_ADDRESS",
"value": "0:0:0:0:0:ffff:8e34:1"
},
{
"context": "ert.isFalse isIpInRange '0:0:0:0:0:ffff:8e34:1', '142.51.0.0/16'\n\n describe 'isIpInAnyRange', ->\n\n r1 = ['",
"end": 2548,
"score": 0.9997259378433228,
"start": 2538,
"tag": "IP_ADDRESS",
"value": "142.51.0.0"
},
{
"context": ", [r1, r2]\n\n it 'false positive not in ranges #12', ->\n assert.isFalse isIpInAnyRange '199.19.",
"end": 2958,
"score": 0.9992607831954956,
"start": 2956,
"tag": "IP_ADDRESS",
"value": "12"
},
{
"context": "ges #12', ->\n assert.isFalse isIpInAnyRange '199.19.250.20', [[\"199.19.16.0\", \"199.19.27.255\"], [\"4.42.247.2",
"end": 3014,
"score": 0.9997059106826782,
"start": 3001,
"tag": "IP_ADDRESS",
"value": "199.19.250.20"
},
{
"context": "assert.isFalse isIpInAnyRange '199.19.250.20', [[\"199.19.16.0\", \"199.19.27.255\"], [\"4.42.247.224\", \"4.42.247.25",
"end": 3031,
"score": 0.9996997714042664,
"start": 3020,
"tag": "IP_ADDRESS",
"value": "199.19.16.0"
},
{
"context": "isIpInAnyRange '199.19.250.20', [[\"199.19.16.0\", \"199.19.27.255\"], [\"4.42.247.224\", \"4.42.247.255\"]]\n assert",
"end": 3048,
"score": 0.999706506729126,
"start": 3035,
"tag": "IP_ADDRESS",
"value": "199.19.27.255"
},
{
"context": ".19.250.20', [[\"199.19.16.0\", \"199.19.27.255\"], [\"4.42.247.224\", \"4.42.247.255\"]]\n assert.isFalse isIpInAny",
"end": 3066,
"score": 0.9997275471687317,
"start": 3054,
"tag": "IP_ADDRESS",
"value": "4.42.247.224"
},
{
"context": "199.19.16.0\", \"199.19.27.255\"], [\"4.42.247.224\", \"4.42.247.255\"]]\n assert.isFalse isIpInAnyRange '39.255.25",
"end": 3082,
"score": 0.9997265338897705,
"start": 3070,
"tag": "IP_ADDRESS",
"value": "4.42.247.255"
},
{
"context": "2.247.255\"]]\n assert.isFalse isIpInAnyRange '39.255.255.148', [[\"40.0.0.0\", \"40.127.255.255\"], [\"40.144.0.0\",",
"end": 3137,
"score": 0.9997016191482544,
"start": 3123,
"tag": "IP_ADDRESS",
"value": "39.255.255.148"
},
{
"context": "ssert.isFalse isIpInAnyRange '39.255.255.148', [[\"40.0.0.0\", \"40.127.255.255\"], [\"40.144.0.0\", \"40.255.255.2",
"end": 3151,
"score": 0.9997357726097107,
"start": 3143,
"tag": "IP_ADDRESS",
"value": "40.0.0.0"
},
{
"context": "e isIpInAnyRange '39.255.255.148', [[\"40.0.0.0\", \"40.127.255.255\"], [\"40.144.0.0\", \"40.255.255.255\"]]\n\n describe ",
"end": 3169,
"score": 0.999728798866272,
"start": 3155,
"tag": "IP_ADDRESS",
"value": "40.127.255.255"
},
{
"context": ".255.255.148', [[\"40.0.0.0\", \"40.127.255.255\"], [\"40.144.0.0\", \"40.255.255.255\"]]\n\n describe 'getStatus', ->\n",
"end": 3185,
"score": 0.9997413754463196,
"start": 3175,
"tag": "IP_ADDRESS",
"value": "40.144.0.0"
},
{
"context": " [[\"40.0.0.0\", \"40.127.255.255\"], [\"40.144.0.0\", \"40.255.255.255\"]]\n\n describe 'getStatus', ->\n\n it 'works', -",
"end": 3203,
"score": 0.9997353553771973,
"start": 3189,
"tag": "IP_ADDRESS",
"value": "40.255.255.255"
},
{
"context": "e: 'Foo', url: 'http://example.com'\n name = 'Bar'\n template = \"{{page}} edited by {{name}} {{",
"end": 3324,
"score": 0.9369162917137146,
"start": 3321,
"tag": "NAME",
"value": "Bar"
},
{
"context": " url: 'http://t.co/BzHLWr31Ce'\n name = 'test'\n template = \"{{page}} edited by {{name}} {{",
"end": 3703,
"score": 0.9650277495384216,
"start": 3699,
"tag": "NAME",
"value": "test"
}
] | test.coffee | patrick478/HudsonWikiEdits | 7 | anon = require './anon'
assert = require('chai').assert
getStatus = anon.getStatus
compareIps = anon.compareIps
isIpInRange = anon.isIpInRange
isIpInAnyRange = anon.isIpInAnyRange
describe 'anon', ->
describe "compareIps ipv4", ->
it 'equal', ->
assert.equal 0, compareIps '1.1.1.1', '1.1.1.1'
it 'greater than', ->
assert.equal 1, compareIps '1.1.1.2', '1.1.1.1'
it 'less than', ->
assert.equal -1, compareIps '1.1.1.1', '1.1.1.2'
describe "compareIps ipv6", ->
it 'equal', ->
assert.equal 0, compareIps '2601:8:b380:3f3:540b:fdbf:bc5:a6bf', '2601:8:b380:3f3:540b:fdbf:bc5:a6bf'
it 'greater than', ->
assert.equal 1, compareIps '2600:8:b380:3f3:540b:fdbf:bc5:a6bf', '2600:8:b380:3f3:540b:fdbf:bc5:a6be'
it 'less than', ->
assert.equal -1, compareIps '2600:8:b380:3f3:540b:fdbf:bc5:a6be', '2601:8:b380:3f3:540b:fdbf:bc5:a6bf'
describe 'isIpInRange ipv4', ->
it 'ip in range', ->
assert.isTrue isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.255']
it 'ip less than range', ->
assert.isFalse isIpInRange '123.123.122.123', ['123.123.123.0', '123.123.123.123']
it 'ip greater than range', ->
assert.isFalse isIpInRange '123.123.123.123', ['123.123.123.0', '123.123.123.122']
it 'ip in cidr range', ->
assert.isTrue isIpInRange '123.123.123.123', '123.123.0.0/16'
it 'ip is not in cidr range', ->
assert.isFalse isIpInRange '123.123.124.1', '123.123.123.0/24'
describe 'isIpInRange ipv6', ->
it 'ipv6 in range', ->
assert.isTrue isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0000', '0000:0000:0000:0000:0000:0000:0000:0002']
it 'ipv6 not in range', ->
assert.isFalse isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0002', '0000:0000:0000:0000:0000:0000:0000:0003']
it 'ipv4 in ipv6 range', ->
assert.isTrue isIpInRange '127.0.0.1', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']
it 'ipv4 not in ipv6 range', ->
assert.isFalse isIpInRange '127.0.0.3', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']
it 'ipv6 in ipv6 cidr', ->
assert.isTrue isIpInRange '0000:0000:0000:0000:0000:0000:1000:0005', '0000:0000:0000:0000:0000:0000:1000:0000/112'
it 'ipv6 in ipv4 cidr', ->
assert.isTrue isIpInRange '0:0:0:0:0:ffff:8e33:1', '142.51.0.0/16'
it 'ipv6 not in ipv4 cidr', ->
assert.isFalse isIpInRange '0:0:0:0:0:ffff:8e34:1', '142.51.0.0/16'
describe 'isIpInAnyRange', ->
r1 = ['1.1.1.0', '1.1.1.5']
r2 = ['2.2.2.0', '2.2.2.5']
it 'ip in first range', ->
assert.isTrue isIpInAnyRange '1.1.1.1', [r1, r2]
it 'ip in second range', ->
assert.isTrue isIpInAnyRange '2.2.2.1', [r1, r2]
it 'ip not in any ranges', ->
assert.isFalse isIpInAnyRange '1.1.1.6', [r1, r2]
it 'false positive not in ranges #12', ->
assert.isFalse isIpInAnyRange '199.19.250.20', [["199.19.16.0", "199.19.27.255"], ["4.42.247.224", "4.42.247.255"]]
assert.isFalse isIpInAnyRange '39.255.255.148', [["40.0.0.0", "40.127.255.255"], ["40.144.0.0", "40.255.255.255"]]
describe 'getStatus', ->
it 'works', ->
edit = page: 'Foo', url: 'http://example.com'
name = 'Bar'
template = "{{page}} edited by {{name}} {{&url}}"
result = getStatus edit, name, template
assert.equal 'Foo edited by Bar http://example.com', result
it 'truncates when > 140 chars', ->
# twitter shortens al urls, so we use a shortened one here
edit =
page: Array(140).join 'x'
url: 'http://t.co/BzHLWr31Ce'
name = 'test'
template = "{{page}} edited by {{name}} {{&url}}"
result = getStatus edit, name, template
assert.isTrue result.length <= 140
| 204364 | anon = require './anon'
assert = require('chai').assert
getStatus = anon.getStatus
compareIps = anon.compareIps
isIpInRange = anon.isIpInRange
isIpInAnyRange = anon.isIpInAnyRange
describe 'anon', ->
describe "compareIps ipv4", ->
it 'equal', ->
assert.equal 0, compareIps '1.1.1.1', '1.1.1.1'
it 'greater than', ->
assert.equal 1, compareIps '1.1.1.2', '1.1.1.1'
it 'less than', ->
assert.equal -1, compareIps '1.1.1.1', '1.1.1.2'
describe "compareIps ipv6", ->
it 'equal', ->
assert.equal 0, compareIps 'fc00:db20:35b:7399::5', 'fc00:db20:35b:7399::5'
it 'greater than', ->
assert.equal 1, compareIps 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b', 'fc00:e968:6179::de52:7100'
it 'less than', ->
assert.equal -1, compareIps 'fc00:e968:6179::de52:7100', 'fc00:db20:35b:7399::5'
describe 'isIpInRange ipv4', ->
it 'ip in range', ->
assert.isTrue isIpInRange '172.16.58.3', ['192.168.3.11', '172.16.17.32']
it 'ip less than range', ->
assert.isFalse isIpInRange '172.16.31.10', ['192.168.3.11', '172.16.58.3']
it 'ip greater than range', ->
assert.isFalse isIpInRange '172.16.58.3', ['192.168.3.11', '172.16.17.32']
it 'ip in cidr range', ->
assert.isTrue isIpInRange '172.16.58.3', '172.16.17.32/16'
it 'ip is not in cidr range', ->
assert.isFalse isIpInRange '192.168.3.11', '192.168.3.11/24'
describe 'isIpInRange ipv6', ->
it 'ipv6 in range', ->
assert.isTrue isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0000', 'fdf8:f53e:61e4::18']
it 'ipv6 not in range', ->
assert.isFalse isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['fdf8:f53e:61e4::18', 'fc00:e968:6179::de52:7100']
it 'ipv4 in ipv6 range', ->
assert.isTrue isIpInRange '127.0.0.1', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']
it 'ipv4 not in ipv6 range', ->
assert.isFalse isIpInRange '127.0.0.3', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']
it 'ipv6 in ipv6 cidr', ->
assert.isTrue isIpInRange 'fdf8:f53e:61e4::18', '0000:0000:0000:0000:0000:0000:1000:0000/112'
it 'ipv6 in ipv4 cidr', ->
assert.isTrue isIpInRange 'fc00:e968:6179::de52:7100', '192.168.3.11/16'
it 'ipv6 not in ipv4 cidr', ->
assert.isFalse isIpInRange 'fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b', '192.168.3.11/16'
describe 'isIpInAnyRange', ->
r1 = ['1.1.1.0', '1.1.1.5']
r2 = ['2.2.2.0', '2.2.2.5']
it 'ip in first range', ->
assert.isTrue isIpInAnyRange '1.1.1.1', [r1, r2]
it 'ip in second range', ->
assert.isTrue isIpInAnyRange '2.2.2.1', [r1, r2]
it 'ip not in any ranges', ->
assert.isFalse isIpInAnyRange '1.1.1.6', [r1, r2]
it 'false positive not in ranges #12', ->
assert.isFalse isIpInAnyRange '172.16.17.32', [["172.16.58.3", "172.16.31.10"], ["172.16.31.10", "172.16.58.3"]]
assert.isFalse isIpInAnyRange '172.16.17.32', [["192.168.3.11", "172.16.17.32"], ["192.168.127.12", "192.168.3.11"]]
describe 'getStatus', ->
it 'works', ->
edit = page: 'Foo', url: 'http://example.com'
name = '<NAME>'
template = "{{page}} edited by {{name}} {{&url}}"
result = getStatus edit, name, template
assert.equal 'Foo edited by Bar http://example.com', result
it 'truncates when > 140 chars', ->
# twitter shortens al urls, so we use a shortened one here
edit =
page: Array(140).join 'x'
url: 'http://t.co/BzHLWr31Ce'
name = '<NAME>'
template = "{{page}} edited by {{name}} {{&url}}"
result = getStatus edit, name, template
assert.isTrue result.length <= 140
| true | anon = require './anon'
assert = require('chai').assert
getStatus = anon.getStatus
compareIps = anon.compareIps
isIpInRange = anon.isIpInRange
isIpInAnyRange = anon.isIpInAnyRange
describe 'anon', ->
describe "compareIps ipv4", ->
it 'equal', ->
assert.equal 0, compareIps '1.1.1.1', '1.1.1.1'
it 'greater than', ->
assert.equal 1, compareIps '1.1.1.2', '1.1.1.1'
it 'less than', ->
assert.equal -1, compareIps '1.1.1.1', '1.1.1.2'
describe "compareIps ipv6", ->
it 'equal', ->
assert.equal 0, compareIps 'PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI', 'PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI'
it 'greater than', ->
assert.equal 1, compareIps 'PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI', 'PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI'
it 'less than', ->
assert.equal -1, compareIps 'PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI', 'PI:IP_ADDRESS:fc00:db20:35b:7399::5END_PI'
describe 'isIpInRange ipv4', ->
it 'ip in range', ->
assert.isTrue isIpInRange 'PI:IP_ADDRESS:172.16.58.3END_PI', ['PI:IP_ADDRESS:192.168.3.11END_PI', 'PI:IP_ADDRESS:172.16.17.32END_PI']
it 'ip less than range', ->
assert.isFalse isIpInRange 'PI:IP_ADDRESS:172.16.31.10END_PI', ['PI:IP_ADDRESS:192.168.3.11END_PI', 'PI:IP_ADDRESS:172.16.58.3END_PI']
it 'ip greater than range', ->
assert.isFalse isIpInRange 'PI:IP_ADDRESS:172.16.58.3END_PI', ['PI:IP_ADDRESS:192.168.3.11END_PI', 'PI:IP_ADDRESS:172.16.17.32END_PI']
it 'ip in cidr range', ->
assert.isTrue isIpInRange 'PI:IP_ADDRESS:172.16.58.3END_PI', 'PI:IP_ADDRESS:172.16.17.32END_PI/16'
it 'ip is not in cidr range', ->
assert.isFalse isIpInRange 'PI:IP_ADDRESS:192.168.3.11END_PI', 'PI:IP_ADDRESS:192.168.3.11END_PI/24'
describe 'isIpInRange ipv6', ->
it 'ipv6 in range', ->
assert.isTrue isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['0000:0000:0000:0000:0000:0000:0000:0000', 'PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI']
it 'ipv6 not in range', ->
assert.isFalse isIpInRange '0000:0000:0000:0000:0000:0000:0000:0001', ['PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI', 'PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI']
it 'ipv4 in ipv6 range', ->
assert.isTrue isIpInRange '127.0.0.1', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']
it 'ipv4 not in ipv6 range', ->
assert.isFalse isIpInRange '127.0.0.3', ['0:0:0:0:0:ffff:7f00:1', '0:0:0:0:0:ffff:7f00:2']
it 'ipv6 in ipv6 cidr', ->
assert.isTrue isIpInRange 'PI:IP_ADDRESS:fdf8:f53e:61e4::18END_PI', '0000:0000:0000:0000:0000:0000:1000:0000/112'
it 'ipv6 in ipv4 cidr', ->
assert.isTrue isIpInRange 'PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI', 'PI:IP_ADDRESS:192.168.3.11END_PI/16'
it 'ipv6 not in ipv4 cidr', ->
assert.isFalse isIpInRange 'PI:IP_ADDRESS:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5bEND_PI', 'PI:IP_ADDRESS:192.168.3.11END_PI/16'
describe 'isIpInAnyRange', ->
r1 = ['1.1.1.0', '1.1.1.5']
r2 = ['2.2.2.0', '2.2.2.5']
it 'ip in first range', ->
assert.isTrue isIpInAnyRange '1.1.1.1', [r1, r2]
it 'ip in second range', ->
assert.isTrue isIpInAnyRange '2.2.2.1', [r1, r2]
it 'ip not in any ranges', ->
assert.isFalse isIpInAnyRange '1.1.1.6', [r1, r2]
it 'false positive not in ranges #12', ->
assert.isFalse isIpInAnyRange 'PI:IP_ADDRESS:172.16.17.32END_PI', [["PI:IP_ADDRESS:172.16.58.3END_PI", "PI:IP_ADDRESS:172.16.31.10END_PI"], ["PI:IP_ADDRESS:172.16.31.10END_PI", "PI:IP_ADDRESS:172.16.58.3END_PI"]]
assert.isFalse isIpInAnyRange 'PI:IP_ADDRESS:172.16.17.32END_PI', [["PI:IP_ADDRESS:192.168.3.11END_PI", "PI:IP_ADDRESS:172.16.17.32END_PI"], ["PI:IP_ADDRESS:192.168.127.12END_PI", "PI:IP_ADDRESS:192.168.3.11END_PI"]]
describe 'getStatus', ->
it 'works', ->
edit = page: 'Foo', url: 'http://example.com'
name = 'PI:NAME:<NAME>END_PI'
template = "{{page}} edited by {{name}} {{&url}}"
result = getStatus edit, name, template
assert.equal 'Foo edited by Bar http://example.com', result
it 'truncates when > 140 chars', ->
# twitter shortens al urls, so we use a shortened one here
edit =
page: Array(140).join 'x'
url: 'http://t.co/BzHLWr31Ce'
name = 'PI:NAME:<NAME>END_PI'
template = "{{page}} edited by {{name}} {{&url}}"
result = getStatus edit, name, template
assert.isTrue result.length <= 140
|
[
{
"context": "Formbuilder.registerField 'text',\n\n name: 'Short Answer'\n\n order: 0\n\n view: \"\"\"\n <% var initial_valu",
"end": 56,
"score": 0.8460570573806763,
"start": 44,
"tag": "NAME",
"value": "Short Answer"
}
] | src/scripts/fields/text.coffee | SanjayHarkaj/formbuilder_custom | 0 | Formbuilder.registerField 'text',
name: 'Short Answer'
order: 0
view: """
<% var initial_value = rf.get(Formbuilder.options.mappings.INITIAL_VALUE); %>
<input type='text' value='<%= initial_value %>' class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>' />
"""
edit: """
<% var minlength = rf.get(Formbuilder.options.mappings.MINLENGTH); %>
<% var maxlength = rf.get(Formbuilder.options.mappings.MAXLENGTH); %>
<%= Formbuilder.templates['edit/initial_value']() %>
<%= Formbuilder.templates['edit/min_max_length']({ rf: rf }) %>
"""
addButton: """
<span class="fa fa-font"></span> Text
"""
| 79130 | Formbuilder.registerField 'text',
name: '<NAME>'
order: 0
view: """
<% var initial_value = rf.get(Formbuilder.options.mappings.INITIAL_VALUE); %>
<input type='text' value='<%= initial_value %>' class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>' />
"""
edit: """
<% var minlength = rf.get(Formbuilder.options.mappings.MINLENGTH); %>
<% var maxlength = rf.get(Formbuilder.options.mappings.MAXLENGTH); %>
<%= Formbuilder.templates['edit/initial_value']() %>
<%= Formbuilder.templates['edit/min_max_length']({ rf: rf }) %>
"""
addButton: """
<span class="fa fa-font"></span> Text
"""
| true | Formbuilder.registerField 'text',
name: 'PI:NAME:<NAME>END_PI'
order: 0
view: """
<% var initial_value = rf.get(Formbuilder.options.mappings.INITIAL_VALUE); %>
<input type='text' value='<%= initial_value %>' class='rf-size-<%= rf.get(Formbuilder.options.mappings.SIZE) %>' />
"""
edit: """
<% var minlength = rf.get(Formbuilder.options.mappings.MINLENGTH); %>
<% var maxlength = rf.get(Formbuilder.options.mappings.MAXLENGTH); %>
<%= Formbuilder.templates['edit/initial_value']() %>
<%= Formbuilder.templates['edit/min_max_length']({ rf: rf }) %>
"""
addButton: """
<span class="fa fa-font"></span> Text
"""
|
[
{
"context": "esource.assignAttributes({\n name: 'New name'\n })\n\n it 'clones resource\\'s",
"end": 43703,
"score": 0.9263346195220947,
"start": 43695,
"tag": "NAME",
"value": "New name"
},
{
"context": " @clone = @resource.buildCustomer({ name: 'J' })\n\n it 'returns owner of relationship'",
"end": 51190,
"score": 0.9961802959442139,
"start": 51189,
"tag": "NAME",
"value": "J"
},
{
"context": ">\n @resource.createCustomer({ name: 'M' })\n .then window.onSuccess\n\n ",
"end": 51606,
"score": 0.9988154768943787,
"start": 51605,
"tag": "NAME",
"value": "M"
},
{
"context": " @clone = @resource.comments().build({ body: 'J' })\n\n it 'returns owner of relationship'",
"end": 55058,
"score": 0.8651031255722046,
"start": 55057,
"tag": "NAME",
"value": "J"
},
{
"context": " @resource.comments().create({ body: 'M' })\n .then window.onSuccess\n\n ",
"end": 55477,
"score": 0.9481326341629028,
"start": 55476,
"tag": "NAME",
"value": "M"
}
] | spec/immutable.coffee | asfktz/active-resource.js | 0 | describe 'ActiveResource', ->
beforeEach ->
window.onSuccess = jasmine.createSpy('onSuccess')
window.onFailure = jasmine.createSpy('onFailure')
window.onCompletion = jasmine.createSpy('onCompletion')
afterEach ->
moxios.uninstall()
describe '::Immutable', ->
beforeAll ->
window.ImmutableLibrary = ActiveResource.createResourceLibrary(
'https://example.com/api/v1',
immutable: true
)
moxios.install(ImmutableLibrary.interface.axios)
class ImmutableLibrary.Comment extends ImmutableLibrary.Base
this.className = 'Comment'
this.queryName = 'comments'
this.belongsTo 'order'
class ImmutableLibrary.Customer extends ImmutableLibrary.Base
this.className = 'Customer'
this.queryName = 'customers'
this.attributes('name')
this.hasMany 'orders', inverseOf: 'customer'
class ImmutableLibrary.GiftCard extends ImmutableLibrary.Base
this.className = 'GiftCard'
this.queryName = 'gift_cards'
this.hasOne 'order'
class ImmutableLibrary.Order extends ImmutableLibrary.Base
this.className = 'Order'
this.queryName = 'orders'
this.attributes('price', 'tax')
this.belongsTo 'customer', autosave: true, inverseOf: 'orders'
this.belongsTo 'giftCard'
this.hasMany 'comments'
this.hasMany 'orderItems', autosave: true, inverseOf: 'order'
this.hasOne 'rating', autosave: true
class ImmutableLibrary.OrderItem extends ImmutableLibrary.Base
this.className = 'OrderItem'
this.queryName = 'order_items'
this.attributes('amount')
this.belongsTo 'order', inverseOf: 'orderItems'
class ImmutableLibrary.Rating extends ImmutableLibrary.Base
this.className = 'Rating'
this.queryName = 'ratings'
this.attributes('value')
this.belongsTo 'order'
describe 'adding errors', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe '#add', ->
beforeEach ->
@resource2 = @resource.errors().add('field', 'code', 'message')
it 'returns new resource', ->
expect(@resource2).not.toBe(@resource)
it 'adds error to new resource', ->
expect(@resource2.errors().size()).toBe(1)
describe '#addAll', ->
beforeEach ->
@resource2 = @resource.errors().addAll(
['field', 'code', 'message'],
['field2', 'code2', 'message2'],
)
it 'returns new resource', ->
expect(@resource2).not.toBe(@resource)
it 'adds errors to new resource', ->
expect(@resource2.errors().size()).toBe(2)
describe 'propagating errors', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe 'singular relationship', ->
beforeEach ->
@resource = @resource.buildCustomer()
@customer = @resource.customer()
@errors = ActiveResource.Collection.build([
{
field: 'customer',
code: 'invalid',
message: 'invalid'
},
{
field: 'customer.firstName',
code: 'invalid',
message: 'invalid'
},
{
field: 'customer.lastName',
code: 'invalid',
message: 'invalid'
}
])
@resource.errors().propagate(@errors)
it 'adds nested base errors to the nested relationship resource base', ->
expect(@resource.customer().errors().forBase().size()).toEqual(1)
it 'adds nested field errors to the nested relationship resource', ->
expect(@resource.customer().errors().forField('firstName').size()).toEqual(1)
it 'clones the relationship resource', ->
expect(@resource.customer()).not.toBe(@customer)
describe 'repeated propagation', ->
beforeEach ->
@resource.errors().propagate(@errors)
it 'does not result in duplicate errors', ->
expect(@resource.customer().errors().forField('firstName').size()).toEqual(1)
describe 'collection relationship', ->
beforeEach ->
@resource = @resource.orderItems().build()
@orderItem = @resource.orderItems().target().first()
@errors = ActiveResource.Collection.build([
{
field: 'orderItems',
code: 'invalid',
message: 'invalid'
},
{
field: 'orderItems.amount',
code: 'invalid',
message: 'invalid'
}
])
@resource.errors().propagate(@errors)
it 'adds non-nested errors to the resource', ->
expect(@resource.errors().forField('orderItems').size()).toEqual(1)
it 'adds nested errors to the nested relationship resource', ->
expect(@resource.orderItems().target().first().errors().forField('amount').size()).toEqual(1)
it 'clones the relationship resource', ->
expect(@resource.orderItems().target().first()).not.toBe(@orderItem)
it 'clones relationships to relationship resource', ->
expect(@resource.orderItems().target().first().order()).toBe(@resource)
it 'does not duplicate cloned resource on the relationship', ->
expect(@resource.orderItems().target().size()).toBe(1)
describe 'repeated propagation', ->
beforeEach ->
@resource.errors().propagate(@errors)
it 'does not result in duplicate errors', ->
expect(@resource.orderItems().target().first().errors().forField('amount').size()).toEqual(1)
describe 'when resource unpersisted', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe 'assigning attributes', ->
beforeEach ->
@resource2 = @resource.assignAttributes({
price: 3.0
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.price).toBeUndefined()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.price).toEqual(3.0)
it 'creates a new resource with the changed attribute tracked', ->
expect(@resource2.changedFields().include('price')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save (resource3) =>
@resource3 = resource3
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.success)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not persist new changes from the server to the old resource', ->
@promise.then =>
expect(@resource2.tax).toBeUndefined()
it 'indicates the attribute was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('price')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'persists new changes from the server', ->
@promise.then =>
expect(@resource3.tax).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('price')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the attribute was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('price')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'maintains attribute on new resource', ->
@promise.catch =>
expect(@resource3.price).toEqual(3.0)
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'indicates the attribute was changed on the new resource', ->
@promise.catch =>
expect(@resource3.changedFields().include('price')).toBeTruthy()
describe 'updating attributes', ->
beforeEach ->
@resource.update({
price: 3.0
}, (resource2) =>
@resource2 = resource2
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
it 'clones a new resource', ->
@promise.then =>
expect(@resource).not.toBe(@resource2)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource.persisted()).toBeFalsy()
it 'does not change the old resource', ->
@promise.then =>
expect(@resource.price).toBeUndefined()
it 'does not persist new changes from the server to the old resource', ->
@promise.then =>
expect(@resource.tax).toBeUndefined()
it 'does not track the change on the old resource', ->
@promise.then =>
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'persists a new resource with the changes', ->
@promise.then =>
expect(@resource2.price).toEqual(3.0)
it 'persists new changes from the server', ->
@promise.then =>
expect(@resource2.tax).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('price')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource).not.toBe(@resource2)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource.persisted()).toBeFalsy()
it 'does not change the old resource', ->
@promise.catch =>
expect(@resource.price).toBeUndefined()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource.errors().empty()).toBeTruthy()
it 'does not indicate the attribute was changed on the old resource', ->
@promise.catch =>
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not change attribute on new resource', ->
@promise.catch =>
expect(@resource2.price).toEqual(null)
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeFalsy()
it 'does not indicate the attribute was changed on the new resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('price')).toBeFalsy()
describe 'assigning relationships', ->
describe 'singular relationship', ->
describe 'when inverse is singular', ->
beforeEach ->
@singularResource = ImmutableLibrary.GiftCard.build(id: '1')
@resource2 = @resource.assignAttributes({
giftCard: @singularResource
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.giftCard()).toBeNull()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('giftCard')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.giftCard()).toEqual(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise.then =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise.then =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.giftCard().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('giftCard')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise.catch =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.giftCard().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('giftCard')).toBeTruthy()
describe 'when inverse is collection', ->
beforeEach ->
@singularResource = ImmutableLibrary.Customer.build(id: '1')
@resource2 = @resource.assignAttributes({
customer: @singularResource
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.customer()).toBeNull()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('customer')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.customer()).toEqual(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('customer')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('customer')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise.then =>
expect(@resource2.customer()).toBe(@resource3.customer())
it 'changes the inverse target of the new relationship resource', ->
@promise.then =>
expect(@resource3.customer().orders().target().toArray()).toEqual([@resource3])
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.customer().changedFields().include('orders')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('customer')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('customer')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise.catch =>
expect(@resource2.customer()).toBe(@resource3.customer())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.customer().orders().target().toArray()).toEqual([@resource3])
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.customer().changedFields().include('orders')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('customer')).toBeTruthy()
describe 'collection relationship', ->
beforeEach ->
@collection = ActiveResource::Collection.build([
ImmutableLibrary.Comment.build(id: '1'),
ImmutableLibrary.Comment.build(id: '2')
])
@resource2 = @resource.assignAttributes({
comments: @collection
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.comments().empty()).toBeTruthy()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('comments')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.comments().size()).toEqual(2)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('comments')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resources to clone', ->
@promise.then =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the new relationship resources', ->
@promise.then =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('comments')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'indicates the new relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('comments')).toBeTruthy()
describe 'when resource persisted', ->
beforeEach ->
ImmutableLibrary.Order.includes('giftCard','orderItems').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'reload', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.reload()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes2)
.then =>
@resource2 = window.onSuccess.calls.mostRecent().args[0]
it 'clones resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'assigns new attributes', ->
@promise2.then =>
expect(@resource2.total).toEqual(9.0)
it 'assigns new singular relationship', ->
@promise2.then =>
expect(@resource2.rating()).toBeNull()
it 'assigns new collection relationship', ->
@promise2.then =>
expect(@resource2.orderItems().target().toArray()).toEqual([])
it 'does not assign unloaded relationships', ->
@promise2.then =>
expect(@resource2.comments().size()).toEqual(2)
describe 'assigning attributes', ->
beforeEach ->
@promise2 = @promise.then =>
@resource2 = @resource.assignAttributes({
tax: 15.0
})
it 'clones a new resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
@promise2.then =>
expect(@resource.tax).toEqual(5.0)
it 'does not track the change on the old resource', ->
@promise2.then =>
expect(@resource.changedFields().include('tax')).toBeFalsy()
it 'creates a new persisted resource', ->
@promise2.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'creates a new resource with the changes', ->
@promise2.then =>
expect(@resource2.tax).toEqual(15.0)
it 'creates a new resource with the changed attribute tracked', ->
@promise2.then =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
describe 'saving the changed persisted resource', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise4.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist new changes from the server to the old resource', ->
@promise4.then =>
expect(@resource2.balance).toBeUndefined()
it 'indicates the attribute was still changed on the old resource', ->
@promise4.then =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
it 'persists a new resource', ->
@promise4.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'persists new changes from the server', ->
@promise4.then =>
expect(@resource3.balance).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise4.then =>
expect(@resource3.changedFields().include('tax')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise4.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise4.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise4.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the attribute was still changed on the old resource', ->
@promise4.catch =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
it 'persists the new resource', ->
@promise4.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'maintains attribute on new resource', ->
@promise4.catch =>
expect(@resource3.tax).toEqual(15.0)
it 'adds errors from the server to the new resource', ->
@promise4.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'indicates the attribute was changed on the new resource', ->
@promise4.catch =>
expect(@resource3.changedFields().include('tax')).toBeTruthy()
describe 'assigning relationships', ->
describe 'singular relationship', ->
beforeEach ->
@promise2 = @promise.then =>
@singularResource = ImmutableLibrary.GiftCard.build(id: '1')
@resource2 = @resource.assignAttributes({
giftCard: @singularResource
})
it 'clones a new resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
@promise2.then =>
expect(@resource.giftCard()).not.toBe(@singularResource)
it 'does not track the change on the old resource', ->
@promise2.then =>
expect(@resource.changedFields().include('giftCard')).toBeFalsy()
it 'creates a new persisted resource', ->
@promise2.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'creates a new resource with the changes', ->
@promise2.then =>
expect(@resource2.giftCard()).toBe(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
@promise2.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
describe 'saving the changed persisted resource', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise4.then =>
expect(@resource2).not.toBe(@resource3)
it 'indicates the relationship was still changed on the old resource', ->
@promise4.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists a new resource', ->
@promise4.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise4.then =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the relationship resource', ->
@promise4.then =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise4.then =>
expect(@resource3.giftCard().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise4.then =>
expect(@resource3.changedFields().include('giftCard')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise4.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise4.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise4.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise4.catch =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists the new resource', ->
@promise4.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'adds errors from the server to the new resource', ->
@promise4.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise4.catch =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise4.catch =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'indicates the new relationship resource inverse target was still changed', ->
@promise4.catch =>
expect(@resource3.giftCard().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise4.catch =>
expect(@resource3.changedFields().include('giftCard')).toBeTruthy()
describe 'collection relationship', ->
beforeEach ->
@collection = ActiveResource::Collection.build([
ImmutableLibrary.Comment.build(id: '1'),
ImmutableLibrary.Comment.build(id: '2')
])
@resource2 = @resource.assignAttributes({
comments: @collection
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.comments().target().map((o) => o.id).toArray()).toEqual(['1', '2'])
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('comments')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.comments().size()).toEqual(2)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('comments')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resources to clone', ->
@promise.then =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the relationship resources to the clone', ->
@promise.then =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'does not indicate the relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('comments')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('comments')).toBeTruthy()
describe 'when resource that is inverse of autosave relationship is changed', ->
describe 'when relationship with autosave inverse is collection', ->
beforeEach ->
ImmutableLibrary.Customer.includes('orders').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource2 = @resource.assignAttributes({
name: 'New name'
})
it 'clones resource\'s collection relationship to clone', ->
@promise.then =>
@resource.orders().target().each((o) =>
expect(@resource2.orders().target().include(o)).toBeFalsy()
expect(@resource2.orders().target().map((t) => t.id).include(o.id)).toBeTruthy()
)
it 'changes the inverse target of the relationship resources to the clone', ->
@promise.then =>
expect(@resource2.orders().target().first().customer()).toBe(@resource2)
it 'indicates the relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource2.orders().target().first().changedFields().include('customer')).toBeTruthy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('orders')).toBeFalsy()
describe 'when relationship with autosave inverse is singular', ->
describe 'when autosave inverse is collection', ->
beforeEach ->
ImmutableLibrary.Order.includes('orderItems').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource3 = @resource.orderItems().target().last()
@resource2 = @resource.orderItems().target().first().assignAttributes({
amount: 1500
})
it 'does not replace resource in collection relationship of old inverse', ->
@promise.then =>
expect(@resource.orderItems().target().first()).not.toBe(@resource2)
it 'clones the inverse target of the relationship', ->
@promise.then =>
expect(@resource2.order()).not.toBe(@resource)
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('order')).toBeFalsy()
it 'replaces resource with clone in collection relationship of cloned inverse', ->
@promise.then =>
expect(@resource2.order().orderItems().target().first()).toBe(@resource2)
it 'does not clone other resources in inverse collection relationship', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last()).toBe(@resource3)
it 'sets the inverse target of other resources in inverse collection relationship to the clone', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last().order()).toBe(@resource2.order())
it 'does not indicate the inverse target of other resources was changed', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last().changedFields().include('order')).toBeFalsy()
it 'does not indicate the old inverse autosave relationship was changed', ->
@promise.then =>
expect(@resource.changedFields().include('orderItems')).toBeFalsy()
it 'indicates the new inverse target autosave relationship was changed', ->
@promise.then =>
expect(@resource2.order().changedFields().include('orderItems')).toBeTruthy()
describe 'when autosave inverse is singular', ->
beforeEach ->
ImmutableLibrary.Order.includes('rating').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource2 = @resource.rating().assignAttributes({
value: 15
})
it 'clones the inverse target of the relationship', ->
@promise.then =>
expect(@resource2.order()).not.toBe(@resource)
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('order')).toBeFalsy()
it 'does not set original inverse relationship target to clone', ->
@promise.then =>
expect(@resource.rating()).not.toBe(@resource2)
it 'sets cloned inverse relationship target to clone', ->
@promise.then =>
expect(@resource2.order().rating()).toBe(@resource2)
it 'does not indicate the original inverse target of the relationship was changed', ->
@promise.then =>
expect(@resource.changedFields().include('rating')).toBeFalsy()
it 'indicates the cloned inverse target of the relationship was changed', ->
@promise.then =>
expect(@resource2.order().changedFields().include('rating')).toBeTruthy()
describe 'when using relationship management', ->
beforeEach ->
ImmutableLibrary.Order.find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'singular', ->
beforeEach ->
ImmutableLibrary.Customer.find('1')
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@relatedResource = window.onSuccess.calls.mostRecent().args[0]
describe 'assign', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.assignCustomer(@relatedResource)
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resource', ->
@promise3.then =>
expect(@clone.customer().isA(ImmutableLibrary.Customer)).toBeTruthy()
expect(@clone.customer()).not.toBe(@relatedResource)
describe 'update', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.updateCustomer(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resource', ->
@promise3.then =>
expect(@clone.customer().isA(ImmutableLibrary.Customer)).toBeTruthy()
expect(@clone.customer()).not.toBe(@relatedResource)
describe 'build', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.buildCustomer({ name: 'J' })
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'create', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.createCustomer({ name: 'M' })
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'collection', ->
beforeEach ->
ImmutableLibrary.Comment.find('1')
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.find.success)
.then =>
@relatedResource = window.onSuccess.calls.mostRecent().args[0]
describe 'load', ->
beforeEach ->
@resource.comments().load()
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.all.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise2.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise2.then =>
expect(@clone).not.toBe(@resource)
it 'loads related resources', ->
@promise2.then =>
expect(@clone.comments().size()).toEqual(2);
describe 'assign', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.comments().assign([@relatedResource], false)
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'update', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().assign([@relatedResource])
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'build', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.comments().build({ body: 'J' })
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'create', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().create({ body: 'M' })
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.find.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'push', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().push(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'delete', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().delete(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
| 33725 | describe 'ActiveResource', ->
beforeEach ->
window.onSuccess = jasmine.createSpy('onSuccess')
window.onFailure = jasmine.createSpy('onFailure')
window.onCompletion = jasmine.createSpy('onCompletion')
afterEach ->
moxios.uninstall()
describe '::Immutable', ->
beforeAll ->
window.ImmutableLibrary = ActiveResource.createResourceLibrary(
'https://example.com/api/v1',
immutable: true
)
moxios.install(ImmutableLibrary.interface.axios)
class ImmutableLibrary.Comment extends ImmutableLibrary.Base
this.className = 'Comment'
this.queryName = 'comments'
this.belongsTo 'order'
class ImmutableLibrary.Customer extends ImmutableLibrary.Base
this.className = 'Customer'
this.queryName = 'customers'
this.attributes('name')
this.hasMany 'orders', inverseOf: 'customer'
class ImmutableLibrary.GiftCard extends ImmutableLibrary.Base
this.className = 'GiftCard'
this.queryName = 'gift_cards'
this.hasOne 'order'
class ImmutableLibrary.Order extends ImmutableLibrary.Base
this.className = 'Order'
this.queryName = 'orders'
this.attributes('price', 'tax')
this.belongsTo 'customer', autosave: true, inverseOf: 'orders'
this.belongsTo 'giftCard'
this.hasMany 'comments'
this.hasMany 'orderItems', autosave: true, inverseOf: 'order'
this.hasOne 'rating', autosave: true
class ImmutableLibrary.OrderItem extends ImmutableLibrary.Base
this.className = 'OrderItem'
this.queryName = 'order_items'
this.attributes('amount')
this.belongsTo 'order', inverseOf: 'orderItems'
class ImmutableLibrary.Rating extends ImmutableLibrary.Base
this.className = 'Rating'
this.queryName = 'ratings'
this.attributes('value')
this.belongsTo 'order'
describe 'adding errors', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe '#add', ->
beforeEach ->
@resource2 = @resource.errors().add('field', 'code', 'message')
it 'returns new resource', ->
expect(@resource2).not.toBe(@resource)
it 'adds error to new resource', ->
expect(@resource2.errors().size()).toBe(1)
describe '#addAll', ->
beforeEach ->
@resource2 = @resource.errors().addAll(
['field', 'code', 'message'],
['field2', 'code2', 'message2'],
)
it 'returns new resource', ->
expect(@resource2).not.toBe(@resource)
it 'adds errors to new resource', ->
expect(@resource2.errors().size()).toBe(2)
describe 'propagating errors', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe 'singular relationship', ->
beforeEach ->
@resource = @resource.buildCustomer()
@customer = @resource.customer()
@errors = ActiveResource.Collection.build([
{
field: 'customer',
code: 'invalid',
message: 'invalid'
},
{
field: 'customer.firstName',
code: 'invalid',
message: 'invalid'
},
{
field: 'customer.lastName',
code: 'invalid',
message: 'invalid'
}
])
@resource.errors().propagate(@errors)
it 'adds nested base errors to the nested relationship resource base', ->
expect(@resource.customer().errors().forBase().size()).toEqual(1)
it 'adds nested field errors to the nested relationship resource', ->
expect(@resource.customer().errors().forField('firstName').size()).toEqual(1)
it 'clones the relationship resource', ->
expect(@resource.customer()).not.toBe(@customer)
describe 'repeated propagation', ->
beforeEach ->
@resource.errors().propagate(@errors)
it 'does not result in duplicate errors', ->
expect(@resource.customer().errors().forField('firstName').size()).toEqual(1)
describe 'collection relationship', ->
beforeEach ->
@resource = @resource.orderItems().build()
@orderItem = @resource.orderItems().target().first()
@errors = ActiveResource.Collection.build([
{
field: 'orderItems',
code: 'invalid',
message: 'invalid'
},
{
field: 'orderItems.amount',
code: 'invalid',
message: 'invalid'
}
])
@resource.errors().propagate(@errors)
it 'adds non-nested errors to the resource', ->
expect(@resource.errors().forField('orderItems').size()).toEqual(1)
it 'adds nested errors to the nested relationship resource', ->
expect(@resource.orderItems().target().first().errors().forField('amount').size()).toEqual(1)
it 'clones the relationship resource', ->
expect(@resource.orderItems().target().first()).not.toBe(@orderItem)
it 'clones relationships to relationship resource', ->
expect(@resource.orderItems().target().first().order()).toBe(@resource)
it 'does not duplicate cloned resource on the relationship', ->
expect(@resource.orderItems().target().size()).toBe(1)
describe 'repeated propagation', ->
beforeEach ->
@resource.errors().propagate(@errors)
it 'does not result in duplicate errors', ->
expect(@resource.orderItems().target().first().errors().forField('amount').size()).toEqual(1)
describe 'when resource unpersisted', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe 'assigning attributes', ->
beforeEach ->
@resource2 = @resource.assignAttributes({
price: 3.0
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.price).toBeUndefined()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.price).toEqual(3.0)
it 'creates a new resource with the changed attribute tracked', ->
expect(@resource2.changedFields().include('price')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save (resource3) =>
@resource3 = resource3
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.success)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not persist new changes from the server to the old resource', ->
@promise.then =>
expect(@resource2.tax).toBeUndefined()
it 'indicates the attribute was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('price')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'persists new changes from the server', ->
@promise.then =>
expect(@resource3.tax).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('price')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the attribute was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('price')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'maintains attribute on new resource', ->
@promise.catch =>
expect(@resource3.price).toEqual(3.0)
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'indicates the attribute was changed on the new resource', ->
@promise.catch =>
expect(@resource3.changedFields().include('price')).toBeTruthy()
describe 'updating attributes', ->
beforeEach ->
@resource.update({
price: 3.0
}, (resource2) =>
@resource2 = resource2
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
it 'clones a new resource', ->
@promise.then =>
expect(@resource).not.toBe(@resource2)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource.persisted()).toBeFalsy()
it 'does not change the old resource', ->
@promise.then =>
expect(@resource.price).toBeUndefined()
it 'does not persist new changes from the server to the old resource', ->
@promise.then =>
expect(@resource.tax).toBeUndefined()
it 'does not track the change on the old resource', ->
@promise.then =>
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'persists a new resource with the changes', ->
@promise.then =>
expect(@resource2.price).toEqual(3.0)
it 'persists new changes from the server', ->
@promise.then =>
expect(@resource2.tax).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('price')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource).not.toBe(@resource2)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource.persisted()).toBeFalsy()
it 'does not change the old resource', ->
@promise.catch =>
expect(@resource.price).toBeUndefined()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource.errors().empty()).toBeTruthy()
it 'does not indicate the attribute was changed on the old resource', ->
@promise.catch =>
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not change attribute on new resource', ->
@promise.catch =>
expect(@resource2.price).toEqual(null)
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeFalsy()
it 'does not indicate the attribute was changed on the new resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('price')).toBeFalsy()
describe 'assigning relationships', ->
describe 'singular relationship', ->
describe 'when inverse is singular', ->
beforeEach ->
@singularResource = ImmutableLibrary.GiftCard.build(id: '1')
@resource2 = @resource.assignAttributes({
giftCard: @singularResource
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.giftCard()).toBeNull()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('giftCard')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.giftCard()).toEqual(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise.then =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise.then =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.giftCard().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('giftCard')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise.catch =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.giftCard().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('giftCard')).toBeTruthy()
describe 'when inverse is collection', ->
beforeEach ->
@singularResource = ImmutableLibrary.Customer.build(id: '1')
@resource2 = @resource.assignAttributes({
customer: @singularResource
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.customer()).toBeNull()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('customer')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.customer()).toEqual(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('customer')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('customer')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise.then =>
expect(@resource2.customer()).toBe(@resource3.customer())
it 'changes the inverse target of the new relationship resource', ->
@promise.then =>
expect(@resource3.customer().orders().target().toArray()).toEqual([@resource3])
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.customer().changedFields().include('orders')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('customer')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('customer')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise.catch =>
expect(@resource2.customer()).toBe(@resource3.customer())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.customer().orders().target().toArray()).toEqual([@resource3])
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.customer().changedFields().include('orders')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('customer')).toBeTruthy()
describe 'collection relationship', ->
beforeEach ->
@collection = ActiveResource::Collection.build([
ImmutableLibrary.Comment.build(id: '1'),
ImmutableLibrary.Comment.build(id: '2')
])
@resource2 = @resource.assignAttributes({
comments: @collection
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.comments().empty()).toBeTruthy()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('comments')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.comments().size()).toEqual(2)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('comments')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resources to clone', ->
@promise.then =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the new relationship resources', ->
@promise.then =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('comments')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'indicates the new relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('comments')).toBeTruthy()
describe 'when resource persisted', ->
beforeEach ->
ImmutableLibrary.Order.includes('giftCard','orderItems').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'reload', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.reload()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes2)
.then =>
@resource2 = window.onSuccess.calls.mostRecent().args[0]
it 'clones resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'assigns new attributes', ->
@promise2.then =>
expect(@resource2.total).toEqual(9.0)
it 'assigns new singular relationship', ->
@promise2.then =>
expect(@resource2.rating()).toBeNull()
it 'assigns new collection relationship', ->
@promise2.then =>
expect(@resource2.orderItems().target().toArray()).toEqual([])
it 'does not assign unloaded relationships', ->
@promise2.then =>
expect(@resource2.comments().size()).toEqual(2)
describe 'assigning attributes', ->
beforeEach ->
@promise2 = @promise.then =>
@resource2 = @resource.assignAttributes({
tax: 15.0
})
it 'clones a new resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
@promise2.then =>
expect(@resource.tax).toEqual(5.0)
it 'does not track the change on the old resource', ->
@promise2.then =>
expect(@resource.changedFields().include('tax')).toBeFalsy()
it 'creates a new persisted resource', ->
@promise2.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'creates a new resource with the changes', ->
@promise2.then =>
expect(@resource2.tax).toEqual(15.0)
it 'creates a new resource with the changed attribute tracked', ->
@promise2.then =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
describe 'saving the changed persisted resource', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise4.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist new changes from the server to the old resource', ->
@promise4.then =>
expect(@resource2.balance).toBeUndefined()
it 'indicates the attribute was still changed on the old resource', ->
@promise4.then =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
it 'persists a new resource', ->
@promise4.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'persists new changes from the server', ->
@promise4.then =>
expect(@resource3.balance).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise4.then =>
expect(@resource3.changedFields().include('tax')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise4.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise4.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise4.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the attribute was still changed on the old resource', ->
@promise4.catch =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
it 'persists the new resource', ->
@promise4.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'maintains attribute on new resource', ->
@promise4.catch =>
expect(@resource3.tax).toEqual(15.0)
it 'adds errors from the server to the new resource', ->
@promise4.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'indicates the attribute was changed on the new resource', ->
@promise4.catch =>
expect(@resource3.changedFields().include('tax')).toBeTruthy()
describe 'assigning relationships', ->
describe 'singular relationship', ->
beforeEach ->
@promise2 = @promise.then =>
@singularResource = ImmutableLibrary.GiftCard.build(id: '1')
@resource2 = @resource.assignAttributes({
giftCard: @singularResource
})
it 'clones a new resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
@promise2.then =>
expect(@resource.giftCard()).not.toBe(@singularResource)
it 'does not track the change on the old resource', ->
@promise2.then =>
expect(@resource.changedFields().include('giftCard')).toBeFalsy()
it 'creates a new persisted resource', ->
@promise2.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'creates a new resource with the changes', ->
@promise2.then =>
expect(@resource2.giftCard()).toBe(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
@promise2.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
describe 'saving the changed persisted resource', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise4.then =>
expect(@resource2).not.toBe(@resource3)
it 'indicates the relationship was still changed on the old resource', ->
@promise4.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists a new resource', ->
@promise4.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise4.then =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the relationship resource', ->
@promise4.then =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise4.then =>
expect(@resource3.giftCard().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise4.then =>
expect(@resource3.changedFields().include('giftCard')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise4.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise4.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise4.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise4.catch =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists the new resource', ->
@promise4.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'adds errors from the server to the new resource', ->
@promise4.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise4.catch =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise4.catch =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'indicates the new relationship resource inverse target was still changed', ->
@promise4.catch =>
expect(@resource3.giftCard().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise4.catch =>
expect(@resource3.changedFields().include('giftCard')).toBeTruthy()
describe 'collection relationship', ->
beforeEach ->
@collection = ActiveResource::Collection.build([
ImmutableLibrary.Comment.build(id: '1'),
ImmutableLibrary.Comment.build(id: '2')
])
@resource2 = @resource.assignAttributes({
comments: @collection
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.comments().target().map((o) => o.id).toArray()).toEqual(['1', '2'])
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('comments')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.comments().size()).toEqual(2)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('comments')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resources to clone', ->
@promise.then =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the relationship resources to the clone', ->
@promise.then =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'does not indicate the relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('comments')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('comments')).toBeTruthy()
describe 'when resource that is inverse of autosave relationship is changed', ->
describe 'when relationship with autosave inverse is collection', ->
beforeEach ->
ImmutableLibrary.Customer.includes('orders').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource2 = @resource.assignAttributes({
name: '<NAME>'
})
it 'clones resource\'s collection relationship to clone', ->
@promise.then =>
@resource.orders().target().each((o) =>
expect(@resource2.orders().target().include(o)).toBeFalsy()
expect(@resource2.orders().target().map((t) => t.id).include(o.id)).toBeTruthy()
)
it 'changes the inverse target of the relationship resources to the clone', ->
@promise.then =>
expect(@resource2.orders().target().first().customer()).toBe(@resource2)
it 'indicates the relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource2.orders().target().first().changedFields().include('customer')).toBeTruthy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('orders')).toBeFalsy()
describe 'when relationship with autosave inverse is singular', ->
describe 'when autosave inverse is collection', ->
beforeEach ->
ImmutableLibrary.Order.includes('orderItems').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource3 = @resource.orderItems().target().last()
@resource2 = @resource.orderItems().target().first().assignAttributes({
amount: 1500
})
it 'does not replace resource in collection relationship of old inverse', ->
@promise.then =>
expect(@resource.orderItems().target().first()).not.toBe(@resource2)
it 'clones the inverse target of the relationship', ->
@promise.then =>
expect(@resource2.order()).not.toBe(@resource)
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('order')).toBeFalsy()
it 'replaces resource with clone in collection relationship of cloned inverse', ->
@promise.then =>
expect(@resource2.order().orderItems().target().first()).toBe(@resource2)
it 'does not clone other resources in inverse collection relationship', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last()).toBe(@resource3)
it 'sets the inverse target of other resources in inverse collection relationship to the clone', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last().order()).toBe(@resource2.order())
it 'does not indicate the inverse target of other resources was changed', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last().changedFields().include('order')).toBeFalsy()
it 'does not indicate the old inverse autosave relationship was changed', ->
@promise.then =>
expect(@resource.changedFields().include('orderItems')).toBeFalsy()
it 'indicates the new inverse target autosave relationship was changed', ->
@promise.then =>
expect(@resource2.order().changedFields().include('orderItems')).toBeTruthy()
describe 'when autosave inverse is singular', ->
beforeEach ->
ImmutableLibrary.Order.includes('rating').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource2 = @resource.rating().assignAttributes({
value: 15
})
it 'clones the inverse target of the relationship', ->
@promise.then =>
expect(@resource2.order()).not.toBe(@resource)
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('order')).toBeFalsy()
it 'does not set original inverse relationship target to clone', ->
@promise.then =>
expect(@resource.rating()).not.toBe(@resource2)
it 'sets cloned inverse relationship target to clone', ->
@promise.then =>
expect(@resource2.order().rating()).toBe(@resource2)
it 'does not indicate the original inverse target of the relationship was changed', ->
@promise.then =>
expect(@resource.changedFields().include('rating')).toBeFalsy()
it 'indicates the cloned inverse target of the relationship was changed', ->
@promise.then =>
expect(@resource2.order().changedFields().include('rating')).toBeTruthy()
describe 'when using relationship management', ->
beforeEach ->
ImmutableLibrary.Order.find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'singular', ->
beforeEach ->
ImmutableLibrary.Customer.find('1')
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@relatedResource = window.onSuccess.calls.mostRecent().args[0]
describe 'assign', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.assignCustomer(@relatedResource)
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resource', ->
@promise3.then =>
expect(@clone.customer().isA(ImmutableLibrary.Customer)).toBeTruthy()
expect(@clone.customer()).not.toBe(@relatedResource)
describe 'update', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.updateCustomer(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resource', ->
@promise3.then =>
expect(@clone.customer().isA(ImmutableLibrary.Customer)).toBeTruthy()
expect(@clone.customer()).not.toBe(@relatedResource)
describe 'build', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.buildCustomer({ name: '<NAME>' })
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'create', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.createCustomer({ name: '<NAME>' })
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'collection', ->
beforeEach ->
ImmutableLibrary.Comment.find('1')
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.find.success)
.then =>
@relatedResource = window.onSuccess.calls.mostRecent().args[0]
describe 'load', ->
beforeEach ->
@resource.comments().load()
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.all.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise2.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise2.then =>
expect(@clone).not.toBe(@resource)
it 'loads related resources', ->
@promise2.then =>
expect(@clone.comments().size()).toEqual(2);
describe 'assign', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.comments().assign([@relatedResource], false)
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'update', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().assign([@relatedResource])
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'build', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.comments().build({ body: '<NAME>' })
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'create', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().create({ body: '<NAME>' })
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.find.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'push', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().push(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'delete', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().delete(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
| true | describe 'ActiveResource', ->
beforeEach ->
window.onSuccess = jasmine.createSpy('onSuccess')
window.onFailure = jasmine.createSpy('onFailure')
window.onCompletion = jasmine.createSpy('onCompletion')
afterEach ->
moxios.uninstall()
describe '::Immutable', ->
beforeAll ->
window.ImmutableLibrary = ActiveResource.createResourceLibrary(
'https://example.com/api/v1',
immutable: true
)
moxios.install(ImmutableLibrary.interface.axios)
class ImmutableLibrary.Comment extends ImmutableLibrary.Base
this.className = 'Comment'
this.queryName = 'comments'
this.belongsTo 'order'
class ImmutableLibrary.Customer extends ImmutableLibrary.Base
this.className = 'Customer'
this.queryName = 'customers'
this.attributes('name')
this.hasMany 'orders', inverseOf: 'customer'
class ImmutableLibrary.GiftCard extends ImmutableLibrary.Base
this.className = 'GiftCard'
this.queryName = 'gift_cards'
this.hasOne 'order'
class ImmutableLibrary.Order extends ImmutableLibrary.Base
this.className = 'Order'
this.queryName = 'orders'
this.attributes('price', 'tax')
this.belongsTo 'customer', autosave: true, inverseOf: 'orders'
this.belongsTo 'giftCard'
this.hasMany 'comments'
this.hasMany 'orderItems', autosave: true, inverseOf: 'order'
this.hasOne 'rating', autosave: true
class ImmutableLibrary.OrderItem extends ImmutableLibrary.Base
this.className = 'OrderItem'
this.queryName = 'order_items'
this.attributes('amount')
this.belongsTo 'order', inverseOf: 'orderItems'
class ImmutableLibrary.Rating extends ImmutableLibrary.Base
this.className = 'Rating'
this.queryName = 'ratings'
this.attributes('value')
this.belongsTo 'order'
describe 'adding errors', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe '#add', ->
beforeEach ->
@resource2 = @resource.errors().add('field', 'code', 'message')
it 'returns new resource', ->
expect(@resource2).not.toBe(@resource)
it 'adds error to new resource', ->
expect(@resource2.errors().size()).toBe(1)
describe '#addAll', ->
beforeEach ->
@resource2 = @resource.errors().addAll(
['field', 'code', 'message'],
['field2', 'code2', 'message2'],
)
it 'returns new resource', ->
expect(@resource2).not.toBe(@resource)
it 'adds errors to new resource', ->
expect(@resource2.errors().size()).toBe(2)
describe 'propagating errors', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe 'singular relationship', ->
beforeEach ->
@resource = @resource.buildCustomer()
@customer = @resource.customer()
@errors = ActiveResource.Collection.build([
{
field: 'customer',
code: 'invalid',
message: 'invalid'
},
{
field: 'customer.firstName',
code: 'invalid',
message: 'invalid'
},
{
field: 'customer.lastName',
code: 'invalid',
message: 'invalid'
}
])
@resource.errors().propagate(@errors)
it 'adds nested base errors to the nested relationship resource base', ->
expect(@resource.customer().errors().forBase().size()).toEqual(1)
it 'adds nested field errors to the nested relationship resource', ->
expect(@resource.customer().errors().forField('firstName').size()).toEqual(1)
it 'clones the relationship resource', ->
expect(@resource.customer()).not.toBe(@customer)
describe 'repeated propagation', ->
beforeEach ->
@resource.errors().propagate(@errors)
it 'does not result in duplicate errors', ->
expect(@resource.customer().errors().forField('firstName').size()).toEqual(1)
describe 'collection relationship', ->
beforeEach ->
@resource = @resource.orderItems().build()
@orderItem = @resource.orderItems().target().first()
@errors = ActiveResource.Collection.build([
{
field: 'orderItems',
code: 'invalid',
message: 'invalid'
},
{
field: 'orderItems.amount',
code: 'invalid',
message: 'invalid'
}
])
@resource.errors().propagate(@errors)
it 'adds non-nested errors to the resource', ->
expect(@resource.errors().forField('orderItems').size()).toEqual(1)
it 'adds nested errors to the nested relationship resource', ->
expect(@resource.orderItems().target().first().errors().forField('amount').size()).toEqual(1)
it 'clones the relationship resource', ->
expect(@resource.orderItems().target().first()).not.toBe(@orderItem)
it 'clones relationships to relationship resource', ->
expect(@resource.orderItems().target().first().order()).toBe(@resource)
it 'does not duplicate cloned resource on the relationship', ->
expect(@resource.orderItems().target().size()).toBe(1)
describe 'repeated propagation', ->
beforeEach ->
@resource.errors().propagate(@errors)
it 'does not result in duplicate errors', ->
expect(@resource.orderItems().target().first().errors().forField('amount').size()).toEqual(1)
describe 'when resource unpersisted', ->
beforeEach ->
@resource = ImmutableLibrary.Order.build()
describe 'assigning attributes', ->
beforeEach ->
@resource2 = @resource.assignAttributes({
price: 3.0
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.price).toBeUndefined()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.price).toEqual(3.0)
it 'creates a new resource with the changed attribute tracked', ->
expect(@resource2.changedFields().include('price')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save (resource3) =>
@resource3 = resource3
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.success)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not persist new changes from the server to the old resource', ->
@promise.then =>
expect(@resource2.tax).toBeUndefined()
it 'indicates the attribute was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('price')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'persists new changes from the server', ->
@promise.then =>
expect(@resource3.tax).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('price')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the attribute was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('price')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'maintains attribute on new resource', ->
@promise.catch =>
expect(@resource3.price).toEqual(3.0)
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'indicates the attribute was changed on the new resource', ->
@promise.catch =>
expect(@resource3.changedFields().include('price')).toBeTruthy()
describe 'updating attributes', ->
beforeEach ->
@resource.update({
price: 3.0
}, (resource2) =>
@resource2 = resource2
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
it 'clones a new resource', ->
@promise.then =>
expect(@resource).not.toBe(@resource2)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource.persisted()).toBeFalsy()
it 'does not change the old resource', ->
@promise.then =>
expect(@resource.price).toBeUndefined()
it 'does not persist new changes from the server to the old resource', ->
@promise.then =>
expect(@resource.tax).toBeUndefined()
it 'does not track the change on the old resource', ->
@promise.then =>
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'persists a new resource with the changes', ->
@promise.then =>
expect(@resource2.price).toEqual(3.0)
it 'persists new changes from the server', ->
@promise.then =>
expect(@resource2.tax).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('price')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource).not.toBe(@resource2)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource.persisted()).toBeFalsy()
it 'does not change the old resource', ->
@promise.catch =>
expect(@resource.price).toBeUndefined()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource.errors().empty()).toBeTruthy()
it 'does not indicate the attribute was changed on the old resource', ->
@promise.catch =>
expect(@resource.changedFields().include('price')).toBeFalsy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not change attribute on new resource', ->
@promise.catch =>
expect(@resource2.price).toEqual(null)
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeFalsy()
it 'does not indicate the attribute was changed on the new resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('price')).toBeFalsy()
describe 'assigning relationships', ->
describe 'singular relationship', ->
describe 'when inverse is singular', ->
beforeEach ->
@singularResource = ImmutableLibrary.GiftCard.build(id: '1')
@resource2 = @resource.assignAttributes({
giftCard: @singularResource
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.giftCard()).toBeNull()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('giftCard')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.giftCard()).toEqual(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise.then =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise.then =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.giftCard().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('giftCard')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise.catch =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.giftCard().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('giftCard')).toBeTruthy()
describe 'when inverse is collection', ->
beforeEach ->
@singularResource = ImmutableLibrary.Customer.build(id: '1')
@resource2 = @resource.assignAttributes({
customer: @singularResource
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.customer()).toBeNull()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('customer')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.customer()).toEqual(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('customer')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('customer')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise.then =>
expect(@resource2.customer()).toBe(@resource3.customer())
it 'changes the inverse target of the new relationship resource', ->
@promise.then =>
expect(@resource3.customer().orders().target().toArray()).toEqual([@resource3])
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.customer().changedFields().include('orders')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('customer')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('customer')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise.catch =>
expect(@resource2.customer()).toBe(@resource3.customer())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.customer().orders().target().toArray()).toEqual([@resource3])
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.customer().changedFields().include('orders')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('customer')).toBeTruthy()
describe 'collection relationship', ->
beforeEach ->
@collection = ActiveResource::Collection.build([
ImmutableLibrary.Comment.build(id: '1'),
ImmutableLibrary.Comment.build(id: '2')
])
@resource2 = @resource.assignAttributes({
comments: @collection
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.comments().empty()).toBeTruthy()
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('comments')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.comments().size()).toEqual(2)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('comments')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeFalsy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resources to clone', ->
@promise.then =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the new relationship resources', ->
@promise.then =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('comments')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeFalsy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'does not persist the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeFalsy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the new relationship resource', ->
@promise.catch =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'indicates the new relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('comments')).toBeTruthy()
describe 'when resource persisted', ->
beforeEach ->
ImmutableLibrary.Order.includes('giftCard','orderItems').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'reload', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.reload()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes2)
.then =>
@resource2 = window.onSuccess.calls.mostRecent().args[0]
it 'clones resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'assigns new attributes', ->
@promise2.then =>
expect(@resource2.total).toEqual(9.0)
it 'assigns new singular relationship', ->
@promise2.then =>
expect(@resource2.rating()).toBeNull()
it 'assigns new collection relationship', ->
@promise2.then =>
expect(@resource2.orderItems().target().toArray()).toEqual([])
it 'does not assign unloaded relationships', ->
@promise2.then =>
expect(@resource2.comments().size()).toEqual(2)
describe 'assigning attributes', ->
beforeEach ->
@promise2 = @promise.then =>
@resource2 = @resource.assignAttributes({
tax: 15.0
})
it 'clones a new resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
@promise2.then =>
expect(@resource.tax).toEqual(5.0)
it 'does not track the change on the old resource', ->
@promise2.then =>
expect(@resource.changedFields().include('tax')).toBeFalsy()
it 'creates a new persisted resource', ->
@promise2.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'creates a new resource with the changes', ->
@promise2.then =>
expect(@resource2.tax).toEqual(15.0)
it 'creates a new resource with the changed attribute tracked', ->
@promise2.then =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
describe 'saving the changed persisted resource', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise4.then =>
expect(@resource2).not.toBe(@resource3)
it 'does not persist new changes from the server to the old resource', ->
@promise4.then =>
expect(@resource2.balance).toBeUndefined()
it 'indicates the attribute was still changed on the old resource', ->
@promise4.then =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
it 'persists a new resource', ->
@promise4.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'persists new changes from the server', ->
@promise4.then =>
expect(@resource3.balance).not.toBeUndefined()
it 'does not indicate the attribute was changed', ->
@promise4.then =>
expect(@resource3.changedFields().include('tax')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise4.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise4.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise4.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the attribute was still changed on the old resource', ->
@promise4.catch =>
expect(@resource2.changedFields().include('tax')).toBeTruthy()
it 'persists the new resource', ->
@promise4.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'maintains attribute on new resource', ->
@promise4.catch =>
expect(@resource3.tax).toEqual(15.0)
it 'adds errors from the server to the new resource', ->
@promise4.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'indicates the attribute was changed on the new resource', ->
@promise4.catch =>
expect(@resource3.changedFields().include('tax')).toBeTruthy()
describe 'assigning relationships', ->
describe 'singular relationship', ->
beforeEach ->
@promise2 = @promise.then =>
@singularResource = ImmutableLibrary.GiftCard.build(id: '1')
@resource2 = @resource.assignAttributes({
giftCard: @singularResource
})
it 'clones a new resource', ->
@promise2.then =>
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
@promise2.then =>
expect(@resource.giftCard()).not.toBe(@singularResource)
it 'does not track the change on the old resource', ->
@promise2.then =>
expect(@resource.changedFields().include('giftCard')).toBeFalsy()
it 'creates a new persisted resource', ->
@promise2.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'creates a new resource with the changes', ->
@promise2.then =>
expect(@resource2.giftCard()).toBe(@singularResource)
it 'creates a new resource with the changed relationship tracked', ->
@promise2.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
describe 'saving the changed persisted resource', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise4.then =>
expect(@resource2).not.toBe(@resource3)
it 'indicates the relationship was still changed on the old resource', ->
@promise4.then =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists a new resource', ->
@promise4.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resource to clone', ->
@promise4.then =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the relationship resource', ->
@promise4.then =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'does not indicate the new relationship resource inverse target was changed', ->
@promise4.then =>
expect(@resource3.giftCard().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise4.then =>
expect(@resource3.changedFields().include('giftCard')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise4.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise4.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise4.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise4.catch =>
expect(@resource2.changedFields().include('giftCard')).toBeTruthy()
it 'persists the new resource', ->
@promise4.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'adds errors from the server to the new resource', ->
@promise4.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resource to clone', ->
@promise4.catch =>
expect(@resource2.giftCard()).toBe(@resource3.giftCard())
it 'changes the inverse target of the new relationship resource', ->
@promise4.catch =>
expect(@resource3.giftCard().order()).toBe(@resource3)
it 'indicates the new relationship resource inverse target was still changed', ->
@promise4.catch =>
expect(@resource3.giftCard().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise4.catch =>
expect(@resource3.changedFields().include('giftCard')).toBeTruthy()
describe 'collection relationship', ->
beforeEach ->
@collection = ActiveResource::Collection.build([
ImmutableLibrary.Comment.build(id: '1'),
ImmutableLibrary.Comment.build(id: '2')
])
@resource2 = @resource.assignAttributes({
comments: @collection
})
it 'clones a new resource', ->
expect(@resource).not.toBe(@resource2)
it 'does not change the old resource', ->
expect(@resource.comments().target().map((o) => o.id).toArray()).toEqual(['1', '2'])
it 'does not track the change on the old resource', ->
expect(@resource.changedFields().include('comments')).toBeFalsy()
it 'creates a new resource with the changes', ->
expect(@resource2.comments().size()).toEqual(2)
it 'creates a new resource with the changed relationship tracked', ->
expect(@resource2.changedFields().include('comments')).toBeTruthy()
describe 'saving the resource', ->
beforeEach ->
@resource2.save((resource3) =>
@resource3 = resource3
)
null
describe 'on success', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.includes)
it 'clones a new resource', ->
@promise.then =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise.then =>
expect(@resource2.persisted()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.then =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists a new resource', ->
@promise.then =>
expect(@resource3.persisted()).toBeTruthy()
it 'assigns relationship resources to clone', ->
@promise.then =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the relationship resources to the clone', ->
@promise.then =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'does not indicate the relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeFalsy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource3.changedFields().include('comments')).toBeFalsy()
describe 'on failure', ->
beforeEach ->
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
it 'clones a new resource', ->
@promise.catch =>
expect(@resource2).not.toBe(@resource3)
it 'persists the old resource', ->
@promise.catch =>
expect(@resource2.persisted()).toBeTruthy()
it 'does not add errors from the server to the old resource', ->
@promise.catch =>
expect(@resource2.errors().empty()).toBeTruthy()
it 'indicates the relationship was still changed on the old resource', ->
@promise.catch =>
expect(@resource2.changedFields().include('comments')).toBeTruthy()
it 'persists the new resource', ->
@promise.catch =>
expect(@resource3.persisted()).toBeTruthy()
it 'adds errors from the server to the new resource', ->
@promise.catch =>
expect(@resource3.errors().empty()).toBeFalsy()
it 'assigns relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().toArray()).toEqual(@resource2.comments().target().toArray())
it 'changes the inverse target of the relationship resources to clone', ->
@promise.catch =>
expect(@resource3.comments().target().first().order()).toBe(@resource3)
it 'indicates the relationship resource inverse target was still changed', ->
@promise.catch =>
expect(@resource3.comments().target().first().changedFields().include('order')).toBeTruthy()
it 'indicates the relationship was still changed', ->
@promise.catch =>
expect(@resource3.changedFields().include('comments')).toBeTruthy()
describe 'when resource that is inverse of autosave relationship is changed', ->
describe 'when relationship with autosave inverse is collection', ->
beforeEach ->
ImmutableLibrary.Customer.includes('orders').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource2 = @resource.assignAttributes({
name: 'PI:NAME:<NAME>END_PI'
})
it 'clones resource\'s collection relationship to clone', ->
@promise.then =>
@resource.orders().target().each((o) =>
expect(@resource2.orders().target().include(o)).toBeFalsy()
expect(@resource2.orders().target().map((t) => t.id).include(o.id)).toBeTruthy()
)
it 'changes the inverse target of the relationship resources to the clone', ->
@promise.then =>
expect(@resource2.orders().target().first().customer()).toBe(@resource2)
it 'indicates the relationship resource inverse target was changed', ->
@promise.then =>
expect(@resource2.orders().target().first().changedFields().include('customer')).toBeTruthy()
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('orders')).toBeFalsy()
describe 'when relationship with autosave inverse is singular', ->
describe 'when autosave inverse is collection', ->
beforeEach ->
ImmutableLibrary.Order.includes('orderItems').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource3 = @resource.orderItems().target().last()
@resource2 = @resource.orderItems().target().first().assignAttributes({
amount: 1500
})
it 'does not replace resource in collection relationship of old inverse', ->
@promise.then =>
expect(@resource.orderItems().target().first()).not.toBe(@resource2)
it 'clones the inverse target of the relationship', ->
@promise.then =>
expect(@resource2.order()).not.toBe(@resource)
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('order')).toBeFalsy()
it 'replaces resource with clone in collection relationship of cloned inverse', ->
@promise.then =>
expect(@resource2.order().orderItems().target().first()).toBe(@resource2)
it 'does not clone other resources in inverse collection relationship', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last()).toBe(@resource3)
it 'sets the inverse target of other resources in inverse collection relationship to the clone', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last().order()).toBe(@resource2.order())
it 'does not indicate the inverse target of other resources was changed', ->
@promise.then =>
expect(@resource2.order().orderItems().target().last().changedFields().include('order')).toBeFalsy()
it 'does not indicate the old inverse autosave relationship was changed', ->
@promise.then =>
expect(@resource.changedFields().include('orderItems')).toBeFalsy()
it 'indicates the new inverse target autosave relationship was changed', ->
@promise.then =>
expect(@resource2.order().changedFields().include('orderItems')).toBeTruthy()
describe 'when autosave inverse is singular', ->
beforeEach ->
ImmutableLibrary.Order.includes('rating').find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@resource2 = @resource.rating().assignAttributes({
value: 15
})
it 'clones the inverse target of the relationship', ->
@promise.then =>
expect(@resource2.order()).not.toBe(@resource)
it 'does not indicate the relationship was changed', ->
@promise.then =>
expect(@resource2.changedFields().include('order')).toBeFalsy()
it 'does not set original inverse relationship target to clone', ->
@promise.then =>
expect(@resource.rating()).not.toBe(@resource2)
it 'sets cloned inverse relationship target to clone', ->
@promise.then =>
expect(@resource2.order().rating()).toBe(@resource2)
it 'does not indicate the original inverse target of the relationship was changed', ->
@promise.then =>
expect(@resource.changedFields().include('rating')).toBeFalsy()
it 'indicates the cloned inverse target of the relationship was changed', ->
@promise.then =>
expect(@resource2.order().changedFields().include('rating')).toBeTruthy()
describe 'when using relationship management', ->
beforeEach ->
ImmutableLibrary.Order.find('1')
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'singular', ->
beforeEach ->
ImmutableLibrary.Customer.find('1')
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@relatedResource = window.onSuccess.calls.mostRecent().args[0]
describe 'assign', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.assignCustomer(@relatedResource)
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resource', ->
@promise3.then =>
expect(@clone.customer().isA(ImmutableLibrary.Customer)).toBeTruthy()
expect(@clone.customer()).not.toBe(@relatedResource)
describe 'update', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.updateCustomer(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resource', ->
@promise3.then =>
expect(@clone.customer().isA(ImmutableLibrary.Customer)).toBeTruthy()
expect(@clone.customer()).not.toBe(@relatedResource)
describe 'build', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.buildCustomer({ name: 'PI:NAME:<NAME>END_PI' })
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'create', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.createCustomer({ name: 'PI:NAME:<NAME>END_PI' })
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Customer.find.includes)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'collection', ->
beforeEach ->
ImmutableLibrary.Comment.find('1')
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.find.success)
.then =>
@relatedResource = window.onSuccess.calls.mostRecent().args[0]
describe 'load', ->
beforeEach ->
@resource.comments().load()
.then window.onSuccess
@promise2 = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.all.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise2.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise2.then =>
expect(@clone).not.toBe(@resource)
it 'loads related resources', ->
@promise2.then =>
expect(@clone.comments().size()).toEqual(2);
describe 'assign', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.comments().assign([@relatedResource], false)
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'update', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().assign([@relatedResource])
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'build', ->
beforeEach ->
@promise3 = @promise2.then =>
@clone = @resource.comments().build({ body: 'PI:NAME:<NAME>END_PI' })
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'create', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().create({ body: 'PI:NAME:<NAME>END_PI' })
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Comment.find.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
describe 'push', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().push(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
describe 'delete', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.comments().delete(@relatedResource)
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
.then =>
@clone = window.onSuccess.calls.mostRecent().args[0]
it 'returns owner of relationship', ->
@promise3.then =>
expect(@clone.isA(ImmutableLibrary.Order)).toBeTruthy()
it 'clones resource', ->
@promise3.then =>
expect(@clone).not.toBe(@resource)
it 'clones related resources', ->
@promise3.then =>
expect(@clone.comments().target().first().isA(ImmutableLibrary.Comment)).toBeTruthy()
expect(@clone.comments().target().first()).not.toBe(@relatedResource)
|
[
{
"context": "_helpers\n# Originally based on https://github.com/GoogleChrome/chrome-app-samples/blob/master/mdns-browser/main.",
"end": 77,
"score": 0.7700541019439697,
"start": 65,
"tag": "USERNAME",
"value": "GoogleChrome"
},
{
"context": " = packet.serialize()\n @api.sendTo sock, raw, \"224.0.0.251\", 5353, (writeInfo) ->\n @callback_ \"could no",
"end": 4458,
"score": 0.9997308850288391,
"start": 4447,
"tag": "IP_ADDRESS",
"value": "224.0.0.251"
}
] | assets/js/mdns.coffee | D1plo1d/ctrlpanel | 1 | #= require mdns_helpers
# Originally based on https://github.com/GoogleChrome/chrome-app-samples/blob/master/mdns-browser/main.js
# Requires the following permissions in your manifest.json:
# "socket": [
# "udp-bind:*",
# "udp-send-to:*"
# ]
# This is a single-use object that does a DNS multicast search on creation.
class @MDNS
# @param {function} callback The callback to be invoked when this object is
# updated, or when an error occurs (passes string).
constructor: (callback) ->
@callback_ = callback
@byIP_ = {}
@byService_ = {}
@sockets_ = []
# TODO: ipv6.
# Store the socket, set up a recieve handler, and broadcast on it.
@forEachAddress_ (address) =>
unless address.indexOf(":") is -1
console.log "IPv6 address unsupported", address
return true
console.log "Broadcasting to address", address
@bindToAddress_ address, (socket) =>
if chrome.runtime.lastError
@callback_ "could not bind UDP socket: " + chrome.runtime.lastError.message
return true
@sockets_.push socket
@recv_ socket
@broadcast_ socket, address
# After a short time, if our database is empty, report an error.
setTimeout =>
@callback_ "no mDNS services found!" unless Object.keys(@byIP_).length
, 10 * 1000
api: chrome.socket or chrome.experimental.socket
# Invokes the callback for every local network address on the system.
# private
# @param {function} callback to invoke
forEachAddress_: (callback) ->
api = @api
unless api.getNetworkList
# Short-circuit for Chrome built before r155662.
callback "0.0.0.0", "*"
return true
api.getNetworkList (adapterInfo) ->
adapterInfo.forEach (info) ->
callback info["address"], info["name"]
# Creates UDP socket bound to the specified address, passing it to the
# callback. Passes null on failure.
# @private
# @param {string} address to bind to
# @param {function} callback to invoke when done
bindToAddress_: (address, callback) ->
api = @api
api.create "udp", {}, (createInfo) ->
api.bind createInfo["socketId"], address, 0, (result) ->
callback createInfo["socketId"]
# Sorts the passed list of string IPs in-place.
# @private
sortIps_: (arg) ->
arg.sort @sortIps_sort_
arg
sortIps_sort_: (l, r) =>
# TODO: support v6.
lp = l.split(".").map(@sortIps_toInt_)
rp = r.split(".").map(@sortIps_toInt_)
i = 0
while i < Math.min(lp.length, rp.length)
if lp[i] < rp[i]
return -1
else return +1 if lp[i] > rp[i]
++i
0
sortIps_toInt_: (i) -> +i
# Returns the services found by this MDNS, optionally filtered by IP.
services: (opt_ip) ->
k = Object.keys((if opt_ip then @byIP_[opt_ip] else @byService_))
k.sort()
k
# Returns the IPs found by this MDNS, optionally filtered by service.
ips: (opt_service) ->
k = Object.keys((if opt_service then @byService_[opt_service] else @byIP_))
@sortIps_ k
# Handles an incoming UDP packet.
# @private
recv_: (sock, info) ->
if chrome.runtime.lastError
# If our socket fails, detect this early: otherwise we'll just register
# to receive again (and fail again).
@callback_ chrome.runtime.lastError.message
return true
@api.recvFrom sock, @recv_.bind(this, sock)
# We didn't receive any data, we were just setting up recvFrom.
return false unless info
getDefault_ = (o, k, def) ->
(k of o) or false is (o[k] = def)
o[k]
# Update our local database.
# TODO: Resolve IPs using the dns extension.
packet = DNSPacket.parse(info.data)
byIP = getDefault_(@byIP_, info.address, {})
packet.each "an", 12, (rec) =>
ptr = rec.asName()
byService = getDefault_(@byService_, ptr, {})
byService[info.address] = true
byIP[ptr] = true
# Ping! Something new is here. Only update every 25ms.
unless @callback_pending_
@callback_pending_ = true
setTimeout =>
@callback_pending_ = `undefined`
@callback_()
, 25
# Broadcasts for services on the given socket/address.
# @private
broadcast_: (sock, address) ->
packet = new DNSPacket()
packet.push "qd", new DNSRecord("_services._dns-sd._udp.local", 12, 1)
raw = packet.serialize()
@api.sendTo sock, raw, "224.0.0.251", 5353, (writeInfo) ->
@callback_ "could not write DNS packet on: " + address unless writeInfo.bytesWritten is raw.byteLength
shutdown: ->
@sockets_.forEach (sock) ->
@api.disconnect sock
@api.destroy sock
| 159806 | #= require mdns_helpers
# Originally based on https://github.com/GoogleChrome/chrome-app-samples/blob/master/mdns-browser/main.js
# Requires the following permissions in your manifest.json:
# "socket": [
# "udp-bind:*",
# "udp-send-to:*"
# ]
# This is a single-use object that does a DNS multicast search on creation.
class @MDNS
# @param {function} callback The callback to be invoked when this object is
# updated, or when an error occurs (passes string).
constructor: (callback) ->
@callback_ = callback
@byIP_ = {}
@byService_ = {}
@sockets_ = []
# TODO: ipv6.
# Store the socket, set up a recieve handler, and broadcast on it.
@forEachAddress_ (address) =>
unless address.indexOf(":") is -1
console.log "IPv6 address unsupported", address
return true
console.log "Broadcasting to address", address
@bindToAddress_ address, (socket) =>
if chrome.runtime.lastError
@callback_ "could not bind UDP socket: " + chrome.runtime.lastError.message
return true
@sockets_.push socket
@recv_ socket
@broadcast_ socket, address
# After a short time, if our database is empty, report an error.
setTimeout =>
@callback_ "no mDNS services found!" unless Object.keys(@byIP_).length
, 10 * 1000
api: chrome.socket or chrome.experimental.socket
# Invokes the callback for every local network address on the system.
# private
# @param {function} callback to invoke
forEachAddress_: (callback) ->
api = @api
unless api.getNetworkList
# Short-circuit for Chrome built before r155662.
callback "0.0.0.0", "*"
return true
api.getNetworkList (adapterInfo) ->
adapterInfo.forEach (info) ->
callback info["address"], info["name"]
# Creates UDP socket bound to the specified address, passing it to the
# callback. Passes null on failure.
# @private
# @param {string} address to bind to
# @param {function} callback to invoke when done
bindToAddress_: (address, callback) ->
api = @api
api.create "udp", {}, (createInfo) ->
api.bind createInfo["socketId"], address, 0, (result) ->
callback createInfo["socketId"]
# Sorts the passed list of string IPs in-place.
# @private
sortIps_: (arg) ->
arg.sort @sortIps_sort_
arg
sortIps_sort_: (l, r) =>
# TODO: support v6.
lp = l.split(".").map(@sortIps_toInt_)
rp = r.split(".").map(@sortIps_toInt_)
i = 0
while i < Math.min(lp.length, rp.length)
if lp[i] < rp[i]
return -1
else return +1 if lp[i] > rp[i]
++i
0
sortIps_toInt_: (i) -> +i
# Returns the services found by this MDNS, optionally filtered by IP.
services: (opt_ip) ->
k = Object.keys((if opt_ip then @byIP_[opt_ip] else @byService_))
k.sort()
k
# Returns the IPs found by this MDNS, optionally filtered by service.
ips: (opt_service) ->
k = Object.keys((if opt_service then @byService_[opt_service] else @byIP_))
@sortIps_ k
# Handles an incoming UDP packet.
# @private
recv_: (sock, info) ->
if chrome.runtime.lastError
# If our socket fails, detect this early: otherwise we'll just register
# to receive again (and fail again).
@callback_ chrome.runtime.lastError.message
return true
@api.recvFrom sock, @recv_.bind(this, sock)
# We didn't receive any data, we were just setting up recvFrom.
return false unless info
getDefault_ = (o, k, def) ->
(k of o) or false is (o[k] = def)
o[k]
# Update our local database.
# TODO: Resolve IPs using the dns extension.
packet = DNSPacket.parse(info.data)
byIP = getDefault_(@byIP_, info.address, {})
packet.each "an", 12, (rec) =>
ptr = rec.asName()
byService = getDefault_(@byService_, ptr, {})
byService[info.address] = true
byIP[ptr] = true
# Ping! Something new is here. Only update every 25ms.
unless @callback_pending_
@callback_pending_ = true
setTimeout =>
@callback_pending_ = `undefined`
@callback_()
, 25
# Broadcasts for services on the given socket/address.
# @private
broadcast_: (sock, address) ->
packet = new DNSPacket()
packet.push "qd", new DNSRecord("_services._dns-sd._udp.local", 12, 1)
raw = packet.serialize()
@api.sendTo sock, raw, "192.168.3.11", 5353, (writeInfo) ->
@callback_ "could not write DNS packet on: " + address unless writeInfo.bytesWritten is raw.byteLength
shutdown: ->
@sockets_.forEach (sock) ->
@api.disconnect sock
@api.destroy sock
| true | #= require mdns_helpers
# Originally based on https://github.com/GoogleChrome/chrome-app-samples/blob/master/mdns-browser/main.js
# Requires the following permissions in your manifest.json:
# "socket": [
# "udp-bind:*",
# "udp-send-to:*"
# ]
# This is a single-use object that does a DNS multicast search on creation.
class @MDNS
# @param {function} callback The callback to be invoked when this object is
# updated, or when an error occurs (passes string).
constructor: (callback) ->
@callback_ = callback
@byIP_ = {}
@byService_ = {}
@sockets_ = []
# TODO: ipv6.
# Store the socket, set up a recieve handler, and broadcast on it.
@forEachAddress_ (address) =>
unless address.indexOf(":") is -1
console.log "IPv6 address unsupported", address
return true
console.log "Broadcasting to address", address
@bindToAddress_ address, (socket) =>
if chrome.runtime.lastError
@callback_ "could not bind UDP socket: " + chrome.runtime.lastError.message
return true
@sockets_.push socket
@recv_ socket
@broadcast_ socket, address
# After a short time, if our database is empty, report an error.
setTimeout =>
@callback_ "no mDNS services found!" unless Object.keys(@byIP_).length
, 10 * 1000
api: chrome.socket or chrome.experimental.socket
# Invokes the callback for every local network address on the system.
# private
# @param {function} callback to invoke
forEachAddress_: (callback) ->
api = @api
unless api.getNetworkList
# Short-circuit for Chrome built before r155662.
callback "0.0.0.0", "*"
return true
api.getNetworkList (adapterInfo) ->
adapterInfo.forEach (info) ->
callback info["address"], info["name"]
# Creates UDP socket bound to the specified address, passing it to the
# callback. Passes null on failure.
# @private
# @param {string} address to bind to
# @param {function} callback to invoke when done
bindToAddress_: (address, callback) ->
api = @api
api.create "udp", {}, (createInfo) ->
api.bind createInfo["socketId"], address, 0, (result) ->
callback createInfo["socketId"]
# Sorts the passed list of string IPs in-place.
# @private
sortIps_: (arg) ->
arg.sort @sortIps_sort_
arg
sortIps_sort_: (l, r) =>
# TODO: support v6.
lp = l.split(".").map(@sortIps_toInt_)
rp = r.split(".").map(@sortIps_toInt_)
i = 0
while i < Math.min(lp.length, rp.length)
if lp[i] < rp[i]
return -1
else return +1 if lp[i] > rp[i]
++i
0
sortIps_toInt_: (i) -> +i
# Returns the services found by this MDNS, optionally filtered by IP.
services: (opt_ip) ->
k = Object.keys((if opt_ip then @byIP_[opt_ip] else @byService_))
k.sort()
k
# Returns the IPs found by this MDNS, optionally filtered by service.
ips: (opt_service) ->
k = Object.keys((if opt_service then @byService_[opt_service] else @byIP_))
@sortIps_ k
# Handles an incoming UDP packet.
# @private
recv_: (sock, info) ->
if chrome.runtime.lastError
# If our socket fails, detect this early: otherwise we'll just register
# to receive again (and fail again).
@callback_ chrome.runtime.lastError.message
return true
@api.recvFrom sock, @recv_.bind(this, sock)
# We didn't receive any data, we were just setting up recvFrom.
return false unless info
getDefault_ = (o, k, def) ->
(k of o) or false is (o[k] = def)
o[k]
# Update our local database.
# TODO: Resolve IPs using the dns extension.
packet = DNSPacket.parse(info.data)
byIP = getDefault_(@byIP_, info.address, {})
packet.each "an", 12, (rec) =>
ptr = rec.asName()
byService = getDefault_(@byService_, ptr, {})
byService[info.address] = true
byIP[ptr] = true
# Ping! Something new is here. Only update every 25ms.
unless @callback_pending_
@callback_pending_ = true
setTimeout =>
@callback_pending_ = `undefined`
@callback_()
, 25
# Broadcasts for services on the given socket/address.
# @private
broadcast_: (sock, address) ->
packet = new DNSPacket()
packet.push "qd", new DNSRecord("_services._dns-sd._udp.local", 12, 1)
raw = packet.serialize()
@api.sendTo sock, raw, "PI:IP_ADDRESS:192.168.3.11END_PI", 5353, (writeInfo) ->
@callback_ "could not write DNS packet on: " + address unless writeInfo.bytesWritten is raw.byteLength
shutdown: ->
@sockets_.forEach (sock) ->
@api.disconnect sock
@api.destroy sock
|
[
{
"context": "oolTip: \"Enter the user's full name\"\n\t\t\tdefault: \"Steve\"\n\t\t,\n\t\t\tfield: \"username\"\n\t\t\ttitle: \"Nick name\"\n\t",
"end": 384,
"score": 0.9976897239685059,
"start": 379,
"tag": "NAME",
"value": "Steve"
},
{
"context": "r's full name\"\n\t\t\tdefault: \"Steve\"\n\t\t,\n\t\t\tfield: \"username\"\n\t\t\ttitle: \"Nick name\"\n\t\t\ttype: \"text\"\n\t\t\trequire",
"end": 409,
"score": 0.9928349852561951,
"start": 401,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ault: \"Steve\"\n\t\t,\n\t\t\tfield: \"username\"\n\t\t\ttitle: \"Nick name\"\n\t\t\ttype: \"text\"\n\t\t\trequired: true\n\t\t\tmultiEdit: ",
"end": 431,
"score": 0.9300446510314941,
"start": 422,
"tag": "NAME",
"value": "Nick name"
},
{
"context": "\t\n\nmodule.exports.objects = [\n\t{\n\t\tid: 1\n\t\tname: \"John Doe\"\n\t\tusername: \"john79\"\n\t\temail: \"john79@gmail.com\"",
"end": 5449,
"score": 0.9998159408569336,
"start": 5441,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "ts = [\n\t{\n\t\tid: 1\n\t\tname: \"John Doe\"\n\t\tusername: \"john79\"\n\t\temail: \"john79@gmail.com\"\n\t\tage: 36\n\t\tdob: \"19",
"end": 5470,
"score": 0.9996165633201599,
"start": 5464,
"tag": "USERNAME",
"value": "john79"
},
{
"context": "\t\tname: \"John Doe\"\n\t\tusername: \"john79\"\n\t\temail: \"john79@gmail.com\"\n\t\tage: 36\n\t\tdob: \"19790522\"\n\t\tactive: true\n\t\tret",
"end": 5498,
"score": 0.99991375207901,
"start": 5482,
"tag": "EMAIL",
"value": "john79@gmail.com"
},
{
"context": "t message to \" + obj.name\n\t},\n\t{\n\t\tid: 2\n\t\tname: \"Michael Smith\"\n\t\tusername: \"michael88\"\n\t\temail: \"michael88@gmai",
"end": 6083,
"score": 0.9998431205749512,
"start": 6070,
"tag": "NAME",
"value": "Michael Smith"
},
{
"context": ",\n\t{\n\t\tid: 2\n\t\tname: \"Michael Smith\"\n\t\tusername: \"michael88\"\n\t\temail: \"michael88@gmail.com\"\n\t\tage: 27\n\t\tdob: ",
"end": 6107,
"score": 0.9995471239089966,
"start": 6098,
"tag": "USERNAME",
"value": "michael88"
},
{
"context": "\"Michael Smith\"\n\t\tusername: \"michael88\"\n\t\temail: \"michael88@gmail.com\"\n\t\tage: 27\n\t\tdob: \"19880127\"\n\t\tactive: false\t\t\t\n\t",
"end": 6138,
"score": 0.9999309182167053,
"start": 6119,
"tag": "EMAIL",
"value": "michael88@gmail.com"
},
{
"context": "\"Michael's value changed\"\n\t},\n\t{\n\t\tid: 3\n\t\tname: \"Jim Beam\"\n\t\tusername: \"jimmy.bean\"\n\t\temail: \"jimmy.bean@gm",
"end": 6512,
"score": 0.9998345375061035,
"start": 6504,
"tag": "NAME",
"value": "Jim Beam"
},
{
"context": "d\"\n\t},\n\t{\n\t\tid: 3\n\t\tname: \"Jim Beam\"\n\t\tusername: \"jimmy.bean\"\n\t\temail: \"jimmy.bean@gmail.com\"\n\t\tage: 61\n\t\tdob:",
"end": 6537,
"score": 0.9996296763420105,
"start": 6527,
"tag": "USERNAME",
"value": "jimmy.bean"
},
{
"context": "me: \"Jim Beam\"\n\t\tusername: \"jimmy.bean\"\n\t\temail: \"jimmy.bean@gmail.com\"\n\t\tage: 61\n\t\tdob: \"19541204\"\n\t\tactive: true\t\t\t\n\t\t",
"end": 6569,
"score": 0.9999322891235352,
"start": 6549,
"tag": "EMAIL",
"value": "jimmy.bean@gmail.com"
},
{
"context": "eLang: \"en\"\n\t\tsex: \"Male\"\n\t},\n\t{\n\t\tid: 4\n\t\tname: \"Sarah Cooper\"\n\t\tusername: \"sarah77\"\n\t\temail: \"sarah77@gmail.co",
"end": 6843,
"score": 0.9998862743377686,
"start": 6831,
"tag": "NAME",
"value": "Sarah Cooper"
},
{
"context": "},\n\t{\n\t\tid: 4\n\t\tname: \"Sarah Cooper\"\n\t\tusername: \"sarah77\"\n\t\temail: \"sarah77@gmail.com\"\n\t\tage: 38\n\t\tdob: \"1",
"end": 6865,
"score": 0.9994513988494873,
"start": 6858,
"tag": "USERNAME",
"value": "sarah77"
},
{
"context": "e: \"Sarah Cooper\"\n\t\tusername: \"sarah77\"\n\t\temail: \"sarah77@gmail.com\"\n\t\tage: 38\n\t\tdob: \"19770921\"\n\t\tactive: true\t\t\t\n\t\t",
"end": 6894,
"score": 0.9999088048934937,
"start": 6877,
"tag": "EMAIL",
"value": "sarah77@gmail.com"
}
] | test/test-data.coffee | icebob/propertiesjs | 21 | _ = require("lodash")
module.exports.schema = {
windowTitle: "Properties Editor"
liveEdit: true
editors: [
field: "id"
title: "ID"
type: "label"
multiEdit: true
,
field: "name"
title: "Name"
type: "text"
placeHolder: "Enter full name"
required: true
multiEdit: true
featured: true
toolTip: "Enter the user's full name"
default: "Steve"
,
field: "username"
title: "Nick name"
type: "text"
required: true
multiEdit: false
featured: true
maxLength: 50
validate: (value, objs) ->
res = []
if /\s/.test value
res.push "Invalid username!"
if value.length < 6
res.push "Username is too short! Minimum 6 characters!"
return res
,
field: "email"
title: "E-mail"
type: "email"
required: false
multiEdit: false
validate: (value, objs) ->
unless /@/.test value
return "Invalid email address"
if value.length < 4
return false
,
field: "password"
title: "Password"
type: "password"
placeHolder: "Password"
required: true
multiEdit: true
featured: true
toolTip: "Enter the user's password"
hint: "Minimum 6 characters"
validate: (value, objs) -> if value.length < 6 then return "Password is too short! Minimum 6 characters!"
,
field: "phone"
title: "Phone"
type: "text"
required: false
multiEdit: true
pattern: "^[237]0/[0-9]{3}-[0-9]{4}$"
hint: "Format: [20/30/70]-000-0000"
,
field: "age"
title: "Age"
type: "number"
required: false
multiEdit: true
minValue: 0
maxValue: null
disabled: (editor, objs) -> return objs[0].active
,
field: "dob"
title: "Date of birth"
type: "date"
placeHolder: "Date of birth"
format: "YYYYMMDD"
required: false
multiEdit: true
validate: (value, objs) ->
if value is "19630307"
return "Invalid date!"
onChanged: (editor, value, workObject) ->
age = new Date().getFullYear() - parseInt(value.substring(0, 4), 10)
ageEditor = editor.PJS.getEditor "age"
if ageEditor?
ageEditor.changeValue age, true
,
field: "active"
title: "Active"
type: "boolean"
required: true
default: true
multiEdit: true
,
field: "avatar"
title: "Avatar"
type: "image"
required: false
multiEdit: false
preview: true
browse: true
,
field: "retired"
title: "Retired"
type: "boolean"
required: true
default: false
multiEdit: true
,
type: "group"
field: "body"
title: "Body properties",
editors: [
field: "body.weight"
title: "Body weight"
type: "number"
required: false
multiEdit: true
minValue: 1
maxValue: 200
,
field: "body.height"
title: "Body height"
type: "number"
required: false
multiEdit: true
minValue: 50
maxValue: 250
,
field: "body.glasses"
title: "Wear glasses"
type: "boolean"
required: true
default: false
multiEdit: true
,
field: "body.foot"
title: "Body foot"
type: "number"
required: false
multiEdit: true
]
,
field: "themeColor"
title: "Theme color"
type: "color"
,
field: "backgroundColor"
title: "Background color"
type: "spectrum"
,
field: "description"
title: "Description"
type: "textarea"
required: false
multiEdit: true
placeHolder: "Your comment"
maxLength: 500
rows: 3
,
field: "ratings"
title: "Ratings"
type: "slider"
required: false
multiEdit: true
default: 1
minValue: 1
maxValue: 5
step: 1
,
field: "nativeLang"
title: "Native language"
type: "select"
required: true
multiEdit: true
default: "de"
values: [
{ id: "en", name: "English" }
{ id: "de", name: "Deutsch" }
{ id: "it", name: "Italiano" }
{ id: "es", name: "Español" }
{ id: "fr", name: "Français" }
]
,
field: "sex"
title: "Male/female"
type: "select"
required: false
multiEdit: true
values: [
"Male"
"Female"
]
,
field: "skills"
title: "Skills"
type: "checklist"
multiEdit: true
values: [
"HTML5"
"CSS3"
"Javascript"
"ES6"
"Coffeescript"
"ReactJS"
"AngularJS"
"SASS/SCSS"
"Less"
]
,
field: "favoriteMovie"
title: "Favorite movie"
type: "select"
required: false
multiEdit: true
values: ->
[
{ id: 1, name: "Matrix" }
{ id: 2, name: "Inception" }
{ id: 3, name: "Kill Bill" }
{ id: 4, name: "Mission Impossible" }
{ id: 5, name: "Interstellar" }
]
,
field: "distance"
title: "Distance"
type: "text"
readonly: true
,
field: "created"
title: "Created at"
type: "timestamp"
format: "YYYYMMDD HHNNSS"
multiEdit: true
readonly: true
,
field: "sendMessage"
title: "Send message to user"
styleClass: "fa fa-envelope"
type: "button"
multiEdit: true
disabled: (editor, objs) -> return not objs[0].active
,
field: "clone"
title: "Clone user"
styleClass: "fa fa-copy"
type: "button"
schemaFunction: true
multiEdit: false
onclick: (objs)->
alert "Clone selected #{objs.length} users"
,
field: "delete"
title: "Delete user"
styleClass: "fa fa-trash"
type: "button"
schemaFunction: true
multiEdit: true
onclick: (objs)->
alert "Delete selected #{objs.length} users"
]
}
module.exports.objects = [
{
id: 1
name: "John Doe"
username: "john79"
email: "john79@gmail.com"
age: 36
dob: "19790522"
active: true
retired: false
created: "20150411 150530"
body:
weight: 72
height: 180
glasses: true
foot: 42
description: "First user"
ratings: 5
nativeLang: "en"
sex: "Male"
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg"
skills: ["Javascript", "Coffeescript", "AngularJS"]
themeColor: "#fab000"
backgroundColor: "rgba(128, 56, 20, 0.6)"
onchanged: -> console.log "John's value changed"
sendMessage: (obj) -> console.log "Sent message to " + obj.name
},
{
id: 2
name: "Michael Smith"
username: "michael88"
email: "michael88@gmail.com"
age: 27
dob: "19880127"
active: false
retired: false
created: "20150411 150535"
body:
weight: 64
height: 165
glasses: false
foot: 42
ratings: 3
nativeLang: "de"
sex: "Male"
skills: ["Javascript", "AngularJS", "ReactJS"]
themeColor: "#FF00F0"
onchanged: -> console.log "Michael's value changed"
},
{
id: 3
name: "Jim Beam"
username: "jimmy.bean"
email: "jimmy.bean@gmail.com"
age: 61
dob: "19541204"
active: true
retired: true
created: "20150319 063320"
body:
weight: 88
height: 180
glasses: true
foot: 42
description: "Last user"
ratings: 5
nativeLang: "en"
sex: "Male"
},
{
id: 4
name: "Sarah Cooper"
username: "sarah77"
email: "sarah77@gmail.com"
age: 38
dob: "19770921"
active: true
retired: false
created: "20150410 123430"
body:
weight: 57
height: 171
glasses: false
foot: 42
description: "Woman"
ratings: 1
nativeLang: "de"
sex: "Female"
onchanged: -> console.log "Sarah's value changed"
}
]
module.exports.clone = ->
return [_.cloneDeep(module.exports.objects), _.cloneDeep(module.exports.schema)]
module.exports.createDivs = (title)->
# $(".propertyEditorWrapper").remove()
console.log "Running #{title}..."
$(".propertyEditor").removeClass().addClass("propertyEditorOld")
$("<div />").addClass("propertyEditorWrapper").append(
$("<div />").addClass("title").text(title),
$("<div />").addClass("propertyEditor")
).appendTo $("body")
module.exports.getEditors = (editors, fields) ->
res = []
_.each editors, (v) ->
if fields.indexOf(v.field) isnt -1 then res.push v
if v.type is "group"
subRes = module.exports.getEditors v.editors, fields
res = res.concat subRes
return
return res | 192181 | _ = require("lodash")
module.exports.schema = {
windowTitle: "Properties Editor"
liveEdit: true
editors: [
field: "id"
title: "ID"
type: "label"
multiEdit: true
,
field: "name"
title: "Name"
type: "text"
placeHolder: "Enter full name"
required: true
multiEdit: true
featured: true
toolTip: "Enter the user's full name"
default: "<NAME>"
,
field: "username"
title: "<NAME>"
type: "text"
required: true
multiEdit: false
featured: true
maxLength: 50
validate: (value, objs) ->
res = []
if /\s/.test value
res.push "Invalid username!"
if value.length < 6
res.push "Username is too short! Minimum 6 characters!"
return res
,
field: "email"
title: "E-mail"
type: "email"
required: false
multiEdit: false
validate: (value, objs) ->
unless /@/.test value
return "Invalid email address"
if value.length < 4
return false
,
field: "password"
title: "Password"
type: "password"
placeHolder: "Password"
required: true
multiEdit: true
featured: true
toolTip: "Enter the user's password"
hint: "Minimum 6 characters"
validate: (value, objs) -> if value.length < 6 then return "Password is too short! Minimum 6 characters!"
,
field: "phone"
title: "Phone"
type: "text"
required: false
multiEdit: true
pattern: "^[237]0/[0-9]{3}-[0-9]{4}$"
hint: "Format: [20/30/70]-000-0000"
,
field: "age"
title: "Age"
type: "number"
required: false
multiEdit: true
minValue: 0
maxValue: null
disabled: (editor, objs) -> return objs[0].active
,
field: "dob"
title: "Date of birth"
type: "date"
placeHolder: "Date of birth"
format: "YYYYMMDD"
required: false
multiEdit: true
validate: (value, objs) ->
if value is "19630307"
return "Invalid date!"
onChanged: (editor, value, workObject) ->
age = new Date().getFullYear() - parseInt(value.substring(0, 4), 10)
ageEditor = editor.PJS.getEditor "age"
if ageEditor?
ageEditor.changeValue age, true
,
field: "active"
title: "Active"
type: "boolean"
required: true
default: true
multiEdit: true
,
field: "avatar"
title: "Avatar"
type: "image"
required: false
multiEdit: false
preview: true
browse: true
,
field: "retired"
title: "Retired"
type: "boolean"
required: true
default: false
multiEdit: true
,
type: "group"
field: "body"
title: "Body properties",
editors: [
field: "body.weight"
title: "Body weight"
type: "number"
required: false
multiEdit: true
minValue: 1
maxValue: 200
,
field: "body.height"
title: "Body height"
type: "number"
required: false
multiEdit: true
minValue: 50
maxValue: 250
,
field: "body.glasses"
title: "Wear glasses"
type: "boolean"
required: true
default: false
multiEdit: true
,
field: "body.foot"
title: "Body foot"
type: "number"
required: false
multiEdit: true
]
,
field: "themeColor"
title: "Theme color"
type: "color"
,
field: "backgroundColor"
title: "Background color"
type: "spectrum"
,
field: "description"
title: "Description"
type: "textarea"
required: false
multiEdit: true
placeHolder: "Your comment"
maxLength: 500
rows: 3
,
field: "ratings"
title: "Ratings"
type: "slider"
required: false
multiEdit: true
default: 1
minValue: 1
maxValue: 5
step: 1
,
field: "nativeLang"
title: "Native language"
type: "select"
required: true
multiEdit: true
default: "de"
values: [
{ id: "en", name: "English" }
{ id: "de", name: "Deutsch" }
{ id: "it", name: "Italiano" }
{ id: "es", name: "Español" }
{ id: "fr", name: "Français" }
]
,
field: "sex"
title: "Male/female"
type: "select"
required: false
multiEdit: true
values: [
"Male"
"Female"
]
,
field: "skills"
title: "Skills"
type: "checklist"
multiEdit: true
values: [
"HTML5"
"CSS3"
"Javascript"
"ES6"
"Coffeescript"
"ReactJS"
"AngularJS"
"SASS/SCSS"
"Less"
]
,
field: "favoriteMovie"
title: "Favorite movie"
type: "select"
required: false
multiEdit: true
values: ->
[
{ id: 1, name: "Matrix" }
{ id: 2, name: "Inception" }
{ id: 3, name: "Kill Bill" }
{ id: 4, name: "Mission Impossible" }
{ id: 5, name: "Interstellar" }
]
,
field: "distance"
title: "Distance"
type: "text"
readonly: true
,
field: "created"
title: "Created at"
type: "timestamp"
format: "YYYYMMDD HHNNSS"
multiEdit: true
readonly: true
,
field: "sendMessage"
title: "Send message to user"
styleClass: "fa fa-envelope"
type: "button"
multiEdit: true
disabled: (editor, objs) -> return not objs[0].active
,
field: "clone"
title: "Clone user"
styleClass: "fa fa-copy"
type: "button"
schemaFunction: true
multiEdit: false
onclick: (objs)->
alert "Clone selected #{objs.length} users"
,
field: "delete"
title: "Delete user"
styleClass: "fa fa-trash"
type: "button"
schemaFunction: true
multiEdit: true
onclick: (objs)->
alert "Delete selected #{objs.length} users"
]
}
module.exports.objects = [
{
id: 1
name: "<NAME>"
username: "john79"
email: "<EMAIL>"
age: 36
dob: "19790522"
active: true
retired: false
created: "20150411 150530"
body:
weight: 72
height: 180
glasses: true
foot: 42
description: "First user"
ratings: 5
nativeLang: "en"
sex: "Male"
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg"
skills: ["Javascript", "Coffeescript", "AngularJS"]
themeColor: "#fab000"
backgroundColor: "rgba(128, 56, 20, 0.6)"
onchanged: -> console.log "John's value changed"
sendMessage: (obj) -> console.log "Sent message to " + obj.name
},
{
id: 2
name: "<NAME>"
username: "michael88"
email: "<EMAIL>"
age: 27
dob: "19880127"
active: false
retired: false
created: "20150411 150535"
body:
weight: 64
height: 165
glasses: false
foot: 42
ratings: 3
nativeLang: "de"
sex: "Male"
skills: ["Javascript", "AngularJS", "ReactJS"]
themeColor: "#FF00F0"
onchanged: -> console.log "Michael's value changed"
},
{
id: 3
name: "<NAME>"
username: "jimmy.bean"
email: "<EMAIL>"
age: 61
dob: "19541204"
active: true
retired: true
created: "20150319 063320"
body:
weight: 88
height: 180
glasses: true
foot: 42
description: "Last user"
ratings: 5
nativeLang: "en"
sex: "Male"
},
{
id: 4
name: "<NAME>"
username: "sarah77"
email: "<EMAIL>"
age: 38
dob: "19770921"
active: true
retired: false
created: "20150410 123430"
body:
weight: 57
height: 171
glasses: false
foot: 42
description: "Woman"
ratings: 1
nativeLang: "de"
sex: "Female"
onchanged: -> console.log "Sarah's value changed"
}
]
module.exports.clone = ->
return [_.cloneDeep(module.exports.objects), _.cloneDeep(module.exports.schema)]
module.exports.createDivs = (title)->
# $(".propertyEditorWrapper").remove()
console.log "Running #{title}..."
$(".propertyEditor").removeClass().addClass("propertyEditorOld")
$("<div />").addClass("propertyEditorWrapper").append(
$("<div />").addClass("title").text(title),
$("<div />").addClass("propertyEditor")
).appendTo $("body")
module.exports.getEditors = (editors, fields) ->
res = []
_.each editors, (v) ->
if fields.indexOf(v.field) isnt -1 then res.push v
if v.type is "group"
subRes = module.exports.getEditors v.editors, fields
res = res.concat subRes
return
return res | true | _ = require("lodash")
module.exports.schema = {
windowTitle: "Properties Editor"
liveEdit: true
editors: [
field: "id"
title: "ID"
type: "label"
multiEdit: true
,
field: "name"
title: "Name"
type: "text"
placeHolder: "Enter full name"
required: true
multiEdit: true
featured: true
toolTip: "Enter the user's full name"
default: "PI:NAME:<NAME>END_PI"
,
field: "username"
title: "PI:NAME:<NAME>END_PI"
type: "text"
required: true
multiEdit: false
featured: true
maxLength: 50
validate: (value, objs) ->
res = []
if /\s/.test value
res.push "Invalid username!"
if value.length < 6
res.push "Username is too short! Minimum 6 characters!"
return res
,
field: "email"
title: "E-mail"
type: "email"
required: false
multiEdit: false
validate: (value, objs) ->
unless /@/.test value
return "Invalid email address"
if value.length < 4
return false
,
field: "password"
title: "Password"
type: "password"
placeHolder: "Password"
required: true
multiEdit: true
featured: true
toolTip: "Enter the user's password"
hint: "Minimum 6 characters"
validate: (value, objs) -> if value.length < 6 then return "Password is too short! Minimum 6 characters!"
,
field: "phone"
title: "Phone"
type: "text"
required: false
multiEdit: true
pattern: "^[237]0/[0-9]{3}-[0-9]{4}$"
hint: "Format: [20/30/70]-000-0000"
,
field: "age"
title: "Age"
type: "number"
required: false
multiEdit: true
minValue: 0
maxValue: null
disabled: (editor, objs) -> return objs[0].active
,
field: "dob"
title: "Date of birth"
type: "date"
placeHolder: "Date of birth"
format: "YYYYMMDD"
required: false
multiEdit: true
validate: (value, objs) ->
if value is "19630307"
return "Invalid date!"
onChanged: (editor, value, workObject) ->
age = new Date().getFullYear() - parseInt(value.substring(0, 4), 10)
ageEditor = editor.PJS.getEditor "age"
if ageEditor?
ageEditor.changeValue age, true
,
field: "active"
title: "Active"
type: "boolean"
required: true
default: true
multiEdit: true
,
field: "avatar"
title: "Avatar"
type: "image"
required: false
multiEdit: false
preview: true
browse: true
,
field: "retired"
title: "Retired"
type: "boolean"
required: true
default: false
multiEdit: true
,
type: "group"
field: "body"
title: "Body properties",
editors: [
field: "body.weight"
title: "Body weight"
type: "number"
required: false
multiEdit: true
minValue: 1
maxValue: 200
,
field: "body.height"
title: "Body height"
type: "number"
required: false
multiEdit: true
minValue: 50
maxValue: 250
,
field: "body.glasses"
title: "Wear glasses"
type: "boolean"
required: true
default: false
multiEdit: true
,
field: "body.foot"
title: "Body foot"
type: "number"
required: false
multiEdit: true
]
,
field: "themeColor"
title: "Theme color"
type: "color"
,
field: "backgroundColor"
title: "Background color"
type: "spectrum"
,
field: "description"
title: "Description"
type: "textarea"
required: false
multiEdit: true
placeHolder: "Your comment"
maxLength: 500
rows: 3
,
field: "ratings"
title: "Ratings"
type: "slider"
required: false
multiEdit: true
default: 1
minValue: 1
maxValue: 5
step: 1
,
field: "nativeLang"
title: "Native language"
type: "select"
required: true
multiEdit: true
default: "de"
values: [
{ id: "en", name: "English" }
{ id: "de", name: "Deutsch" }
{ id: "it", name: "Italiano" }
{ id: "es", name: "Español" }
{ id: "fr", name: "Français" }
]
,
field: "sex"
title: "Male/female"
type: "select"
required: false
multiEdit: true
values: [
"Male"
"Female"
]
,
field: "skills"
title: "Skills"
type: "checklist"
multiEdit: true
values: [
"HTML5"
"CSS3"
"Javascript"
"ES6"
"Coffeescript"
"ReactJS"
"AngularJS"
"SASS/SCSS"
"Less"
]
,
field: "favoriteMovie"
title: "Favorite movie"
type: "select"
required: false
multiEdit: true
values: ->
[
{ id: 1, name: "Matrix" }
{ id: 2, name: "Inception" }
{ id: 3, name: "Kill Bill" }
{ id: 4, name: "Mission Impossible" }
{ id: 5, name: "Interstellar" }
]
,
field: "distance"
title: "Distance"
type: "text"
readonly: true
,
field: "created"
title: "Created at"
type: "timestamp"
format: "YYYYMMDD HHNNSS"
multiEdit: true
readonly: true
,
field: "sendMessage"
title: "Send message to user"
styleClass: "fa fa-envelope"
type: "button"
multiEdit: true
disabled: (editor, objs) -> return not objs[0].active
,
field: "clone"
title: "Clone user"
styleClass: "fa fa-copy"
type: "button"
schemaFunction: true
multiEdit: false
onclick: (objs)->
alert "Clone selected #{objs.length} users"
,
field: "delete"
title: "Delete user"
styleClass: "fa fa-trash"
type: "button"
schemaFunction: true
multiEdit: true
onclick: (objs)->
alert "Delete selected #{objs.length} users"
]
}
module.exports.objects = [
{
id: 1
name: "PI:NAME:<NAME>END_PI"
username: "john79"
email: "PI:EMAIL:<EMAIL>END_PI"
age: 36
dob: "19790522"
active: true
retired: false
created: "20150411 150530"
body:
weight: 72
height: 180
glasses: true
foot: 42
description: "First user"
ratings: 5
nativeLang: "en"
sex: "Male"
avatar: "https://s3.amazonaws.com/uifaces/faces/twitter/peterlandt/128.jpg"
skills: ["Javascript", "Coffeescript", "AngularJS"]
themeColor: "#fab000"
backgroundColor: "rgba(128, 56, 20, 0.6)"
onchanged: -> console.log "John's value changed"
sendMessage: (obj) -> console.log "Sent message to " + obj.name
},
{
id: 2
name: "PI:NAME:<NAME>END_PI"
username: "michael88"
email: "PI:EMAIL:<EMAIL>END_PI"
age: 27
dob: "19880127"
active: false
retired: false
created: "20150411 150535"
body:
weight: 64
height: 165
glasses: false
foot: 42
ratings: 3
nativeLang: "de"
sex: "Male"
skills: ["Javascript", "AngularJS", "ReactJS"]
themeColor: "#FF00F0"
onchanged: -> console.log "Michael's value changed"
},
{
id: 3
name: "PI:NAME:<NAME>END_PI"
username: "jimmy.bean"
email: "PI:EMAIL:<EMAIL>END_PI"
age: 61
dob: "19541204"
active: true
retired: true
created: "20150319 063320"
body:
weight: 88
height: 180
glasses: true
foot: 42
description: "Last user"
ratings: 5
nativeLang: "en"
sex: "Male"
},
{
id: 4
name: "PI:NAME:<NAME>END_PI"
username: "sarah77"
email: "PI:EMAIL:<EMAIL>END_PI"
age: 38
dob: "19770921"
active: true
retired: false
created: "20150410 123430"
body:
weight: 57
height: 171
glasses: false
foot: 42
description: "Woman"
ratings: 1
nativeLang: "de"
sex: "Female"
onchanged: -> console.log "Sarah's value changed"
}
]
module.exports.clone = ->
return [_.cloneDeep(module.exports.objects), _.cloneDeep(module.exports.schema)]
module.exports.createDivs = (title)->
# $(".propertyEditorWrapper").remove()
console.log "Running #{title}..."
$(".propertyEditor").removeClass().addClass("propertyEditorOld")
$("<div />").addClass("propertyEditorWrapper").append(
$("<div />").addClass("title").text(title),
$("<div />").addClass("propertyEditor")
).appendTo $("body")
module.exports.getEditors = (editors, fields) ->
res = []
_.each editors, (v) ->
if fields.indexOf(v.field) isnt -1 then res.push v
if v.type is "group"
subRes = module.exports.getEditors v.editors, fields
res = res.concat subRes
return
return res |
[
{
"context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio",
"end": 30,
"score": 0.9998685717582703,
"start": 17,
"tag": "NAME",
"value": "Joshua Carver"
}
] | src/coffeescript/charts/bar_chart_options.coffee | jcarver989/raphy-charts | 5 | # Copyright 2012 Joshua Carver
#
# 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.
class BarChartOptions
@DEFAULTS: {
bar_width: 20
bar_spacing: 20
bar_color: "#00aadd"
rounding: 0
font_family: "Helvetica, Arial, sans-serif"
show_x_labels: true
show_y_labels: true
x_label_size: 14
x_label_color: "#333"
y_label_size: 14
y_label_color: "#333"
show_grid: false
x_padding: 25
y_padding: 40
}
@merge: (from = {}, to = {}) ->
opts = {}
for option, value of from
opts[option] = value
for option, value of to when to.hasOwnProperty(option)
opts[option] = value
return opts
constructor: (options) ->
opts = {}
for option, value of BarChartOptions.DEFAULTS
opts[option] = value
for option, value of options when options.hasOwnProperty(option)
opts[option] = value
return opts
| 174462 | # Copyright 2012 <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.
class BarChartOptions
@DEFAULTS: {
bar_width: 20
bar_spacing: 20
bar_color: "#00aadd"
rounding: 0
font_family: "Helvetica, Arial, sans-serif"
show_x_labels: true
show_y_labels: true
x_label_size: 14
x_label_color: "#333"
y_label_size: 14
y_label_color: "#333"
show_grid: false
x_padding: 25
y_padding: 40
}
@merge: (from = {}, to = {}) ->
opts = {}
for option, value of from
opts[option] = value
for option, value of to when to.hasOwnProperty(option)
opts[option] = value
return opts
constructor: (options) ->
opts = {}
for option, value of BarChartOptions.DEFAULTS
opts[option] = value
for option, value of options when options.hasOwnProperty(option)
opts[option] = value
return opts
| true | # Copyright 2012 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.
class BarChartOptions
@DEFAULTS: {
bar_width: 20
bar_spacing: 20
bar_color: "#00aadd"
rounding: 0
font_family: "Helvetica, Arial, sans-serif"
show_x_labels: true
show_y_labels: true
x_label_size: 14
x_label_color: "#333"
y_label_size: 14
y_label_color: "#333"
show_grid: false
x_padding: 25
y_padding: 40
}
@merge: (from = {}, to = {}) ->
opts = {}
for option, value of from
opts[option] = value
for option, value of to when to.hasOwnProperty(option)
opts[option] = value
return opts
constructor: (options) ->
opts = {}
for option, value of BarChartOptions.DEFAULTS
opts[option] = value
for option, value of options when options.hasOwnProperty(option)
opts[option] = value
return opts
|
[
{
"context": "ion processing code exhibited in Phytodynamica, by James Stone (www.jamesjamesjames.com)\n\n###\n\ncoffee_draw = (p5",
"end": 132,
"score": 0.9998869299888611,
"start": 121,
"tag": "NAME",
"value": "James Stone"
}
] | prototypes/p5coffee/phytodynamica/js/app.coffee | jamesstoneco/canvas-only | 1 | ###
Simple demonstration of 3 modes of drawing, simular to my projection processing code exhibited in Phytodynamica, by James Stone (www.jamesjamesjames.com)
###
coffee_draw = (p5) ->
drawMode = 0
circles = () ->
p5.noStroke()
for i in [0..20] by 1
circle_size = p5.random(10, 40)
if circle_size < 30 then p5.fill 255, 0, 0 else p5.fill 0, 0, 255
p5.ellipse p5.random(0, p5.width), p5.random(0, p5.height), circle_size, circle_size
lines = () ->
for i in [0..10] by 1
if p5.random(0,1) > 0.3 then p5.stroke 255, 0, 0 else p5.stroke 0, 0, 255
xLoc = p5.random(0, p5.width)
p5.line xLoc, 0, xLoc, p5.height
linesHoriz = () ->
for i in [0..10] by 1
if p5.random(0,1) > 0.3 then p5.stroke 255, 0, 0 else p5.stroke 0, 0, 255
yLoc = p5.random(0, p5.height)
p5.line 0, yLoc, p5.width, yLoc
p5.setup = () ->
p5.size $(window).width(), $(window).height()
p5.draw = () ->
switch drawMode
when 0 then circles()
when 1 then lines()
when 2 then linesHoriz()
drawMode = p5.floor(p5.random(0,3)) if p5.frameCount % 200 == 0
### do not edit below ###
# change canvas / processing sketch size to match resized window, note restarts sketch
$(window).resize ->
processing.size $(window).width(), $(window).height()
$(document).ready ->
canvas = document.getElementById "p5canvas"
window.processing = new Processing canvas, coffee_draw | 36870 | ###
Simple demonstration of 3 modes of drawing, simular to my projection processing code exhibited in Phytodynamica, by <NAME> (www.jamesjamesjames.com)
###
coffee_draw = (p5) ->
drawMode = 0
circles = () ->
p5.noStroke()
for i in [0..20] by 1
circle_size = p5.random(10, 40)
if circle_size < 30 then p5.fill 255, 0, 0 else p5.fill 0, 0, 255
p5.ellipse p5.random(0, p5.width), p5.random(0, p5.height), circle_size, circle_size
lines = () ->
for i in [0..10] by 1
if p5.random(0,1) > 0.3 then p5.stroke 255, 0, 0 else p5.stroke 0, 0, 255
xLoc = p5.random(0, p5.width)
p5.line xLoc, 0, xLoc, p5.height
linesHoriz = () ->
for i in [0..10] by 1
if p5.random(0,1) > 0.3 then p5.stroke 255, 0, 0 else p5.stroke 0, 0, 255
yLoc = p5.random(0, p5.height)
p5.line 0, yLoc, p5.width, yLoc
p5.setup = () ->
p5.size $(window).width(), $(window).height()
p5.draw = () ->
switch drawMode
when 0 then circles()
when 1 then lines()
when 2 then linesHoriz()
drawMode = p5.floor(p5.random(0,3)) if p5.frameCount % 200 == 0
### do not edit below ###
# change canvas / processing sketch size to match resized window, note restarts sketch
$(window).resize ->
processing.size $(window).width(), $(window).height()
$(document).ready ->
canvas = document.getElementById "p5canvas"
window.processing = new Processing canvas, coffee_draw | true | ###
Simple demonstration of 3 modes of drawing, simular to my projection processing code exhibited in Phytodynamica, by PI:NAME:<NAME>END_PI (www.jamesjamesjames.com)
###
coffee_draw = (p5) ->
drawMode = 0
circles = () ->
p5.noStroke()
for i in [0..20] by 1
circle_size = p5.random(10, 40)
if circle_size < 30 then p5.fill 255, 0, 0 else p5.fill 0, 0, 255
p5.ellipse p5.random(0, p5.width), p5.random(0, p5.height), circle_size, circle_size
lines = () ->
for i in [0..10] by 1
if p5.random(0,1) > 0.3 then p5.stroke 255, 0, 0 else p5.stroke 0, 0, 255
xLoc = p5.random(0, p5.width)
p5.line xLoc, 0, xLoc, p5.height
linesHoriz = () ->
for i in [0..10] by 1
if p5.random(0,1) > 0.3 then p5.stroke 255, 0, 0 else p5.stroke 0, 0, 255
yLoc = p5.random(0, p5.height)
p5.line 0, yLoc, p5.width, yLoc
p5.setup = () ->
p5.size $(window).width(), $(window).height()
p5.draw = () ->
switch drawMode
when 0 then circles()
when 1 then lines()
when 2 then linesHoriz()
drawMode = p5.floor(p5.random(0,3)) if p5.frameCount % 200 == 0
### do not edit below ###
# change canvas / processing sketch size to match resized window, note restarts sketch
$(window).resize ->
processing.size $(window).width(), $(window).height()
$(document).ready ->
canvas = document.getElementById "p5canvas"
window.processing = new Processing canvas, coffee_draw |
[
{
"context": "e', 'multi')\n\n wantsServer: true\n\n masterName: 'Master'\n masterMandatory: false\n\n coin: null\n\n cosign",
"end": 993,
"score": 0.9181723594665527,
"start": 987,
"tag": "NAME",
"value": "Master"
}
] | app/components/account/new-account-wizard.coffee | melis-wallet/melis-cm-client | 1 | import Component from '@ember/component'
import { inject as service } from '@ember/service'
import { alias, equal } from '@ember/object/computed'
import { get } from '@ember/object'
import { A } from '@ember/array'
import CMCore from 'melis-api-js'
import { validator, buildValidations } from 'ember-cp-validations'
import AsWizard from 'ember-leaf-core/mixins/leaf-as-wizard'
import { task, taskGroup } from 'ember-concurrency'
import Logger from 'melis-cm-svcs/utils/logger'
C = CMCore.C
Validations = buildValidations(
accountName: [
validator('presence', true)
validator('length', min: 1, max: 32)
]
selectedScheme: [
validator('presence', true)
]
)
NewAccountWizard = Component.extend(AsWizard, Validations,
cm: service('cm-session')
coinsvc: service('cm-coin')
apiOps: taskGroup().drop()
joinAccount: false
step: 1
stepBack: true
accountName: null
type: null
isMulti: equal('type', 'multi')
wantsServer: true
masterName: 'Master'
masterMandatory: false
coin: null
cosignersCnt: alias('cosigners.length')
totalSignatures: ( ->
@get('cosignersCnt') + 1
).property('cosignersCnt')
minSignatures: null
cosigners: null
createError: null
serverLocked: false
newAccount: null
completeOn: ( ->
if @get('isMulti')
5
else
4
).property('isMulti')
availableCoins: alias('coinsvc.enabledCoins')
selectedCoin: ( ->
if c = @get('coin')
@get('availableCoins').findBy('unit', c)
).property('coin', 'availableCoins')
coin: null
selectedScheme: ( ->
{ type, wantsServer } = @getProperties('type', 'wantsServer')
switch type
when 'single'
if wantsServer
C.TYPE_2OF2_SERVER
else
C.TYPE_PLAIN_HD
when 'multi'
if wantsServer
C.TYPE_MULTISIG_MANDATORY_SERVER
else
C.TYPE_MULTISIG_NO_SERVER
).property('type', 'wantsServer')
accountCreateTask: task((data) ->
@set('createError', null)
try
account = yield @get('cm').accountCreate(data)
@set('newAccount', account)
catch error
Logger.error("Create Account failed:", error)
if error.ex == 'CmServerLockedException'
@set('serverLocked', true)
else
@set('createError', error)
).group('apiOps')
accountCreate: ->
cm = @get('cm')
{ coin,
accountName,
masterName,
masterMandatory,
minSignatures,
selectedScheme } = @getProperties('coin', 'accountName', 'masterName', 'masterMandatory', 'minSignatures', 'selectedScheme')
if @get('isMulti')
cosigners = @get('cosigners').map( (i)->
{ name: i.name, mandatory: i.mandatory }
)
minSignatures = @get('minSignatures')
else
cosigners = []
minSignatures = null
masterName = null
@get('accountCreateTask').perform(
coin: coin
type: selectedScheme
meta: {name: accountName, masterName: masterName}
pubMeta: {name: accountName}
minSignatures: minSignatures
mandatorySignature: masterMandatory
cosigners: cosigners
)
setup: ( ->
@setProperties
cosigners: A()
#coin: @get('availableCoins.firstObject.unit')
).on('init')
finishWizard: (account) ->
if modal = @get('modal')
modal.close(true).then( =>
@sendAction('on-wizard-finish', account)
)
else
@sendAction('on-wizard-finish', account)
actions:
selectCoin: (c) ->
if unit = get(c, 'unit')
@set('coin', unit)
destroyWizard: ->
# not sure, but lets do this
if newA = @get('newAccount.pubId')
@get('cm').selectAccount(newA)
@finishWizard(@get('newAccount'))
'complete-step': (value) ->
@markCompleted(value)
@set('step', value + 1)
doJoinAcc: ->
@set('joinAccount', true)
cancelJoinAcc: ->
@set('joinAccount', false)
doneJoinAcc: (account) ->
@finishWizard(account)
doneNameSelect: ->
@markCompleted()
@accountCreate()
doneCosigners: (data) ->
@setProperties(data)
@markCompleted(4, 5)
typeSelected: ->
if @get('type')
@markCompleted(2, 3)
coinSelected: ->
if @get('coin')
@markCompleted(1, 2)
serverSelected: ->
@markCompleted(3, 4)
singleAccount: ->
@set('type', 'single')
multiAccount: ->
@set('type', 'multi')
noServer: ->
@set('wantsServer', false)
withServer: ->
@set('wantsServer', true)
)
export default NewAccountWizard
| 145028 | import Component from '@ember/component'
import { inject as service } from '@ember/service'
import { alias, equal } from '@ember/object/computed'
import { get } from '@ember/object'
import { A } from '@ember/array'
import CMCore from 'melis-api-js'
import { validator, buildValidations } from 'ember-cp-validations'
import AsWizard from 'ember-leaf-core/mixins/leaf-as-wizard'
import { task, taskGroup } from 'ember-concurrency'
import Logger from 'melis-cm-svcs/utils/logger'
C = CMCore.C
Validations = buildValidations(
accountName: [
validator('presence', true)
validator('length', min: 1, max: 32)
]
selectedScheme: [
validator('presence', true)
]
)
NewAccountWizard = Component.extend(AsWizard, Validations,
cm: service('cm-session')
coinsvc: service('cm-coin')
apiOps: taskGroup().drop()
joinAccount: false
step: 1
stepBack: true
accountName: null
type: null
isMulti: equal('type', 'multi')
wantsServer: true
masterName: '<NAME>'
masterMandatory: false
coin: null
cosignersCnt: alias('cosigners.length')
totalSignatures: ( ->
@get('cosignersCnt') + 1
).property('cosignersCnt')
minSignatures: null
cosigners: null
createError: null
serverLocked: false
newAccount: null
completeOn: ( ->
if @get('isMulti')
5
else
4
).property('isMulti')
availableCoins: alias('coinsvc.enabledCoins')
selectedCoin: ( ->
if c = @get('coin')
@get('availableCoins').findBy('unit', c)
).property('coin', 'availableCoins')
coin: null
selectedScheme: ( ->
{ type, wantsServer } = @getProperties('type', 'wantsServer')
switch type
when 'single'
if wantsServer
C.TYPE_2OF2_SERVER
else
C.TYPE_PLAIN_HD
when 'multi'
if wantsServer
C.TYPE_MULTISIG_MANDATORY_SERVER
else
C.TYPE_MULTISIG_NO_SERVER
).property('type', 'wantsServer')
accountCreateTask: task((data) ->
@set('createError', null)
try
account = yield @get('cm').accountCreate(data)
@set('newAccount', account)
catch error
Logger.error("Create Account failed:", error)
if error.ex == 'CmServerLockedException'
@set('serverLocked', true)
else
@set('createError', error)
).group('apiOps')
accountCreate: ->
cm = @get('cm')
{ coin,
accountName,
masterName,
masterMandatory,
minSignatures,
selectedScheme } = @getProperties('coin', 'accountName', 'masterName', 'masterMandatory', 'minSignatures', 'selectedScheme')
if @get('isMulti')
cosigners = @get('cosigners').map( (i)->
{ name: i.name, mandatory: i.mandatory }
)
minSignatures = @get('minSignatures')
else
cosigners = []
minSignatures = null
masterName = null
@get('accountCreateTask').perform(
coin: coin
type: selectedScheme
meta: {name: accountName, masterName: masterName}
pubMeta: {name: accountName}
minSignatures: minSignatures
mandatorySignature: masterMandatory
cosigners: cosigners
)
setup: ( ->
@setProperties
cosigners: A()
#coin: @get('availableCoins.firstObject.unit')
).on('init')
finishWizard: (account) ->
if modal = @get('modal')
modal.close(true).then( =>
@sendAction('on-wizard-finish', account)
)
else
@sendAction('on-wizard-finish', account)
actions:
selectCoin: (c) ->
if unit = get(c, 'unit')
@set('coin', unit)
destroyWizard: ->
# not sure, but lets do this
if newA = @get('newAccount.pubId')
@get('cm').selectAccount(newA)
@finishWizard(@get('newAccount'))
'complete-step': (value) ->
@markCompleted(value)
@set('step', value + 1)
doJoinAcc: ->
@set('joinAccount', true)
cancelJoinAcc: ->
@set('joinAccount', false)
doneJoinAcc: (account) ->
@finishWizard(account)
doneNameSelect: ->
@markCompleted()
@accountCreate()
doneCosigners: (data) ->
@setProperties(data)
@markCompleted(4, 5)
typeSelected: ->
if @get('type')
@markCompleted(2, 3)
coinSelected: ->
if @get('coin')
@markCompleted(1, 2)
serverSelected: ->
@markCompleted(3, 4)
singleAccount: ->
@set('type', 'single')
multiAccount: ->
@set('type', 'multi')
noServer: ->
@set('wantsServer', false)
withServer: ->
@set('wantsServer', true)
)
export default NewAccountWizard
| true | import Component from '@ember/component'
import { inject as service } from '@ember/service'
import { alias, equal } from '@ember/object/computed'
import { get } from '@ember/object'
import { A } from '@ember/array'
import CMCore from 'melis-api-js'
import { validator, buildValidations } from 'ember-cp-validations'
import AsWizard from 'ember-leaf-core/mixins/leaf-as-wizard'
import { task, taskGroup } from 'ember-concurrency'
import Logger from 'melis-cm-svcs/utils/logger'
C = CMCore.C
Validations = buildValidations(
accountName: [
validator('presence', true)
validator('length', min: 1, max: 32)
]
selectedScheme: [
validator('presence', true)
]
)
NewAccountWizard = Component.extend(AsWizard, Validations,
cm: service('cm-session')
coinsvc: service('cm-coin')
apiOps: taskGroup().drop()
joinAccount: false
step: 1
stepBack: true
accountName: null
type: null
isMulti: equal('type', 'multi')
wantsServer: true
masterName: 'PI:NAME:<NAME>END_PI'
masterMandatory: false
coin: null
cosignersCnt: alias('cosigners.length')
totalSignatures: ( ->
@get('cosignersCnt') + 1
).property('cosignersCnt')
minSignatures: null
cosigners: null
createError: null
serverLocked: false
newAccount: null
completeOn: ( ->
if @get('isMulti')
5
else
4
).property('isMulti')
availableCoins: alias('coinsvc.enabledCoins')
selectedCoin: ( ->
if c = @get('coin')
@get('availableCoins').findBy('unit', c)
).property('coin', 'availableCoins')
coin: null
selectedScheme: ( ->
{ type, wantsServer } = @getProperties('type', 'wantsServer')
switch type
when 'single'
if wantsServer
C.TYPE_2OF2_SERVER
else
C.TYPE_PLAIN_HD
when 'multi'
if wantsServer
C.TYPE_MULTISIG_MANDATORY_SERVER
else
C.TYPE_MULTISIG_NO_SERVER
).property('type', 'wantsServer')
accountCreateTask: task((data) ->
@set('createError', null)
try
account = yield @get('cm').accountCreate(data)
@set('newAccount', account)
catch error
Logger.error("Create Account failed:", error)
if error.ex == 'CmServerLockedException'
@set('serverLocked', true)
else
@set('createError', error)
).group('apiOps')
accountCreate: ->
cm = @get('cm')
{ coin,
accountName,
masterName,
masterMandatory,
minSignatures,
selectedScheme } = @getProperties('coin', 'accountName', 'masterName', 'masterMandatory', 'minSignatures', 'selectedScheme')
if @get('isMulti')
cosigners = @get('cosigners').map( (i)->
{ name: i.name, mandatory: i.mandatory }
)
minSignatures = @get('minSignatures')
else
cosigners = []
minSignatures = null
masterName = null
@get('accountCreateTask').perform(
coin: coin
type: selectedScheme
meta: {name: accountName, masterName: masterName}
pubMeta: {name: accountName}
minSignatures: minSignatures
mandatorySignature: masterMandatory
cosigners: cosigners
)
setup: ( ->
@setProperties
cosigners: A()
#coin: @get('availableCoins.firstObject.unit')
).on('init')
finishWizard: (account) ->
if modal = @get('modal')
modal.close(true).then( =>
@sendAction('on-wizard-finish', account)
)
else
@sendAction('on-wizard-finish', account)
actions:
selectCoin: (c) ->
if unit = get(c, 'unit')
@set('coin', unit)
destroyWizard: ->
# not sure, but lets do this
if newA = @get('newAccount.pubId')
@get('cm').selectAccount(newA)
@finishWizard(@get('newAccount'))
'complete-step': (value) ->
@markCompleted(value)
@set('step', value + 1)
doJoinAcc: ->
@set('joinAccount', true)
cancelJoinAcc: ->
@set('joinAccount', false)
doneJoinAcc: (account) ->
@finishWizard(account)
doneNameSelect: ->
@markCompleted()
@accountCreate()
doneCosigners: (data) ->
@setProperties(data)
@markCompleted(4, 5)
typeSelected: ->
if @get('type')
@markCompleted(2, 3)
coinSelected: ->
if @get('coin')
@markCompleted(1, 2)
serverSelected: ->
@markCompleted(3, 4)
singleAccount: ->
@set('type', 'single')
multiAccount: ->
@set('type', 'multi')
noServer: ->
@set('wantsServer', false)
withServer: ->
@set('wantsServer', true)
)
export default NewAccountWizard
|
[
{
"context": "\"\n\nmodule.exports =\n subscriptions: null\n key: \"activate-power-mode.particles.colours\"\n conf: []\n golden_ratio_conjugate: 0.618033988",
"end": 124,
"score": 0.9894469976425171,
"start": 87,
"tag": "KEY",
"value": "activate-power-mode.particles.colours"
}
] | lib/color-helper.coffee | kyl3r92/activate-power-mode | 4,172 | {CompositeDisposable} = require "atom"
module.exports =
subscriptions: null
key: "activate-power-mode.particles.colours"
conf: []
golden_ratio_conjugate: 0.618033988749895
init: ->
@initConfigSubscribers()
@initList()
disable: ->
@subscriptions?.dispose()
@colorList?.dispose()
@colorList = null
observe: (key) ->
@subscriptions.add atom.config.observe(
"#{@key}.#{key}", (value) =>
@conf[key] = value
)
initConfigSubscribers: ->
@subscriptions = new CompositeDisposable
@observe 'type'
@observe 'fixed'
@observe 'randomType'
hsvToRgb: (h,s,v) -> # HSV to RGB algorithm, as per wikipedia
c = v * s
h2 = (360.0*h) /60.0 # According to wikipedia, 0<h<360...
h3 = Math.abs((h2%2) - 1.0)
x = c * (1.0 - h3)
m = v - c
if 0<=h2<1 then return [c+m,x+m,m]
if 1<=h2<2 then return [x+m,c+m,m]
if 2<=h2<3 then return [m,c+m,x+m]
if 3<=h2<4 then return [m,x+m,c+m]
if 4<=h2<5 then return [x+m,m,c+m]
if 5<=h2<6 then return [c+m,m,x+m]
getFixedColorGenerator: ->
c = @conf['fixed']
color = "rgb(#{c.red},#{c.green},#{c.blue})"
loop
yield color
return
getRandomBrightColor: ->
@seed += @golden_ratio_conjugate
@seed = @seed - (@seed//1)
rgb = @hsvToRgb(@seed,1,1)
r = (rgb[0]*255)//1
g = (rgb[1]*255)//1
b = (rgb[2]*255)//1
"rgb(#{r},#{g},#{b})"
getRandomAllColor: ->
r = Math.floor(Math.random() * 256)
g = Math.floor(Math.random() * 256)
b = Math.floor(Math.random() * 256)
"rgb(#{r},#{g},#{b})"
getRandomGenerator: ->
if @conf['randomType'] == 'bright'
@seed = Math.random()
loop
yield @getRandomBrightColor()
return
else
loop
yield @getRandomAllColor()
return
getRandomSpawnGenerator: ->
if @conf['randomType'] == 'bright'
@seed = Math.random()
color = @getRandomBrightColor()
else
color = @getRandomAllColor()
loop
yield color
return
getColorAtCursorGenerator: (cursor, editorElement) ->
color = @getColorAtCursor cursor, editorElement
loop
yield color
return
getColorAtCursor: (cursor, editorElement) ->
scope = cursor.getScopeDescriptor()
scope = scope.toString().replace(/\./g, '.syntax--')
try
el = editorElement.querySelector scope
catch error
"rgb(255, 255, 255)"
if el
getComputedStyle(el).color
else
"rgb(255, 255, 255)"
generateColors: (cursor, editorElement) ->
colorType = @conf['type']
if (colorType == 'random')
return @getRandomGenerator()
else if colorType == 'fixed'
@getFixedColorGenerator()
else if colorType == 'randomSpawn'
@getRandomSpawnGenerator()
else
@getColorAtCursorGenerator cursor, editorElement
selectColor: (code) ->
atom.config.set("#{@key}.type", code)
initList: ->
return if @colorList?
@colorList = require "./color-list"
@colorList.init this
@subscriptions.add atom.commands.add "atom-workspace",
"activate-power-mode:select-color": =>
@colorList.toggle()
| 5853 | {CompositeDisposable} = require "atom"
module.exports =
subscriptions: null
key: "<KEY>"
conf: []
golden_ratio_conjugate: 0.618033988749895
init: ->
@initConfigSubscribers()
@initList()
disable: ->
@subscriptions?.dispose()
@colorList?.dispose()
@colorList = null
observe: (key) ->
@subscriptions.add atom.config.observe(
"#{@key}.#{key}", (value) =>
@conf[key] = value
)
initConfigSubscribers: ->
@subscriptions = new CompositeDisposable
@observe 'type'
@observe 'fixed'
@observe 'randomType'
hsvToRgb: (h,s,v) -> # HSV to RGB algorithm, as per wikipedia
c = v * s
h2 = (360.0*h) /60.0 # According to wikipedia, 0<h<360...
h3 = Math.abs((h2%2) - 1.0)
x = c * (1.0 - h3)
m = v - c
if 0<=h2<1 then return [c+m,x+m,m]
if 1<=h2<2 then return [x+m,c+m,m]
if 2<=h2<3 then return [m,c+m,x+m]
if 3<=h2<4 then return [m,x+m,c+m]
if 4<=h2<5 then return [x+m,m,c+m]
if 5<=h2<6 then return [c+m,m,x+m]
getFixedColorGenerator: ->
c = @conf['fixed']
color = "rgb(#{c.red},#{c.green},#{c.blue})"
loop
yield color
return
getRandomBrightColor: ->
@seed += @golden_ratio_conjugate
@seed = @seed - (@seed//1)
rgb = @hsvToRgb(@seed,1,1)
r = (rgb[0]*255)//1
g = (rgb[1]*255)//1
b = (rgb[2]*255)//1
"rgb(#{r},#{g},#{b})"
getRandomAllColor: ->
r = Math.floor(Math.random() * 256)
g = Math.floor(Math.random() * 256)
b = Math.floor(Math.random() * 256)
"rgb(#{r},#{g},#{b})"
getRandomGenerator: ->
if @conf['randomType'] == 'bright'
@seed = Math.random()
loop
yield @getRandomBrightColor()
return
else
loop
yield @getRandomAllColor()
return
getRandomSpawnGenerator: ->
if @conf['randomType'] == 'bright'
@seed = Math.random()
color = @getRandomBrightColor()
else
color = @getRandomAllColor()
loop
yield color
return
getColorAtCursorGenerator: (cursor, editorElement) ->
color = @getColorAtCursor cursor, editorElement
loop
yield color
return
getColorAtCursor: (cursor, editorElement) ->
scope = cursor.getScopeDescriptor()
scope = scope.toString().replace(/\./g, '.syntax--')
try
el = editorElement.querySelector scope
catch error
"rgb(255, 255, 255)"
if el
getComputedStyle(el).color
else
"rgb(255, 255, 255)"
generateColors: (cursor, editorElement) ->
colorType = @conf['type']
if (colorType == 'random')
return @getRandomGenerator()
else if colorType == 'fixed'
@getFixedColorGenerator()
else if colorType == 'randomSpawn'
@getRandomSpawnGenerator()
else
@getColorAtCursorGenerator cursor, editorElement
selectColor: (code) ->
atom.config.set("#{@key}.type", code)
initList: ->
return if @colorList?
@colorList = require "./color-list"
@colorList.init this
@subscriptions.add atom.commands.add "atom-workspace",
"activate-power-mode:select-color": =>
@colorList.toggle()
| true | {CompositeDisposable} = require "atom"
module.exports =
subscriptions: null
key: "PI:KEY:<KEY>END_PI"
conf: []
golden_ratio_conjugate: 0.618033988749895
init: ->
@initConfigSubscribers()
@initList()
disable: ->
@subscriptions?.dispose()
@colorList?.dispose()
@colorList = null
observe: (key) ->
@subscriptions.add atom.config.observe(
"#{@key}.#{key}", (value) =>
@conf[key] = value
)
initConfigSubscribers: ->
@subscriptions = new CompositeDisposable
@observe 'type'
@observe 'fixed'
@observe 'randomType'
hsvToRgb: (h,s,v) -> # HSV to RGB algorithm, as per wikipedia
c = v * s
h2 = (360.0*h) /60.0 # According to wikipedia, 0<h<360...
h3 = Math.abs((h2%2) - 1.0)
x = c * (1.0 - h3)
m = v - c
if 0<=h2<1 then return [c+m,x+m,m]
if 1<=h2<2 then return [x+m,c+m,m]
if 2<=h2<3 then return [m,c+m,x+m]
if 3<=h2<4 then return [m,x+m,c+m]
if 4<=h2<5 then return [x+m,m,c+m]
if 5<=h2<6 then return [c+m,m,x+m]
getFixedColorGenerator: ->
c = @conf['fixed']
color = "rgb(#{c.red},#{c.green},#{c.blue})"
loop
yield color
return
getRandomBrightColor: ->
@seed += @golden_ratio_conjugate
@seed = @seed - (@seed//1)
rgb = @hsvToRgb(@seed,1,1)
r = (rgb[0]*255)//1
g = (rgb[1]*255)//1
b = (rgb[2]*255)//1
"rgb(#{r},#{g},#{b})"
getRandomAllColor: ->
r = Math.floor(Math.random() * 256)
g = Math.floor(Math.random() * 256)
b = Math.floor(Math.random() * 256)
"rgb(#{r},#{g},#{b})"
getRandomGenerator: ->
if @conf['randomType'] == 'bright'
@seed = Math.random()
loop
yield @getRandomBrightColor()
return
else
loop
yield @getRandomAllColor()
return
getRandomSpawnGenerator: ->
if @conf['randomType'] == 'bright'
@seed = Math.random()
color = @getRandomBrightColor()
else
color = @getRandomAllColor()
loop
yield color
return
getColorAtCursorGenerator: (cursor, editorElement) ->
color = @getColorAtCursor cursor, editorElement
loop
yield color
return
getColorAtCursor: (cursor, editorElement) ->
scope = cursor.getScopeDescriptor()
scope = scope.toString().replace(/\./g, '.syntax--')
try
el = editorElement.querySelector scope
catch error
"rgb(255, 255, 255)"
if el
getComputedStyle(el).color
else
"rgb(255, 255, 255)"
generateColors: (cursor, editorElement) ->
colorType = @conf['type']
if (colorType == 'random')
return @getRandomGenerator()
else if colorType == 'fixed'
@getFixedColorGenerator()
else if colorType == 'randomSpawn'
@getRandomSpawnGenerator()
else
@getColorAtCursorGenerator cursor, editorElement
selectColor: (code) ->
atom.config.set("#{@key}.type", code)
initList: ->
return if @colorList?
@colorList = require "./color-list"
@colorList.init this
@subscriptions.add atom.commands.add "atom-workspace",
"activate-power-mode:select-color": =>
@colorList.toggle()
|
[
{
"context": "dash'\n\nclass Util\n\n #see https://gist.github.com/dperini/729294\n re_weburl = new RegExp(\n \"^\" +\n # ",
"end": 72,
"score": 0.999603807926178,
"start": 65,
"tag": "USERNAME",
"value": "dperini"
},
{
"context": " network 0.0.0.0\n # excludes reserved space >= 224.0.0.0\n # excludes network & broacast addresses\n #",
"end": 584,
"score": 0.9982795715332031,
"start": 575,
"tag": "IP_ADDRESS",
"value": "224.0.0.0"
}
] | src/util.coffee | Oipo/hubot-toldify | 0 | _ = require 'lodash'
class Util
#see https://gist.github.com/dperini/729294
re_weburl = new RegExp(
"^" +
# protocol identifier
"(?:(?:https?|ftp)://)" +
# user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
# IP address exclusion
# private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 224.0.0.0
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
# domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
# TLD identifier
"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
# TLD may end with dot
"\\.?" +
")" +
# port number
"(?::\\d{2,5})?" +
# resource path
"(?:[/?#]\\S*)?" +
"$", "i"
)
isValidUrl: (url) ->
return re_weburl.test url
convertToData: (body, url) ->
bodyArray = body.toString().split '\n'
_.remove bodyArray, (n) ->
if n in ['', '```']
return true
return false
{url: url, data: bodyArray}
reloadAllData: (robot) ->
currentCommands = robot.brain.get "toldify-commands"
if not currentCommands? or currentCommands.length <= 0
return
_(currentCommands).forEach (val) =>
storedArray = robot.brain.get "toldify-command-#{val}"
url = storedArray.url
robot.http(url).get() (err, httpRes, body) =>
if err
console.err err.stack
return
if httpRes.statusCode isnt 200
console.err "couldn't reload #{url} due to status code #{httpRes.statusCode}"
return
storedData = @convertToData(body, url)
robot.brain.set "toldify-command-#{val}", storedData
module.exports = Util | 69878 | _ = require 'lodash'
class Util
#see https://gist.github.com/dperini/729294
re_weburl = new RegExp(
"^" +
# protocol identifier
"(?:(?:https?|ftp)://)" +
# user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
# IP address exclusion
# private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 172.16.58.3
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
# domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
# TLD identifier
"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
# TLD may end with dot
"\\.?" +
")" +
# port number
"(?::\\d{2,5})?" +
# resource path
"(?:[/?#]\\S*)?" +
"$", "i"
)
isValidUrl: (url) ->
return re_weburl.test url
convertToData: (body, url) ->
bodyArray = body.toString().split '\n'
_.remove bodyArray, (n) ->
if n in ['', '```']
return true
return false
{url: url, data: bodyArray}
reloadAllData: (robot) ->
currentCommands = robot.brain.get "toldify-commands"
if not currentCommands? or currentCommands.length <= 0
return
_(currentCommands).forEach (val) =>
storedArray = robot.brain.get "toldify-command-#{val}"
url = storedArray.url
robot.http(url).get() (err, httpRes, body) =>
if err
console.err err.stack
return
if httpRes.statusCode isnt 200
console.err "couldn't reload #{url} due to status code #{httpRes.statusCode}"
return
storedData = @convertToData(body, url)
robot.brain.set "toldify-command-#{val}", storedData
module.exports = Util | true | _ = require 'lodash'
class Util
#see https://gist.github.com/dperini/729294
re_weburl = new RegExp(
"^" +
# protocol identifier
"(?:(?:https?|ftp)://)" +
# user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
# IP address exclusion
# private & local networks
"(?!(?:10|127)(?:\\.\\d{1,3}){3})" +
"(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})" +
"(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= PI:IP_ADDRESS:172.16.58.3END_PI
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
# domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
# TLD identifier
"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
# TLD may end with dot
"\\.?" +
")" +
# port number
"(?::\\d{2,5})?" +
# resource path
"(?:[/?#]\\S*)?" +
"$", "i"
)
isValidUrl: (url) ->
return re_weburl.test url
convertToData: (body, url) ->
bodyArray = body.toString().split '\n'
_.remove bodyArray, (n) ->
if n in ['', '```']
return true
return false
{url: url, data: bodyArray}
reloadAllData: (robot) ->
currentCommands = robot.brain.get "toldify-commands"
if not currentCommands? or currentCommands.length <= 0
return
_(currentCommands).forEach (val) =>
storedArray = robot.brain.get "toldify-command-#{val}"
url = storedArray.url
robot.http(url).get() (err, httpRes, body) =>
if err
console.err err.stack
return
if httpRes.statusCode isnt 200
console.err "couldn't reload #{url} due to status code #{httpRes.statusCode}"
return
storedData = @convertToData(body, url)
robot.brain.set "toldify-command-#{val}", storedData
module.exports = Util |
[
{
"context": ".active = 0;\n this.ctors = {}\n this.name = 'Проект'\n getItem = (item, items) ->\n if ",
"end": 350,
"score": 0.9185399413108826,
"start": 349,
"tag": "NAME",
"value": "П"
}
] | old/storage.coffee | i-v-s/sumulta | 0 | this.pd = (o, d) ->
o._der ? o._der.push d : (o._der = [d])
this.rfa = (a, v) ->
o = 0
for t in a
a[o++] = t if t isnt v
a.length = o
Storage = ->
data =
sheets: [{name:"Новый лист", items:[]}]
this.data = data
this.active = data.sheets[0].items
data.active = 0;
this.ctors = {}
this.name = 'Проект'
getItem = (item, items) ->
if item.toJSON?
return item.toJSON (o) ->
return o.getId() if o.getId?
items.indexOf(o);
result = _: item.ctor
result[name] = field for own name, field of item
if item.dep?
for dep in item.dep
result[dep] =
if item.getId?
item.getId items
else items.indexOf item
result
getSheet = (sheet) ->
result = {}
for name, field of sheet
result[name] =
if name is 'items'
getItem item, field for item in field
else field
result
this.getJSON = ->
result = {}
for own name, block of data
result[name] =
if name is 'sheets'
getSheet sheet for sheet in block
else block
JSON.stringify result, (key, value) ->
return value if key is '_'
c = key[0]
if c is '_' or c is '$'
undefined
else value
this.putJSON = (json) ->
this.data = data = JSON.parse json
data.active = 0 if !data.active?
this.active = data.sheets[data.active].items
ctors = this.ctors
for sheet in data.sheets
for item in sheet.items
r = new ctors[item._]
for x, prop in item
r[x] = prop if x isnt '_'
for d in r.dep if r.dep?
this
###
return JSON.stringify(data, function(key, value)
{
if((key !== "_" && key[0] === '_') || key[0] === '$') return undefined;
if(typeof value === "object" && value.ctor)
{
var r = {_:value.ctor};
for(var x in value) if(value.hasOwnProperty(x) && typeof value[x] !== "function")
r[x] = value[x];
var dep = value.dep;
for(var x in dep)
{
var p = dep[x];
if(r[p] instanceof Array)
{
var s = r[p], d = [];
for(var y in s) d[y] = getId(s[y]);
r[p] = d;
}
else r[p] = getId(r[p]);
}
return r;
}
return value;
});
};
###
window.storage = new Storage()
| 69852 | this.pd = (o, d) ->
o._der ? o._der.push d : (o._der = [d])
this.rfa = (a, v) ->
o = 0
for t in a
a[o++] = t if t isnt v
a.length = o
Storage = ->
data =
sheets: [{name:"Новый лист", items:[]}]
this.data = data
this.active = data.sheets[0].items
data.active = 0;
this.ctors = {}
this.name = '<NAME>роект'
getItem = (item, items) ->
if item.toJSON?
return item.toJSON (o) ->
return o.getId() if o.getId?
items.indexOf(o);
result = _: item.ctor
result[name] = field for own name, field of item
if item.dep?
for dep in item.dep
result[dep] =
if item.getId?
item.getId items
else items.indexOf item
result
getSheet = (sheet) ->
result = {}
for name, field of sheet
result[name] =
if name is 'items'
getItem item, field for item in field
else field
result
this.getJSON = ->
result = {}
for own name, block of data
result[name] =
if name is 'sheets'
getSheet sheet for sheet in block
else block
JSON.stringify result, (key, value) ->
return value if key is '_'
c = key[0]
if c is '_' or c is '$'
undefined
else value
this.putJSON = (json) ->
this.data = data = JSON.parse json
data.active = 0 if !data.active?
this.active = data.sheets[data.active].items
ctors = this.ctors
for sheet in data.sheets
for item in sheet.items
r = new ctors[item._]
for x, prop in item
r[x] = prop if x isnt '_'
for d in r.dep if r.dep?
this
###
return JSON.stringify(data, function(key, value)
{
if((key !== "_" && key[0] === '_') || key[0] === '$') return undefined;
if(typeof value === "object" && value.ctor)
{
var r = {_:value.ctor};
for(var x in value) if(value.hasOwnProperty(x) && typeof value[x] !== "function")
r[x] = value[x];
var dep = value.dep;
for(var x in dep)
{
var p = dep[x];
if(r[p] instanceof Array)
{
var s = r[p], d = [];
for(var y in s) d[y] = getId(s[y]);
r[p] = d;
}
else r[p] = getId(r[p]);
}
return r;
}
return value;
});
};
###
window.storage = new Storage()
| true | this.pd = (o, d) ->
o._der ? o._der.push d : (o._der = [d])
this.rfa = (a, v) ->
o = 0
for t in a
a[o++] = t if t isnt v
a.length = o
Storage = ->
data =
sheets: [{name:"Новый лист", items:[]}]
this.data = data
this.active = data.sheets[0].items
data.active = 0;
this.ctors = {}
this.name = 'PI:NAME:<NAME>END_PIроект'
getItem = (item, items) ->
if item.toJSON?
return item.toJSON (o) ->
return o.getId() if o.getId?
items.indexOf(o);
result = _: item.ctor
result[name] = field for own name, field of item
if item.dep?
for dep in item.dep
result[dep] =
if item.getId?
item.getId items
else items.indexOf item
result
getSheet = (sheet) ->
result = {}
for name, field of sheet
result[name] =
if name is 'items'
getItem item, field for item in field
else field
result
this.getJSON = ->
result = {}
for own name, block of data
result[name] =
if name is 'sheets'
getSheet sheet for sheet in block
else block
JSON.stringify result, (key, value) ->
return value if key is '_'
c = key[0]
if c is '_' or c is '$'
undefined
else value
this.putJSON = (json) ->
this.data = data = JSON.parse json
data.active = 0 if !data.active?
this.active = data.sheets[data.active].items
ctors = this.ctors
for sheet in data.sheets
for item in sheet.items
r = new ctors[item._]
for x, prop in item
r[x] = prop if x isnt '_'
for d in r.dep if r.dep?
this
###
return JSON.stringify(data, function(key, value)
{
if((key !== "_" && key[0] === '_') || key[0] === '$') return undefined;
if(typeof value === "object" && value.ctor)
{
var r = {_:value.ctor};
for(var x in value) if(value.hasOwnProperty(x) && typeof value[x] !== "function")
r[x] = value[x];
var dep = value.dep;
for(var x in dep)
{
var p = dep[x];
if(r[p] instanceof Array)
{
var s = r[p], d = [];
for(var y in s) d[y] = getId(s[y]);
r[p] = d;
}
else r[p] = getId(r[p]);
}
return r;
}
return value;
});
};
###
window.storage = new Storage()
|
[
{
"context": "# Mark\n# ===============================================",
"end": 6,
"score": 0.9974355101585388,
"start": 2,
"tag": "NAME",
"value": "Mark"
}
] | src/formatter/transform/subscript.coffee | alinex/node-report | 1 | # Mark
# =================================================
chalk = require 'chalk'
# Transformer rules
#
# @type {Object<Transformer>} rules to set output text in token
module.exports =
md:
format: 'md'
type: 'subscript'
fn: (num, token) -> token.out = "~"
html:
format: 'html'
type: 'subscript'
fn: (num, token) ->
token.out = switch token.nesting
when 1 then "<sub#{@htmlAttribs token}>"
when -1 then "</sub>"
else "<sub></sub>"
| 178706 | # <NAME>
# =================================================
chalk = require 'chalk'
# Transformer rules
#
# @type {Object<Transformer>} rules to set output text in token
module.exports =
md:
format: 'md'
type: 'subscript'
fn: (num, token) -> token.out = "~"
html:
format: 'html'
type: 'subscript'
fn: (num, token) ->
token.out = switch token.nesting
when 1 then "<sub#{@htmlAttribs token}>"
when -1 then "</sub>"
else "<sub></sub>"
| true | # PI:NAME:<NAME>END_PI
# =================================================
chalk = require 'chalk'
# Transformer rules
#
# @type {Object<Transformer>} rules to set output text in token
module.exports =
md:
format: 'md'
type: 'subscript'
fn: (num, token) -> token.out = "~"
html:
format: 'html'
type: 'subscript'
fn: (num, token) ->
token.out = switch token.nesting
when 1 then "<sub#{@htmlAttribs token}>"
when -1 then "</sub>"
else "<sub></sub>"
|
[
{
"context": "terPhone: '(495) 9210326'\n importerEmail: 'np@newproducts.ru'\n\n exportDepartment: 'Відділ експорту'\n ",
"end": 789,
"score": 0.9999281764030457,
"start": 772,
"tag": "EMAIL",
"value": "np@newproducts.ru"
},
{
"context": "partment: 'Відділ експорту'\n exportEmail: 'korniyuk@newproducts.ua'\n exportPhone: '+38 (067) 5484945'\n\n sh",
"end": 881,
"score": 0.9999284744262695,
"start": 858,
"tag": "EMAIL",
"value": "korniyuk@newproducts.ua"
}
] | locale/ua.coffee | winnlab/Polpharma | 0 | module.exports =
checkAge: 'BAM БІЛЬШЕ 18 РОКІВ?'
yes: 'Так'
no: 'Ні'
healthWarn: 'НАДМІРНЕ СПОЖИВАННЯ АЛКОГОЛЮ ШКОДИТЬ ВАШОМУ ЗДОРОВ\'Ю'
consume: 'СПОЖИВАЙ <span class="clearfix"></span> РОЗУМНО'
allCocktails: 'Всі коктейлі'
bottle: 'Пляшка'
can: 'Банка'
menu: 'Меню'
close: 'Закрити'
contacts:
contacts: 'Контакти'
mainOffice: 'Головний офіс'
postAddress: '01601, Київ'
address: 'Спортивна пл, 3'
phone: '044 502 99 00'
importerInRF: 'Імпортер в РФ'
novyeProducty: '"Нові продукти"'
importerPlacement: 'Російська федерація, 107078, Москва'
importerAddress: 'Нова Басманна 9/2-4, 6,'
importerPhone: '(495) 9210326'
importerEmail: 'np@newproducts.ru'
exportDepartment: 'Відділ експорту'
exportEmail: 'korniyuk@newproducts.ua'
exportPhone: '+38 (067) 5484945'
shakeit:
share: 'поделись'
moment: 'моментом'
download: 'скачай'
ringtone: 'рингтон'
newPodcast: 'новый подкаст'
by: 'от'
allPodcasts: 'Всі подкасти'
back: 'Назад'
| 167730 | module.exports =
checkAge: 'BAM БІЛЬШЕ 18 РОКІВ?'
yes: 'Так'
no: 'Ні'
healthWarn: 'НАДМІРНЕ СПОЖИВАННЯ АЛКОГОЛЮ ШКОДИТЬ ВАШОМУ ЗДОРОВ\'Ю'
consume: 'СПОЖИВАЙ <span class="clearfix"></span> РОЗУМНО'
allCocktails: 'Всі коктейлі'
bottle: 'Пляшка'
can: 'Банка'
menu: 'Меню'
close: 'Закрити'
contacts:
contacts: 'Контакти'
mainOffice: 'Головний офіс'
postAddress: '01601, Київ'
address: 'Спортивна пл, 3'
phone: '044 502 99 00'
importerInRF: 'Імпортер в РФ'
novyeProducty: '"Нові продукти"'
importerPlacement: 'Російська федерація, 107078, Москва'
importerAddress: 'Нова Басманна 9/2-4, 6,'
importerPhone: '(495) 9210326'
importerEmail: '<EMAIL>'
exportDepartment: 'Відділ експорту'
exportEmail: '<EMAIL>'
exportPhone: '+38 (067) 5484945'
shakeit:
share: 'поделись'
moment: 'моментом'
download: 'скачай'
ringtone: 'рингтон'
newPodcast: 'новый подкаст'
by: 'от'
allPodcasts: 'Всі подкасти'
back: 'Назад'
| true | module.exports =
checkAge: 'BAM БІЛЬШЕ 18 РОКІВ?'
yes: 'Так'
no: 'Ні'
healthWarn: 'НАДМІРНЕ СПОЖИВАННЯ АЛКОГОЛЮ ШКОДИТЬ ВАШОМУ ЗДОРОВ\'Ю'
consume: 'СПОЖИВАЙ <span class="clearfix"></span> РОЗУМНО'
allCocktails: 'Всі коктейлі'
bottle: 'Пляшка'
can: 'Банка'
menu: 'Меню'
close: 'Закрити'
contacts:
contacts: 'Контакти'
mainOffice: 'Головний офіс'
postAddress: '01601, Київ'
address: 'Спортивна пл, 3'
phone: '044 502 99 00'
importerInRF: 'Імпортер в РФ'
novyeProducty: '"Нові продукти"'
importerPlacement: 'Російська федерація, 107078, Москва'
importerAddress: 'Нова Басманна 9/2-4, 6,'
importerPhone: '(495) 9210326'
importerEmail: 'PI:EMAIL:<EMAIL>END_PI'
exportDepartment: 'Відділ експорту'
exportEmail: 'PI:EMAIL:<EMAIL>END_PI'
exportPhone: '+38 (067) 5484945'
shakeit:
share: 'поделись'
moment: 'моментом'
download: 'скачай'
ringtone: 'рингтон'
newPodcast: 'новый подкаст'
by: 'от'
allPodcasts: 'Всі подкасти'
back: 'Назад'
|
[
{
"context": "GE: \"best commit ever\",\n COMMIT_INFO_EMAIL: \"user@company.com\",\n COMMIT_INFO_AUTHOR: \"Agent Smith\",\n ",
"end": 1496,
"score": 0.9999273419380188,
"start": 1480,
"tag": "EMAIL",
"value": "user@company.com"
},
{
"context": "L: \"user@company.com\",\n COMMIT_INFO_AUTHOR: \"Agent Smith\",\n COMMIT_INFO_SHA: \"0123456\",\n C",
"end": 1531,
"score": 0.8450520038604736,
"start": 1526,
"tag": "USERNAME",
"value": "Agent"
},
{
"context": "ser@company.com\",\n COMMIT_INFO_AUTHOR: \"Agent Smith\",\n COMMIT_INFO_SHA: \"0123456\",\n COMMIT_",
"end": 1537,
"score": 0.5295020341873169,
"start": 1532,
"tag": "NAME",
"value": "Smith"
},
{
"context": " message: \"buildKiteMessage\"\n authorName: \"buildKiteBuildCreator\"\n authorEmail: \"buildKiteCreatorEmail\"\n ",
"end": 6726,
"score": 0.9974724054336548,
"start": 6705,
"tag": "USERNAME",
"value": "buildKiteBuildCreator"
},
{
"context": "ME: \"circlePrReponame\"\n CIRCLE_PR_USERNAME: \"circlePrUsername\"\n CIRCLE_COMPARE_URL: \"circleCompareUrl\"\n ",
"end": 7543,
"score": 0.9995483756065369,
"start": 7527,
"tag": "USERNAME",
"value": "circlePrUsername"
},
{
"context": "LE_BRANCH: \"circleBranch\"\n CIRCLE_USERNAME: \"circleUsername\"\n }, {clear: true})\n\n expectsName(\"circle\")",
"end": 7878,
"score": 0.9996198415756226,
"start": 7864,
"tag": "USERNAME",
"value": "circleUsername"
},
{
"context": "name: \"circlePrReponame\"\n circlePrUsername: \"circlePrUsername\"\n circleCompareUrl: \"circleCompareUrl\"\n ",
"end": 8181,
"score": 0.9996283650398254,
"start": 8165,
"tag": "USERNAME",
"value": "circlePrUsername"
},
{
"context": "\"\n branch: \"circleBranch\"\n authorName: \"circleUsername\"\n })\n\n it \"codeshipBasic\", ->\n resetEnv = ",
"end": 8518,
"score": 0.9995903968811035,
"start": 8504,
"tag": "USERNAME",
"value": "circleUsername"
},
{
"context": " message: \"ciCommitMessage\"\n authorName: \"ciCommitterName\"\n authorEmail: \"ciCommitterEmail\"\n })\n\n ",
"end": 9458,
"score": 0.9565836191177368,
"start": 9443,
"tag": "USERNAME",
"value": "ciCommitterName"
},
{
"context": "SAGE: \"ciCommitMessage\"\n CI_COMMITTER_NAME: \"ciCommitterName\"\n CI_COMMITTER_EMAIL: \"ciCommitterEmail\"\n ",
"end": 9828,
"score": 0.7833893299102783,
"start": 9813,
"tag": "USERNAME",
"value": "ciCommitterName"
},
{
"context": " message: \"ciCommitMessage\"\n authorName: \"ciCommitterName\"\n authorEmail: \"ciCommitterEmail\"\n })\n\n ",
"end": 10193,
"score": 0.9175347685813904,
"start": 10178,
"tag": "USERNAME",
"value": "ciCommitterName"
},
{
"context": " \"droneCommitMessage\"\n DRONE_COMMIT_AUTHOR: \"droneCommitAuthor\"\n DRONE_COMMIT_AUTHOR_EMAIL: \"droneCom",
"end": 10655,
"score": 0.6059058904647827,
"start": 10644,
"tag": "USERNAME",
"value": "droneCommit"
},
{
"context": " message: \"droneCommitMessage\"\n authorName: \"droneCommitAuthor\"\n authorEmail: \"droneCommitAuthorEmail\"\n ",
"end": 11165,
"score": 0.9825458526611328,
"start": 11148,
"tag": "USERNAME",
"value": "droneCommitAuthor"
},
{
"context": "SSAGE: \"ciCommitMessage\"\n GITLAB_USER_NAME: \"gitlabUserName\"\n GITLAB_USER_EMAIL: \"gitlabUserEmail\"\n }",
"end": 11896,
"score": 0.9988779425621033,
"start": 11882,
"tag": "USERNAME",
"value": "gitlabUserName"
},
{
"context": "_NAME: \"gitlabUserName\"\n GITLAB_USER_EMAIL: \"gitlabUserEmail\"\n }, {clear: true})\n\n expectsName(\"gitlab\")",
"end": 11939,
"score": 0.7435994148254395,
"start": 11924,
"tag": "USERNAME",
"value": "gitlabUserEmail"
},
{
"context": " message: \"ciCommitMessage\"\n authorName: \"gitlabUserName\"\n authorEmail: \"gitlabUserEmail\"\n })\n\n ",
"end": 12502,
"score": 0.9991155862808228,
"start": 12488,
"tag": "USERNAME",
"value": "gitlabUserName"
},
{
"context": " authorName: \"gitlabUserName\"\n authorEmail: \"gitlabUserEmail\"\n })\n\n resetEnv = mockedEnv({\n CI",
"end": 12534,
"score": 0.7715842723846436,
"start": 12524,
"tag": "USERNAME",
"value": "gitlabUser"
},
{
"context": "e: \"gitlabUserName\"\n authorEmail: \"gitlabUserEmail\"\n })\n\n resetEnv = mockedEnv({\n CI_SERV",
"end": 12539,
"score": 0.4735736846923828,
"start": 12534,
"tag": "PASSWORD",
"value": "Email"
},
{
"context": " message: \"commitMessage\"\n authorName: \"committer\"\n })\n\n it \"snap\", ->\n resetEnv = mockedEnv",
"end": 18403,
"score": 0.787161111831665,
"start": 18394,
"tag": "USERNAME",
"value": "committer"
},
{
"context": "SAGE: \"message\"\n BUILD_SOURCEVERSIONAUTHOR: \"name\"\n BUILD_REQUESTEDFOREMAIL: \"email\"\n }, {c",
"end": 19286,
"score": 0.8287394642829895,
"start": 19282,
"tag": "USERNAME",
"value": "name"
},
{
"context": "anch\"\n message: \"message\"\n authorName: \"name\"\n authorEmail: \"email\"\n })\n\n it \"teamfou",
"end": 19674,
"score": 0.8867191672325134,
"start": 19670,
"tag": "USERNAME",
"value": "name"
},
{
"context": "SAGE: \"message\"\n BUILD_SOURCEVERSIONAUTHOR: \"name\"\n }, {clear: true})\n\n expectsName(\"teamfoun",
"end": 20104,
"score": 0.861004650592804,
"start": 20100,
"tag": "USERNAME",
"value": "name"
},
{
"context": "anch\"\n message: \"message\"\n authorName: \"name\"\n })\n\n it \"travis\", ->\n resetEnv = mockedE",
"end": 20415,
"score": 0.9951017498970032,
"start": 20411,
"tag": "USERNAME",
"value": "name"
}
] | packages/server/test/unit/ci_provider_spec.coffee | smiileTeam/cypress | 0 | R = require("ramda")
mockedEnv = require("mocked-env")
require("../spec_helper")
ciProvider = require("#{root}lib/util/ci_provider")
expectsName = (name) ->
expect(ciProvider.provider(), "CI providers detected name").to.eq(name)
expectsCiParams = (params) ->
expect(ciProvider.ciParams(), "CI providers detected CI params").to.deep.eq(params)
expectsCommitParams = (params) ->
expect(ciProvider.commitParams(), "CI providers detected commit params").to.deep.eq(params)
expectsCommitDefaults = (existing, expected) ->
expect(expected).to.be.an("object")
expect(ciProvider.commitDefaults(existing), "CI providers default git params").to.deep.eq(expected)
describe "lib/util/ci_provider", ->
resetEnv = null
afterEach ->
# we need to reset environment
# to avoid affecting tests in other suites
resetEnv?()
it "null when unknown", ->
resetEnv = mockedEnv({}, {clear: true})
expectsName(null)
expectsCiParams(null)
expectsCommitParams(null)
it "does not extract from commit environment variables yet", ->
# see fallback environment variables
# https://github.com/cypress-io/commit-info#fallback-environment-variables
# BUT those defaults are NOT used by "ci_provider"
# instead they are used in the "record" module
# this test just confirms that these defaults are not considered
env = {
COMMIT_INFO_BRANCH: "my-branch-221",
COMMIT_INFO_MESSAGE: "best commit ever",
COMMIT_INFO_EMAIL: "user@company.com",
COMMIT_INFO_AUTHOR: "Agent Smith",
COMMIT_INFO_SHA: "0123456",
COMMIT_INFO_REMOTE: "remote repo"
}
resetEnv = mockedEnv(env, {clear: true})
expectsName(null) # we don't know CI
expectsCiParams(null) # we don't know CI params
expectsCommitParams(null) # we don't know CI-specific params
it "appveyor", ->
resetEnv = mockedEnv({
APPVEYOR: "true"
APPVEYOR_JOB_ID: "appveyorJobId2"
APPVEYOR_ACCOUNT_NAME: "appveyorAccountName"
APPVEYOR_PROJECT_SLUG: "appveyorProjectSlug"
APPVEYOR_BUILD_VERSION: "appveyorBuildVersion"
APPVEYOR_BUILD_NUMBER: "appveyorBuildNumber"
APPVEYOR_PULL_REQUEST_NUMBER: "appveyorPullRequestNumber"
APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH: "appveyorPullRequestHeadRepoBranch"
APPVEYOR_REPO_COMMIT: "repoCommit"
APPVEYOR_REPO_COMMIT_MESSAGE: "repoCommitMessage"
APPVEYOR_REPO_BRANCH: "repoBranch"
APPVEYOR_REPO_COMMIT_AUTHOR: "repoCommitAuthor"
APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL: "repoCommitAuthorEmail"
}, {clear: true})
expectsName("appveyor")
expectsCiParams({
appveyorJobId: "appveyorJobId2"
appveyorAccountName: "appveyorAccountName"
appveyorProjectSlug: "appveyorProjectSlug"
appveyorBuildNumber: "appveyorBuildNumber"
appveyorBuildVersion: "appveyorBuildVersion"
appveyorPullRequestNumber: "appveyorPullRequestNumber"
appveyorPullRequestHeadRepoBranch: "appveyorPullRequestHeadRepoBranch"
})
expectsCommitParams({
sha: "repoCommit"
branch: "appveyorPullRequestHeadRepoBranch"
message: "repoCommitMessage"
authorName: "repoCommitAuthor"
authorEmail: "repoCommitAuthorEmail"
})
resetEnv()
resetEnv = mockedEnv({
APPVEYOR: "true"
APPVEYOR_REPO_COMMIT_MESSAGE: "repoCommitMessage"
APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED: "repoCommitMessageExtended"
}, {clear: true})
expectsCommitParams({
message: "repoCommitMessage\nrepoCommitMessageExtended"
})
it "bamboo", ->
resetEnv = mockedEnv({
"bamboo.buildNumber": "123"
"bamboo.resultsUrl": "bamboo.resultsUrl"
"bamboo.buildResultsUrl": "bamboo.buildResultsUrl"
"bamboo.planRepository.repositoryUrl": "bamboo.planRepository.repositoryUrl"
"bamboo.planRepository.branch": "bamboo.planRepository.branch"
}, {clear: true})
expectsName("bamboo")
expectsCiParams({
bambooResultsUrl: "bamboo.resultsUrl"
bambooBuildNumber: "123"
bambooBuildResultsUrl: "bamboo.buildResultsUrl"
bambooPlanRepositoryRepositoryUrl: "bamboo.planRepository.repositoryUrl"
})
expectsCommitParams({
branch: "bamboo.planRepository.branch"
})
it "bitbucket", ->
resetEnv = mockedEnv({
CI: "1"
# build information
BITBUCKET_BUILD_NUMBER: "bitbucketBuildNumber"
BITBUCKET_REPO_OWNER: "bitbucketRepoOwner"
BITBUCKET_REPO_SLUG: "bitbucketRepoSlug"
# git information
BITBUCKET_COMMIT: "bitbucketCommit"
BITBUCKET_BRANCH: "bitbucketBranch"
}, {clear: true})
expectsName("bitbucket")
expectsCiParams({
bitbucketBuildNumber: "bitbucketBuildNumber"
bitbucketRepoOwner: "bitbucketRepoOwner"
bitbucketRepoSlug: "bitbucketRepoSlug"
})
expectsCommitParams({
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
expectsCommitDefaults({
sha: null
branch: "gitFoundBranch"
}, {
sha: "bitbucketCommit"
branch: "gitFoundBranch"
})
expectsCommitDefaults({
sha: undefined
branch: ""
}, {
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
it "buildkite", ->
resetEnv = mockedEnv({
BUILDKITE: "true"
BUILDKITE_REPO: "buildkiteRepo"
BUILDKITE_JOB_ID: "buildkiteJobId"
BUILDKITE_SOURCE: "buildkiteSource"
BUILDKITE_BUILD_ID: "buildkiteBuildId"
BUILDKITE_BUILD_URL: "buildkiteBuildUrl"
BUILDKITE_BUILD_NUMBER: "buildkiteBuildNumber"
BUILDKITE_PULL_REQUEST: "buildkitePullRequest"
BUILDKITE_PULL_REQUEST_REPO: "buildkitePullRequestRepo"
BUILDKITE_PULL_REQUEST_BASE_BRANCH: "buildkitePullRequestBaseBranch"
BUILDKITE_COMMIT: "buildKiteCommit"
BUILDKITE_BRANCH: "buildKiteBranch"
BUILDKITE_MESSAGE: "buildKiteMessage"
BUILDKITE_BUILD_CREATOR: "buildKiteBuildCreator"
BUILDKITE_BUILD_CREATOR_EMAIL: "buildKiteCreatorEmail"
BUILDKITE_PIPELINE_DEFAULT_BRANCH: "buildkitePipelineDefaultBranch"
}, {clear: true})
expectsName("buildkite")
expectsCiParams({
buildkiteRepo: "buildkiteRepo"
buildkiteJobId: "buildkiteJobId"
buildkiteSource: "buildkiteSource"
buildkiteBuildId: "buildkiteBuildId"
buildkiteBuildUrl: "buildkiteBuildUrl"
buildkiteBuildNumber: "buildkiteBuildNumber"
buildkitePullRequest: "buildkitePullRequest"
buildkitePullRequestRepo: "buildkitePullRequestRepo"
buildkitePullRequestBaseBranch: "buildkitePullRequestBaseBranch"
})
expectsCommitParams({
sha: "buildKiteCommit"
branch: "buildKiteBranch"
message: "buildKiteMessage"
authorName: "buildKiteBuildCreator"
authorEmail: "buildKiteCreatorEmail"
remoteOrigin: "buildkiteRepo"
defaultBranch: "buildkitePipelineDefaultBranch"
})
# in this test only interested in branch and sha for example
expectsCommitDefaults({
sha: null,
branch: "gitFoundBranch"
}, {
sha: "buildKiteCommit",
branch: "gitFoundBranch"
})
expectsCommitDefaults({
sha: undefined,
branch: ""
}, {
sha: "buildKiteCommit",
branch: "buildKiteBranch"
})
it "circle", ->
resetEnv = mockedEnv({
CIRCLECI: "true"
CIRCLE_JOB: "circleJob"
CIRCLE_BUILD_NUM: "circleBuildNum"
CIRCLE_BUILD_URL: "circleBuildUrl"
CIRCLE_PR_NUMBER: "circlePrNumber"
CIRCLE_PR_REPONAME: "circlePrReponame"
CIRCLE_PR_USERNAME: "circlePrUsername"
CIRCLE_COMPARE_URL: "circleCompareUrl"
CIRCLE_WORKFLOW_ID: "circleWorkflowId"
CIRCLE_PULL_REQUEST: "circlePullRequest"
CIRCLE_REPOSITORY_URL: "circleRepositoryUrl"
CI_PULL_REQUEST: "ciPullRequest"
CIRCLE_SHA1: "circleSha"
CIRCLE_BRANCH: "circleBranch"
CIRCLE_USERNAME: "circleUsername"
}, {clear: true})
expectsName("circle")
expectsCiParams({
circleJob: "circleJob"
circleBuildNum: "circleBuildNum"
circleBuildUrl: "circleBuildUrl"
circlePrNumber: "circlePrNumber"
circlePrReponame: "circlePrReponame"
circlePrUsername: "circlePrUsername"
circleCompareUrl: "circleCompareUrl"
circleWorkflowId: "circleWorkflowId"
circlePullRequest: "circlePullRequest"
circleRepositoryUrl: "circleRepositoryUrl"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "circleSha"
branch: "circleBranch"
authorName: "circleUsername"
})
it "codeshipBasic", ->
resetEnv = mockedEnv({
CODESHIP: "TRUE"
CI_NAME: "codeship"
CI_BUILD_ID: "ciBuildId"
CI_REPO_NAME: "ciRepoName"
CI_BUILD_URL: "ciBuildUrl"
CI_PROJECT_ID: "ciProjectId"
CI_BUILD_NUMBER: "ciBuildNumber"
CI_PULL_REQUEST: "ciPullRequest"
CI_COMMIT_ID: "ciCommitId"
CI_BRANCH: "ciBranch"
CI_COMMIT_MESSAGE: "ciCommitMessage"
CI_COMMITTER_NAME: "ciCommitterName"
CI_COMMITTER_EMAIL: "ciCommitterEmail"
}, {clear: true})
expectsName("codeshipBasic")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciBuildUrl: "ciBuildUrl"
ciProjectId: "ciProjectId"
ciBuildNumber: "ciBuildNumber"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "codeshipPro", ->
resetEnv = mockedEnv({
CI_NAME: "codeship"
CI_BUILD_ID: "ciBuildId"
CI_REPO_NAME: "ciRepoName"
CI_PROJECT_ID: "ciProjectId"
CI_COMMIT_ID: "ciCommitId"
CI_BRANCH: "ciBranch"
CI_COMMIT_MESSAGE: "ciCommitMessage"
CI_COMMITTER_NAME: "ciCommitterName"
CI_COMMITTER_EMAIL: "ciCommitterEmail"
}, {clear: true})
expectsName("codeshipPro")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciProjectId: "ciProjectId"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "drone", ->
resetEnv = mockedEnv({
DRONE: "true"
DRONE_JOB_NUMBER: "droneJobNumber"
DRONE_BUILD_LINK: "droneBuildLink"
DRONE_BUILD_NUMBER: "droneBuildNumber"
DRONE_PULL_REQUEST: "dronePullRequest"
DRONE_COMMIT_SHA: "droneCommitSha"
DRONE_COMMIT_BRANCH: "droneCommitBranch"
DRONE_COMMIT_MESSAGE: "droneCommitMessage"
DRONE_COMMIT_AUTHOR: "droneCommitAuthor"
DRONE_COMMIT_AUTHOR_EMAIL: "droneCommitAuthorEmail"
DRONE_REPO_BRANCH: "droneRepoBranch"
}, {clear: true})
expectsName("drone")
expectsCiParams({
droneJobNumber: "droneJobNumber"
droneBuildLink: "droneBuildLink"
droneBuildNumber: "droneBuildNumber"
dronePullRequest: "dronePullRequest"
})
expectsCommitParams({
sha: "droneCommitSha"
branch: "droneCommitBranch"
message: "droneCommitMessage"
authorName: "droneCommitAuthor"
authorEmail: "droneCommitAuthorEmail"
defaultBranch: "droneRepoBranch"
})
it "gitlab", ->
resetEnv = mockedEnv({
GITLAB_CI: "true"
# Gitlab has job id and build id as synonyms
CI_BUILD_ID: "ciJobId"
CI_JOB_ID: "ciJobId"
CI_JOB_URL: "ciJobUrl"
CI_PIPELINE_ID: "ciPipelineId"
CI_PIPELINE_URL: "ciPipelineUrl"
GITLAB_HOST: "gitlabHost"
CI_PROJECT_ID: "ciProjectId"
CI_PROJECT_URL: "ciProjectUrl"
CI_REPOSITORY_URL: "ciRepositoryUrl"
CI_ENVIRONMENT_URL: "ciEnvironmentUrl"
CI_COMMIT_SHA: "ciCommitSha"
CI_COMMIT_REF_NAME: "ciCommitRefName"
CI_COMMIT_MESSAGE: "ciCommitMessage"
GITLAB_USER_NAME: "gitlabUserName"
GITLAB_USER_EMAIL: "gitlabUserEmail"
}, {clear: true})
expectsName("gitlab")
expectsCiParams({
ciJobId: "ciJobId"
ciJobUrl: "ciJobUrl"
ciBuildId: "ciJobId"
ciPipelineId: "ciPipelineId"
ciPipelineUrl: "ciPipelineUrl"
gitlabHost: "gitlabHost"
ciProjectId: "ciProjectId"
ciProjectUrl: "ciProjectUrl"
ciRepositoryUrl: "ciRepositoryUrl"
ciEnvironmentUrl: "ciEnvironmentUrl"
})
expectsCommitParams({
sha: "ciCommitSha"
branch: "ciCommitRefName"
message: "ciCommitMessage"
authorName: "gitlabUserName"
authorEmail: "gitlabUserEmail"
})
resetEnv = mockedEnv({
CI_SERVER_NAME: "GitLab CI"
}, {clear: true})
expectsName("gitlab")
resetEnv = mockedEnv({
CI_SERVER_NAME: "GitLab"
}, {clear: true})
expectsName("gitlab")
it "google cloud", ->
resetEnv = mockedEnv({
GCP_PROJECT: "123"
BUILD_ID: "buildId"
PROJECT_ID: "projectId"
COMMIT_SHA: "commitSha"
BRANCH_NAME: "branchName"
}, {clear: true})
expectsName("googleCloud")
expectsCiParams({
buildId: "buildId"
projectId: "projectId"
commitSha: "commitSha"
branchName: "branchName"
})
expectsCommitParams({
sha: "commitSha"
branch: "branchName"
})
resetEnv = mockedEnv({
GCLOUD_PROJECT: "123"
}, {clear: true})
expectsName("googleCloud")
resetEnv = mockedEnv({
GOOGLE_CLOUD_PROJECT: "123"
}, {clear: true})
expectsName("googleCloud")
it "jenkins", ->
resetEnv = mockedEnv({
JENKINS_URL: "true"
BUILD_ID: "buildId"
BUILD_URL: "buildUrl"
BUILD_NUMBER: "buildNumber"
ghprbPullId: "gbprbPullId"
GIT_COMMIT: "gitCommit"
GIT_BRANCH: "gitBranch"
}, {clear: true})
expectsName("jenkins")
expectsCiParams({
buildId: "buildId"
buildUrl: "buildUrl"
buildNumber: "buildNumber"
ghprbPullId: "gbprbPullId"
})
expectsCommitParams({
sha: "gitCommit"
branch: "gitBranch"
})
resetEnv = mockedEnv({
JENKINS_HOME: "/path/to/jenkins"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
JENKINS_VERSION: "1.2.3"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
HUDSON_HOME: "/path/to/jenkins"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
HUDSON_URL: "true"
}, {clear: true})
expectsName("jenkins")
it "semaphore", ->
resetEnv = mockedEnv({
SEMAPHORE: "true"
SEMAPHORE_BRANCH_ID: "semaphoreBranchId"
SEMAPHORE_BUILD_NUMBER: "semaphoreBuildNumber"
SEMAPHORE_CURRENT_JOB: "semaphoreCurrentJob"
SEMAPHORE_CURRENT_THREAD: "semaphoreCurrentThread"
SEMAPHORE_EXECUTABLE_UUID: "semaphoreExecutableUuid"
SEMAPHORE_JOB_COUNT: "semaphoreJobCount"
SEMAPHORE_JOB_UUID: "semaphoreJobUuid"
SEMAPHORE_PLATFORM: "semaphorePlatform"
SEMAPHORE_PROJECT_DIR: "semaphoreProjectDir"
SEMAPHORE_PROJECT_HASH_ID: "semaphoreProjectHashId"
SEMAPHORE_PROJECT_NAME: "semaphoreProjectName"
SEMAPHORE_PROJECT_UUID: "semaphoreProjectUuid"
SEMAPHORE_REPO_SLUG: "semaphoreRepoSlug"
SEMAPHORE_TRIGGER_SOURCE: "semaphoreTriggerSource"
PULL_REQUEST_NUMBER: "pullRequestNumber"
REVISION: "revision"
BRANCH_NAME: "branchName"
}, {clear: true})
expectsName("semaphore")
expectsCiParams({
pullRequestNumber: "pullRequestNumber"
semaphoreBranchId: "semaphoreBranchId"
semaphoreBuildNumber: "semaphoreBuildNumber"
semaphoreCurrentJob: "semaphoreCurrentJob"
semaphoreCurrentThread: "semaphoreCurrentThread"
semaphoreExecutableUuid: "semaphoreExecutableUuid"
semaphoreJobCount: "semaphoreJobCount"
semaphoreJobUuid: "semaphoreJobUuid"
semaphorePlatform: "semaphorePlatform"
semaphoreProjectDir: "semaphoreProjectDir"
semaphoreProjectHashId: "semaphoreProjectHashId"
semaphoreProjectName: "semaphoreProjectName"
semaphoreProjectUuid: "semaphoreProjectUuid"
semaphoreRepoSlug: "semaphoreRepoSlug"
semaphoreTriggerSource: "semaphoreTriggerSource"
})
expectsCommitParams({
sha: "revision"
branch: "branchName"
})
it "shippable", ->
resetEnv = mockedEnv({
SHIPPABLE: "true"
# build environment variables
SHIPPABLE_BUILD_ID: "buildId"
SHIPPABLE_BUILD_NUMBER: "buildNumber"
SHIPPABLE_COMMIT_RANGE: "commitRange"
SHIPPABLE_CONTAINER_NAME: "containerName"
SHIPPABLE_JOB_ID: "jobId"
SHIPPABLE_JOB_NUMBER: "jobNumber"
SHIPPABLE_REPO_SLUG: "repoSlug"
# additional information
IS_FORK: "isFork"
IS_GIT_TAG: "isGitTag"
IS_PRERELEASE: "isPrerelease"
IS_RELEASE: "isRelease"
REPOSITORY_URL: "repositoryUrl"
REPO_FULL_NAME: "repoFullName"
REPO_NAME: "repoName"
BUILD_URL: "buildUrl"
# pull request variables
BASE_BRANCH: "baseBranch"
HEAD_BRANCH: "headBranch"
IS_PULL_REQUEST: "isPullRequest"
PULL_REQUEST: "pullRequest"
PULL_REQUEST_BASE_BRANCH: "pullRequestBaseBranch"
PULL_REQUEST_REPO_FULL_NAME: "pullRequestRepoFullName"
# git information
COMMIT: "commit"
BRANCH: "branch"
COMMITTER: "committer"
COMMIT_MESSAGE: "commitMessage"
}, {clear: true})
expectsName("shippable")
expectsCiParams({
# build information
shippableBuildId: "buildId"
shippableBuildNumber: "buildNumber"
shippableCommitRange: "commitRange"
shippableContainerName: "containerName"
shippableJobId: "jobId"
shippableJobNumber: "jobNumber"
shippableRepoSlug: "repoSlug"
# additional information
isFork: "isFork"
isGitTag: "isGitTag"
isPrerelease: "isPrerelease"
isRelease: "isRelease"
repositoryUrl: "repositoryUrl"
repoFullName: "repoFullName"
repoName: "repoName"
buildUrl: "buildUrl"
# pull request information
baseBranch: "baseBranch"
headBranch: "headBranch"
isPullRequest: "isPullRequest"
pullRequest: "pullRequest"
pullRequestBaseBranch: "pullRequestBaseBranch"
pullRequestRepoFullName: "pullRequestRepoFullName"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "commitMessage"
authorName: "committer"
})
it "snap", ->
resetEnv = mockedEnv({
SNAP_CI: "true"
}, {clear: true})
expectsName("snap")
expectsCiParams(null)
expectsCommitParams(null)
it "teamcity", ->
resetEnv = mockedEnv({
TEAMCITY_VERSION: "true"
}, {clear: true})
expectsName("teamcity")
expectsCiParams(null)
expectsCommitParams(null)
it "azure", ->
resetEnv = mockedEnv({
# these two variables tell us it is Azure CI
TF_BUILD: "true"
AZURE_HTTP_USER_AGENT: "VSTS_5e0090d5-c5b9-4fab-8fd8-ce288e9fb666_build_2_0"
BUILD_BUILDID: "buildId"
BUILD_BUILDNUMBER: "buildNumber"
BUILD_CONTAINERID: "containerId"
BUILD_REPOSITORY_URI: "buildRepositoryUri"
BUILD_SOURCEVERSION: "commit"
BUILD_SOURCEBRANCHNAME: "branch"
BUILD_SOURCEVERSIONMESSAGE: "message"
BUILD_SOURCEVERSIONAUTHOR: "name"
BUILD_REQUESTEDFOREMAIL: "email"
}, {clear: true})
expectsName("azure")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
buildRepositoryUri: "buildRepositoryUri"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
authorEmail: "email"
})
it "teamfoundation", ->
resetEnv = mockedEnv({
TF_BUILD: "true"
TF_BUILD_BUILDNUMBER: "CIBuild_20130613.6"
BUILD_BUILDID: "buildId"
BUILD_BUILDNUMBER: "buildNumber"
BUILD_CONTAINERID: "containerId"
BUILD_SOURCEVERSION: "commit"
BUILD_SOURCEBRANCHNAME: "branch"
BUILD_SOURCEVERSIONMESSAGE: "message"
BUILD_SOURCEVERSIONAUTHOR: "name"
}, {clear: true})
expectsName("teamfoundation")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
})
it "travis", ->
resetEnv = mockedEnv({
TRAVIS: "true"
TRAVIS_JOB_ID: "travisJobId"
TRAVIS_BUILD_ID: "travisBuildId"
TRAVIS_REPO_SLUG: "travisRepoSlug"
TRAVIS_JOB_NUMBER: "travisJobNumber"
TRAVIS_EVENT_TYPE: "travisEventType"
TRAVIS_COMMIT_RANGE: "travisCommitRange"
TRAVIS_BUILD_NUMBER: "travisBuildNumber"
TRAVIS_PULL_REQUEST: "travisPullRequest"
TRAVIS_PULL_REQUEST_BRANCH: "travisPullRequestBranch"
TRAVIS_COMMIT: "travisCommit"
TRAVIS_BRANCH: "travisBranch"
TRAVIS_COMMIT_MESSAGE: "travisCommitMessage"
}, {clear: true})
expectsName("travis")
expectsCiParams({
travisJobId: "travisJobId"
travisBuildId: "travisBuildId"
travisRepoSlug: "travisRepoSlug"
travisJobNumber: "travisJobNumber"
travisEventType: "travisEventType"
travisCommitRange: "travisCommitRange"
travisBuildNumber: "travisBuildNumber"
travisPullRequest: "travisPullRequest"
travisPullRequestBranch: "travisPullRequestBranch"
})
expectsCommitParams({
sha: "travisCommit"
branch: "travisPullRequestBranch"
message: "travisCommitMessage"
})
resetEnv = mockedEnv({
TRAVIS: "true"
TRAVIS_BRANCH: "travisBranch"
}, {clear: true})
expectsCommitParams({
branch: "travisBranch"
})
it "wercker", ->
resetEnv = mockedEnv({
WERCKER: "true"
}, {clear: true})
expectsName("wercker")
expectsCiParams(null)
expectsCommitParams(null)
resetEnv = mockedEnv({
WERCKER_MAIN_PIPELINE_STARTED: "true"
}, {clear: true})
expectsName("wercker")
| 98025 | R = require("ramda")
mockedEnv = require("mocked-env")
require("../spec_helper")
ciProvider = require("#{root}lib/util/ci_provider")
expectsName = (name) ->
expect(ciProvider.provider(), "CI providers detected name").to.eq(name)
expectsCiParams = (params) ->
expect(ciProvider.ciParams(), "CI providers detected CI params").to.deep.eq(params)
expectsCommitParams = (params) ->
expect(ciProvider.commitParams(), "CI providers detected commit params").to.deep.eq(params)
expectsCommitDefaults = (existing, expected) ->
expect(expected).to.be.an("object")
expect(ciProvider.commitDefaults(existing), "CI providers default git params").to.deep.eq(expected)
describe "lib/util/ci_provider", ->
resetEnv = null
afterEach ->
# we need to reset environment
# to avoid affecting tests in other suites
resetEnv?()
it "null when unknown", ->
resetEnv = mockedEnv({}, {clear: true})
expectsName(null)
expectsCiParams(null)
expectsCommitParams(null)
it "does not extract from commit environment variables yet", ->
# see fallback environment variables
# https://github.com/cypress-io/commit-info#fallback-environment-variables
# BUT those defaults are NOT used by "ci_provider"
# instead they are used in the "record" module
# this test just confirms that these defaults are not considered
env = {
COMMIT_INFO_BRANCH: "my-branch-221",
COMMIT_INFO_MESSAGE: "best commit ever",
COMMIT_INFO_EMAIL: "<EMAIL>",
COMMIT_INFO_AUTHOR: "Agent <NAME>",
COMMIT_INFO_SHA: "0123456",
COMMIT_INFO_REMOTE: "remote repo"
}
resetEnv = mockedEnv(env, {clear: true})
expectsName(null) # we don't know CI
expectsCiParams(null) # we don't know CI params
expectsCommitParams(null) # we don't know CI-specific params
it "appveyor", ->
resetEnv = mockedEnv({
APPVEYOR: "true"
APPVEYOR_JOB_ID: "appveyorJobId2"
APPVEYOR_ACCOUNT_NAME: "appveyorAccountName"
APPVEYOR_PROJECT_SLUG: "appveyorProjectSlug"
APPVEYOR_BUILD_VERSION: "appveyorBuildVersion"
APPVEYOR_BUILD_NUMBER: "appveyorBuildNumber"
APPVEYOR_PULL_REQUEST_NUMBER: "appveyorPullRequestNumber"
APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH: "appveyorPullRequestHeadRepoBranch"
APPVEYOR_REPO_COMMIT: "repoCommit"
APPVEYOR_REPO_COMMIT_MESSAGE: "repoCommitMessage"
APPVEYOR_REPO_BRANCH: "repoBranch"
APPVEYOR_REPO_COMMIT_AUTHOR: "repoCommitAuthor"
APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL: "repoCommitAuthorEmail"
}, {clear: true})
expectsName("appveyor")
expectsCiParams({
appveyorJobId: "appveyorJobId2"
appveyorAccountName: "appveyorAccountName"
appveyorProjectSlug: "appveyorProjectSlug"
appveyorBuildNumber: "appveyorBuildNumber"
appveyorBuildVersion: "appveyorBuildVersion"
appveyorPullRequestNumber: "appveyorPullRequestNumber"
appveyorPullRequestHeadRepoBranch: "appveyorPullRequestHeadRepoBranch"
})
expectsCommitParams({
sha: "repoCommit"
branch: "appveyorPullRequestHeadRepoBranch"
message: "repoCommitMessage"
authorName: "repoCommitAuthor"
authorEmail: "repoCommitAuthorEmail"
})
resetEnv()
resetEnv = mockedEnv({
APPVEYOR: "true"
APPVEYOR_REPO_COMMIT_MESSAGE: "repoCommitMessage"
APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED: "repoCommitMessageExtended"
}, {clear: true})
expectsCommitParams({
message: "repoCommitMessage\nrepoCommitMessageExtended"
})
it "bamboo", ->
resetEnv = mockedEnv({
"bamboo.buildNumber": "123"
"bamboo.resultsUrl": "bamboo.resultsUrl"
"bamboo.buildResultsUrl": "bamboo.buildResultsUrl"
"bamboo.planRepository.repositoryUrl": "bamboo.planRepository.repositoryUrl"
"bamboo.planRepository.branch": "bamboo.planRepository.branch"
}, {clear: true})
expectsName("bamboo")
expectsCiParams({
bambooResultsUrl: "bamboo.resultsUrl"
bambooBuildNumber: "123"
bambooBuildResultsUrl: "bamboo.buildResultsUrl"
bambooPlanRepositoryRepositoryUrl: "bamboo.planRepository.repositoryUrl"
})
expectsCommitParams({
branch: "bamboo.planRepository.branch"
})
it "bitbucket", ->
resetEnv = mockedEnv({
CI: "1"
# build information
BITBUCKET_BUILD_NUMBER: "bitbucketBuildNumber"
BITBUCKET_REPO_OWNER: "bitbucketRepoOwner"
BITBUCKET_REPO_SLUG: "bitbucketRepoSlug"
# git information
BITBUCKET_COMMIT: "bitbucketCommit"
BITBUCKET_BRANCH: "bitbucketBranch"
}, {clear: true})
expectsName("bitbucket")
expectsCiParams({
bitbucketBuildNumber: "bitbucketBuildNumber"
bitbucketRepoOwner: "bitbucketRepoOwner"
bitbucketRepoSlug: "bitbucketRepoSlug"
})
expectsCommitParams({
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
expectsCommitDefaults({
sha: null
branch: "gitFoundBranch"
}, {
sha: "bitbucketCommit"
branch: "gitFoundBranch"
})
expectsCommitDefaults({
sha: undefined
branch: ""
}, {
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
it "buildkite", ->
resetEnv = mockedEnv({
BUILDKITE: "true"
BUILDKITE_REPO: "buildkiteRepo"
BUILDKITE_JOB_ID: "buildkiteJobId"
BUILDKITE_SOURCE: "buildkiteSource"
BUILDKITE_BUILD_ID: "buildkiteBuildId"
BUILDKITE_BUILD_URL: "buildkiteBuildUrl"
BUILDKITE_BUILD_NUMBER: "buildkiteBuildNumber"
BUILDKITE_PULL_REQUEST: "buildkitePullRequest"
BUILDKITE_PULL_REQUEST_REPO: "buildkitePullRequestRepo"
BUILDKITE_PULL_REQUEST_BASE_BRANCH: "buildkitePullRequestBaseBranch"
BUILDKITE_COMMIT: "buildKiteCommit"
BUILDKITE_BRANCH: "buildKiteBranch"
BUILDKITE_MESSAGE: "buildKiteMessage"
BUILDKITE_BUILD_CREATOR: "buildKiteBuildCreator"
BUILDKITE_BUILD_CREATOR_EMAIL: "buildKiteCreatorEmail"
BUILDKITE_PIPELINE_DEFAULT_BRANCH: "buildkitePipelineDefaultBranch"
}, {clear: true})
expectsName("buildkite")
expectsCiParams({
buildkiteRepo: "buildkiteRepo"
buildkiteJobId: "buildkiteJobId"
buildkiteSource: "buildkiteSource"
buildkiteBuildId: "buildkiteBuildId"
buildkiteBuildUrl: "buildkiteBuildUrl"
buildkiteBuildNumber: "buildkiteBuildNumber"
buildkitePullRequest: "buildkitePullRequest"
buildkitePullRequestRepo: "buildkitePullRequestRepo"
buildkitePullRequestBaseBranch: "buildkitePullRequestBaseBranch"
})
expectsCommitParams({
sha: "buildKiteCommit"
branch: "buildKiteBranch"
message: "buildKiteMessage"
authorName: "buildKiteBuildCreator"
authorEmail: "buildKiteCreatorEmail"
remoteOrigin: "buildkiteRepo"
defaultBranch: "buildkitePipelineDefaultBranch"
})
# in this test only interested in branch and sha for example
expectsCommitDefaults({
sha: null,
branch: "gitFoundBranch"
}, {
sha: "buildKiteCommit",
branch: "gitFoundBranch"
})
expectsCommitDefaults({
sha: undefined,
branch: ""
}, {
sha: "buildKiteCommit",
branch: "buildKiteBranch"
})
it "circle", ->
resetEnv = mockedEnv({
CIRCLECI: "true"
CIRCLE_JOB: "circleJob"
CIRCLE_BUILD_NUM: "circleBuildNum"
CIRCLE_BUILD_URL: "circleBuildUrl"
CIRCLE_PR_NUMBER: "circlePrNumber"
CIRCLE_PR_REPONAME: "circlePrReponame"
CIRCLE_PR_USERNAME: "circlePrUsername"
CIRCLE_COMPARE_URL: "circleCompareUrl"
CIRCLE_WORKFLOW_ID: "circleWorkflowId"
CIRCLE_PULL_REQUEST: "circlePullRequest"
CIRCLE_REPOSITORY_URL: "circleRepositoryUrl"
CI_PULL_REQUEST: "ciPullRequest"
CIRCLE_SHA1: "circleSha"
CIRCLE_BRANCH: "circleBranch"
CIRCLE_USERNAME: "circleUsername"
}, {clear: true})
expectsName("circle")
expectsCiParams({
circleJob: "circleJob"
circleBuildNum: "circleBuildNum"
circleBuildUrl: "circleBuildUrl"
circlePrNumber: "circlePrNumber"
circlePrReponame: "circlePrReponame"
circlePrUsername: "circlePrUsername"
circleCompareUrl: "circleCompareUrl"
circleWorkflowId: "circleWorkflowId"
circlePullRequest: "circlePullRequest"
circleRepositoryUrl: "circleRepositoryUrl"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "circleSha"
branch: "circleBranch"
authorName: "circleUsername"
})
it "codeshipBasic", ->
resetEnv = mockedEnv({
CODESHIP: "TRUE"
CI_NAME: "codeship"
CI_BUILD_ID: "ciBuildId"
CI_REPO_NAME: "ciRepoName"
CI_BUILD_URL: "ciBuildUrl"
CI_PROJECT_ID: "ciProjectId"
CI_BUILD_NUMBER: "ciBuildNumber"
CI_PULL_REQUEST: "ciPullRequest"
CI_COMMIT_ID: "ciCommitId"
CI_BRANCH: "ciBranch"
CI_COMMIT_MESSAGE: "ciCommitMessage"
CI_COMMITTER_NAME: "ciCommitterName"
CI_COMMITTER_EMAIL: "ciCommitterEmail"
}, {clear: true})
expectsName("codeshipBasic")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciBuildUrl: "ciBuildUrl"
ciProjectId: "ciProjectId"
ciBuildNumber: "ciBuildNumber"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "codeshipPro", ->
resetEnv = mockedEnv({
CI_NAME: "codeship"
CI_BUILD_ID: "ciBuildId"
CI_REPO_NAME: "ciRepoName"
CI_PROJECT_ID: "ciProjectId"
CI_COMMIT_ID: "ciCommitId"
CI_BRANCH: "ciBranch"
CI_COMMIT_MESSAGE: "ciCommitMessage"
CI_COMMITTER_NAME: "ciCommitterName"
CI_COMMITTER_EMAIL: "ciCommitterEmail"
}, {clear: true})
expectsName("codeshipPro")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciProjectId: "ciProjectId"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "drone", ->
resetEnv = mockedEnv({
DRONE: "true"
DRONE_JOB_NUMBER: "droneJobNumber"
DRONE_BUILD_LINK: "droneBuildLink"
DRONE_BUILD_NUMBER: "droneBuildNumber"
DRONE_PULL_REQUEST: "dronePullRequest"
DRONE_COMMIT_SHA: "droneCommitSha"
DRONE_COMMIT_BRANCH: "droneCommitBranch"
DRONE_COMMIT_MESSAGE: "droneCommitMessage"
DRONE_COMMIT_AUTHOR: "droneCommitAuthor"
DRONE_COMMIT_AUTHOR_EMAIL: "droneCommitAuthorEmail"
DRONE_REPO_BRANCH: "droneRepoBranch"
}, {clear: true})
expectsName("drone")
expectsCiParams({
droneJobNumber: "droneJobNumber"
droneBuildLink: "droneBuildLink"
droneBuildNumber: "droneBuildNumber"
dronePullRequest: "dronePullRequest"
})
expectsCommitParams({
sha: "droneCommitSha"
branch: "droneCommitBranch"
message: "droneCommitMessage"
authorName: "droneCommitAuthor"
authorEmail: "droneCommitAuthorEmail"
defaultBranch: "droneRepoBranch"
})
it "gitlab", ->
resetEnv = mockedEnv({
GITLAB_CI: "true"
# Gitlab has job id and build id as synonyms
CI_BUILD_ID: "ciJobId"
CI_JOB_ID: "ciJobId"
CI_JOB_URL: "ciJobUrl"
CI_PIPELINE_ID: "ciPipelineId"
CI_PIPELINE_URL: "ciPipelineUrl"
GITLAB_HOST: "gitlabHost"
CI_PROJECT_ID: "ciProjectId"
CI_PROJECT_URL: "ciProjectUrl"
CI_REPOSITORY_URL: "ciRepositoryUrl"
CI_ENVIRONMENT_URL: "ciEnvironmentUrl"
CI_COMMIT_SHA: "ciCommitSha"
CI_COMMIT_REF_NAME: "ciCommitRefName"
CI_COMMIT_MESSAGE: "ciCommitMessage"
GITLAB_USER_NAME: "gitlabUserName"
GITLAB_USER_EMAIL: "gitlabUserEmail"
}, {clear: true})
expectsName("gitlab")
expectsCiParams({
ciJobId: "ciJobId"
ciJobUrl: "ciJobUrl"
ciBuildId: "ciJobId"
ciPipelineId: "ciPipelineId"
ciPipelineUrl: "ciPipelineUrl"
gitlabHost: "gitlabHost"
ciProjectId: "ciProjectId"
ciProjectUrl: "ciProjectUrl"
ciRepositoryUrl: "ciRepositoryUrl"
ciEnvironmentUrl: "ciEnvironmentUrl"
})
expectsCommitParams({
sha: "ciCommitSha"
branch: "ciCommitRefName"
message: "ciCommitMessage"
authorName: "gitlabUserName"
authorEmail: "gitlabUser<PASSWORD>"
})
resetEnv = mockedEnv({
CI_SERVER_NAME: "GitLab CI"
}, {clear: true})
expectsName("gitlab")
resetEnv = mockedEnv({
CI_SERVER_NAME: "GitLab"
}, {clear: true})
expectsName("gitlab")
it "google cloud", ->
resetEnv = mockedEnv({
GCP_PROJECT: "123"
BUILD_ID: "buildId"
PROJECT_ID: "projectId"
COMMIT_SHA: "commitSha"
BRANCH_NAME: "branchName"
}, {clear: true})
expectsName("googleCloud")
expectsCiParams({
buildId: "buildId"
projectId: "projectId"
commitSha: "commitSha"
branchName: "branchName"
})
expectsCommitParams({
sha: "commitSha"
branch: "branchName"
})
resetEnv = mockedEnv({
GCLOUD_PROJECT: "123"
}, {clear: true})
expectsName("googleCloud")
resetEnv = mockedEnv({
GOOGLE_CLOUD_PROJECT: "123"
}, {clear: true})
expectsName("googleCloud")
it "jenkins", ->
resetEnv = mockedEnv({
JENKINS_URL: "true"
BUILD_ID: "buildId"
BUILD_URL: "buildUrl"
BUILD_NUMBER: "buildNumber"
ghprbPullId: "gbprbPullId"
GIT_COMMIT: "gitCommit"
GIT_BRANCH: "gitBranch"
}, {clear: true})
expectsName("jenkins")
expectsCiParams({
buildId: "buildId"
buildUrl: "buildUrl"
buildNumber: "buildNumber"
ghprbPullId: "gbprbPullId"
})
expectsCommitParams({
sha: "gitCommit"
branch: "gitBranch"
})
resetEnv = mockedEnv({
JENKINS_HOME: "/path/to/jenkins"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
JENKINS_VERSION: "1.2.3"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
HUDSON_HOME: "/path/to/jenkins"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
HUDSON_URL: "true"
}, {clear: true})
expectsName("jenkins")
it "semaphore", ->
resetEnv = mockedEnv({
SEMAPHORE: "true"
SEMAPHORE_BRANCH_ID: "semaphoreBranchId"
SEMAPHORE_BUILD_NUMBER: "semaphoreBuildNumber"
SEMAPHORE_CURRENT_JOB: "semaphoreCurrentJob"
SEMAPHORE_CURRENT_THREAD: "semaphoreCurrentThread"
SEMAPHORE_EXECUTABLE_UUID: "semaphoreExecutableUuid"
SEMAPHORE_JOB_COUNT: "semaphoreJobCount"
SEMAPHORE_JOB_UUID: "semaphoreJobUuid"
SEMAPHORE_PLATFORM: "semaphorePlatform"
SEMAPHORE_PROJECT_DIR: "semaphoreProjectDir"
SEMAPHORE_PROJECT_HASH_ID: "semaphoreProjectHashId"
SEMAPHORE_PROJECT_NAME: "semaphoreProjectName"
SEMAPHORE_PROJECT_UUID: "semaphoreProjectUuid"
SEMAPHORE_REPO_SLUG: "semaphoreRepoSlug"
SEMAPHORE_TRIGGER_SOURCE: "semaphoreTriggerSource"
PULL_REQUEST_NUMBER: "pullRequestNumber"
REVISION: "revision"
BRANCH_NAME: "branchName"
}, {clear: true})
expectsName("semaphore")
expectsCiParams({
pullRequestNumber: "pullRequestNumber"
semaphoreBranchId: "semaphoreBranchId"
semaphoreBuildNumber: "semaphoreBuildNumber"
semaphoreCurrentJob: "semaphoreCurrentJob"
semaphoreCurrentThread: "semaphoreCurrentThread"
semaphoreExecutableUuid: "semaphoreExecutableUuid"
semaphoreJobCount: "semaphoreJobCount"
semaphoreJobUuid: "semaphoreJobUuid"
semaphorePlatform: "semaphorePlatform"
semaphoreProjectDir: "semaphoreProjectDir"
semaphoreProjectHashId: "semaphoreProjectHashId"
semaphoreProjectName: "semaphoreProjectName"
semaphoreProjectUuid: "semaphoreProjectUuid"
semaphoreRepoSlug: "semaphoreRepoSlug"
semaphoreTriggerSource: "semaphoreTriggerSource"
})
expectsCommitParams({
sha: "revision"
branch: "branchName"
})
it "shippable", ->
resetEnv = mockedEnv({
SHIPPABLE: "true"
# build environment variables
SHIPPABLE_BUILD_ID: "buildId"
SHIPPABLE_BUILD_NUMBER: "buildNumber"
SHIPPABLE_COMMIT_RANGE: "commitRange"
SHIPPABLE_CONTAINER_NAME: "containerName"
SHIPPABLE_JOB_ID: "jobId"
SHIPPABLE_JOB_NUMBER: "jobNumber"
SHIPPABLE_REPO_SLUG: "repoSlug"
# additional information
IS_FORK: "isFork"
IS_GIT_TAG: "isGitTag"
IS_PRERELEASE: "isPrerelease"
IS_RELEASE: "isRelease"
REPOSITORY_URL: "repositoryUrl"
REPO_FULL_NAME: "repoFullName"
REPO_NAME: "repoName"
BUILD_URL: "buildUrl"
# pull request variables
BASE_BRANCH: "baseBranch"
HEAD_BRANCH: "headBranch"
IS_PULL_REQUEST: "isPullRequest"
PULL_REQUEST: "pullRequest"
PULL_REQUEST_BASE_BRANCH: "pullRequestBaseBranch"
PULL_REQUEST_REPO_FULL_NAME: "pullRequestRepoFullName"
# git information
COMMIT: "commit"
BRANCH: "branch"
COMMITTER: "committer"
COMMIT_MESSAGE: "commitMessage"
}, {clear: true})
expectsName("shippable")
expectsCiParams({
# build information
shippableBuildId: "buildId"
shippableBuildNumber: "buildNumber"
shippableCommitRange: "commitRange"
shippableContainerName: "containerName"
shippableJobId: "jobId"
shippableJobNumber: "jobNumber"
shippableRepoSlug: "repoSlug"
# additional information
isFork: "isFork"
isGitTag: "isGitTag"
isPrerelease: "isPrerelease"
isRelease: "isRelease"
repositoryUrl: "repositoryUrl"
repoFullName: "repoFullName"
repoName: "repoName"
buildUrl: "buildUrl"
# pull request information
baseBranch: "baseBranch"
headBranch: "headBranch"
isPullRequest: "isPullRequest"
pullRequest: "pullRequest"
pullRequestBaseBranch: "pullRequestBaseBranch"
pullRequestRepoFullName: "pullRequestRepoFullName"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "commitMessage"
authorName: "committer"
})
it "snap", ->
resetEnv = mockedEnv({
SNAP_CI: "true"
}, {clear: true})
expectsName("snap")
expectsCiParams(null)
expectsCommitParams(null)
it "teamcity", ->
resetEnv = mockedEnv({
TEAMCITY_VERSION: "true"
}, {clear: true})
expectsName("teamcity")
expectsCiParams(null)
expectsCommitParams(null)
it "azure", ->
resetEnv = mockedEnv({
# these two variables tell us it is Azure CI
TF_BUILD: "true"
AZURE_HTTP_USER_AGENT: "VSTS_5e0090d5-c5b9-4fab-8fd8-ce288e9fb666_build_2_0"
BUILD_BUILDID: "buildId"
BUILD_BUILDNUMBER: "buildNumber"
BUILD_CONTAINERID: "containerId"
BUILD_REPOSITORY_URI: "buildRepositoryUri"
BUILD_SOURCEVERSION: "commit"
BUILD_SOURCEBRANCHNAME: "branch"
BUILD_SOURCEVERSIONMESSAGE: "message"
BUILD_SOURCEVERSIONAUTHOR: "name"
BUILD_REQUESTEDFOREMAIL: "email"
}, {clear: true})
expectsName("azure")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
buildRepositoryUri: "buildRepositoryUri"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
authorEmail: "email"
})
it "teamfoundation", ->
resetEnv = mockedEnv({
TF_BUILD: "true"
TF_BUILD_BUILDNUMBER: "CIBuild_20130613.6"
BUILD_BUILDID: "buildId"
BUILD_BUILDNUMBER: "buildNumber"
BUILD_CONTAINERID: "containerId"
BUILD_SOURCEVERSION: "commit"
BUILD_SOURCEBRANCHNAME: "branch"
BUILD_SOURCEVERSIONMESSAGE: "message"
BUILD_SOURCEVERSIONAUTHOR: "name"
}, {clear: true})
expectsName("teamfoundation")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
})
it "travis", ->
resetEnv = mockedEnv({
TRAVIS: "true"
TRAVIS_JOB_ID: "travisJobId"
TRAVIS_BUILD_ID: "travisBuildId"
TRAVIS_REPO_SLUG: "travisRepoSlug"
TRAVIS_JOB_NUMBER: "travisJobNumber"
TRAVIS_EVENT_TYPE: "travisEventType"
TRAVIS_COMMIT_RANGE: "travisCommitRange"
TRAVIS_BUILD_NUMBER: "travisBuildNumber"
TRAVIS_PULL_REQUEST: "travisPullRequest"
TRAVIS_PULL_REQUEST_BRANCH: "travisPullRequestBranch"
TRAVIS_COMMIT: "travisCommit"
TRAVIS_BRANCH: "travisBranch"
TRAVIS_COMMIT_MESSAGE: "travisCommitMessage"
}, {clear: true})
expectsName("travis")
expectsCiParams({
travisJobId: "travisJobId"
travisBuildId: "travisBuildId"
travisRepoSlug: "travisRepoSlug"
travisJobNumber: "travisJobNumber"
travisEventType: "travisEventType"
travisCommitRange: "travisCommitRange"
travisBuildNumber: "travisBuildNumber"
travisPullRequest: "travisPullRequest"
travisPullRequestBranch: "travisPullRequestBranch"
})
expectsCommitParams({
sha: "travisCommit"
branch: "travisPullRequestBranch"
message: "travisCommitMessage"
})
resetEnv = mockedEnv({
TRAVIS: "true"
TRAVIS_BRANCH: "travisBranch"
}, {clear: true})
expectsCommitParams({
branch: "travisBranch"
})
it "wercker", ->
resetEnv = mockedEnv({
WERCKER: "true"
}, {clear: true})
expectsName("wercker")
expectsCiParams(null)
expectsCommitParams(null)
resetEnv = mockedEnv({
WERCKER_MAIN_PIPELINE_STARTED: "true"
}, {clear: true})
expectsName("wercker")
| true | R = require("ramda")
mockedEnv = require("mocked-env")
require("../spec_helper")
ciProvider = require("#{root}lib/util/ci_provider")
expectsName = (name) ->
expect(ciProvider.provider(), "CI providers detected name").to.eq(name)
expectsCiParams = (params) ->
expect(ciProvider.ciParams(), "CI providers detected CI params").to.deep.eq(params)
expectsCommitParams = (params) ->
expect(ciProvider.commitParams(), "CI providers detected commit params").to.deep.eq(params)
expectsCommitDefaults = (existing, expected) ->
expect(expected).to.be.an("object")
expect(ciProvider.commitDefaults(existing), "CI providers default git params").to.deep.eq(expected)
describe "lib/util/ci_provider", ->
resetEnv = null
afterEach ->
# we need to reset environment
# to avoid affecting tests in other suites
resetEnv?()
it "null when unknown", ->
resetEnv = mockedEnv({}, {clear: true})
expectsName(null)
expectsCiParams(null)
expectsCommitParams(null)
it "does not extract from commit environment variables yet", ->
# see fallback environment variables
# https://github.com/cypress-io/commit-info#fallback-environment-variables
# BUT those defaults are NOT used by "ci_provider"
# instead they are used in the "record" module
# this test just confirms that these defaults are not considered
env = {
COMMIT_INFO_BRANCH: "my-branch-221",
COMMIT_INFO_MESSAGE: "best commit ever",
COMMIT_INFO_EMAIL: "PI:EMAIL:<EMAIL>END_PI",
COMMIT_INFO_AUTHOR: "Agent PI:NAME:<NAME>END_PI",
COMMIT_INFO_SHA: "0123456",
COMMIT_INFO_REMOTE: "remote repo"
}
resetEnv = mockedEnv(env, {clear: true})
expectsName(null) # we don't know CI
expectsCiParams(null) # we don't know CI params
expectsCommitParams(null) # we don't know CI-specific params
it "appveyor", ->
resetEnv = mockedEnv({
APPVEYOR: "true"
APPVEYOR_JOB_ID: "appveyorJobId2"
APPVEYOR_ACCOUNT_NAME: "appveyorAccountName"
APPVEYOR_PROJECT_SLUG: "appveyorProjectSlug"
APPVEYOR_BUILD_VERSION: "appveyorBuildVersion"
APPVEYOR_BUILD_NUMBER: "appveyorBuildNumber"
APPVEYOR_PULL_REQUEST_NUMBER: "appveyorPullRequestNumber"
APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH: "appveyorPullRequestHeadRepoBranch"
APPVEYOR_REPO_COMMIT: "repoCommit"
APPVEYOR_REPO_COMMIT_MESSAGE: "repoCommitMessage"
APPVEYOR_REPO_BRANCH: "repoBranch"
APPVEYOR_REPO_COMMIT_AUTHOR: "repoCommitAuthor"
APPVEYOR_REPO_COMMIT_AUTHOR_EMAIL: "repoCommitAuthorEmail"
}, {clear: true})
expectsName("appveyor")
expectsCiParams({
appveyorJobId: "appveyorJobId2"
appveyorAccountName: "appveyorAccountName"
appveyorProjectSlug: "appveyorProjectSlug"
appveyorBuildNumber: "appveyorBuildNumber"
appveyorBuildVersion: "appveyorBuildVersion"
appveyorPullRequestNumber: "appveyorPullRequestNumber"
appveyorPullRequestHeadRepoBranch: "appveyorPullRequestHeadRepoBranch"
})
expectsCommitParams({
sha: "repoCommit"
branch: "appveyorPullRequestHeadRepoBranch"
message: "repoCommitMessage"
authorName: "repoCommitAuthor"
authorEmail: "repoCommitAuthorEmail"
})
resetEnv()
resetEnv = mockedEnv({
APPVEYOR: "true"
APPVEYOR_REPO_COMMIT_MESSAGE: "repoCommitMessage"
APPVEYOR_REPO_COMMIT_MESSAGE_EXTENDED: "repoCommitMessageExtended"
}, {clear: true})
expectsCommitParams({
message: "repoCommitMessage\nrepoCommitMessageExtended"
})
it "bamboo", ->
resetEnv = mockedEnv({
"bamboo.buildNumber": "123"
"bamboo.resultsUrl": "bamboo.resultsUrl"
"bamboo.buildResultsUrl": "bamboo.buildResultsUrl"
"bamboo.planRepository.repositoryUrl": "bamboo.planRepository.repositoryUrl"
"bamboo.planRepository.branch": "bamboo.planRepository.branch"
}, {clear: true})
expectsName("bamboo")
expectsCiParams({
bambooResultsUrl: "bamboo.resultsUrl"
bambooBuildNumber: "123"
bambooBuildResultsUrl: "bamboo.buildResultsUrl"
bambooPlanRepositoryRepositoryUrl: "bamboo.planRepository.repositoryUrl"
})
expectsCommitParams({
branch: "bamboo.planRepository.branch"
})
it "bitbucket", ->
resetEnv = mockedEnv({
CI: "1"
# build information
BITBUCKET_BUILD_NUMBER: "bitbucketBuildNumber"
BITBUCKET_REPO_OWNER: "bitbucketRepoOwner"
BITBUCKET_REPO_SLUG: "bitbucketRepoSlug"
# git information
BITBUCKET_COMMIT: "bitbucketCommit"
BITBUCKET_BRANCH: "bitbucketBranch"
}, {clear: true})
expectsName("bitbucket")
expectsCiParams({
bitbucketBuildNumber: "bitbucketBuildNumber"
bitbucketRepoOwner: "bitbucketRepoOwner"
bitbucketRepoSlug: "bitbucketRepoSlug"
})
expectsCommitParams({
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
expectsCommitDefaults({
sha: null
branch: "gitFoundBranch"
}, {
sha: "bitbucketCommit"
branch: "gitFoundBranch"
})
expectsCommitDefaults({
sha: undefined
branch: ""
}, {
sha: "bitbucketCommit"
branch: "bitbucketBranch"
})
it "buildkite", ->
resetEnv = mockedEnv({
BUILDKITE: "true"
BUILDKITE_REPO: "buildkiteRepo"
BUILDKITE_JOB_ID: "buildkiteJobId"
BUILDKITE_SOURCE: "buildkiteSource"
BUILDKITE_BUILD_ID: "buildkiteBuildId"
BUILDKITE_BUILD_URL: "buildkiteBuildUrl"
BUILDKITE_BUILD_NUMBER: "buildkiteBuildNumber"
BUILDKITE_PULL_REQUEST: "buildkitePullRequest"
BUILDKITE_PULL_REQUEST_REPO: "buildkitePullRequestRepo"
BUILDKITE_PULL_REQUEST_BASE_BRANCH: "buildkitePullRequestBaseBranch"
BUILDKITE_COMMIT: "buildKiteCommit"
BUILDKITE_BRANCH: "buildKiteBranch"
BUILDKITE_MESSAGE: "buildKiteMessage"
BUILDKITE_BUILD_CREATOR: "buildKiteBuildCreator"
BUILDKITE_BUILD_CREATOR_EMAIL: "buildKiteCreatorEmail"
BUILDKITE_PIPELINE_DEFAULT_BRANCH: "buildkitePipelineDefaultBranch"
}, {clear: true})
expectsName("buildkite")
expectsCiParams({
buildkiteRepo: "buildkiteRepo"
buildkiteJobId: "buildkiteJobId"
buildkiteSource: "buildkiteSource"
buildkiteBuildId: "buildkiteBuildId"
buildkiteBuildUrl: "buildkiteBuildUrl"
buildkiteBuildNumber: "buildkiteBuildNumber"
buildkitePullRequest: "buildkitePullRequest"
buildkitePullRequestRepo: "buildkitePullRequestRepo"
buildkitePullRequestBaseBranch: "buildkitePullRequestBaseBranch"
})
expectsCommitParams({
sha: "buildKiteCommit"
branch: "buildKiteBranch"
message: "buildKiteMessage"
authorName: "buildKiteBuildCreator"
authorEmail: "buildKiteCreatorEmail"
remoteOrigin: "buildkiteRepo"
defaultBranch: "buildkitePipelineDefaultBranch"
})
# in this test only interested in branch and sha for example
expectsCommitDefaults({
sha: null,
branch: "gitFoundBranch"
}, {
sha: "buildKiteCommit",
branch: "gitFoundBranch"
})
expectsCommitDefaults({
sha: undefined,
branch: ""
}, {
sha: "buildKiteCommit",
branch: "buildKiteBranch"
})
it "circle", ->
resetEnv = mockedEnv({
CIRCLECI: "true"
CIRCLE_JOB: "circleJob"
CIRCLE_BUILD_NUM: "circleBuildNum"
CIRCLE_BUILD_URL: "circleBuildUrl"
CIRCLE_PR_NUMBER: "circlePrNumber"
CIRCLE_PR_REPONAME: "circlePrReponame"
CIRCLE_PR_USERNAME: "circlePrUsername"
CIRCLE_COMPARE_URL: "circleCompareUrl"
CIRCLE_WORKFLOW_ID: "circleWorkflowId"
CIRCLE_PULL_REQUEST: "circlePullRequest"
CIRCLE_REPOSITORY_URL: "circleRepositoryUrl"
CI_PULL_REQUEST: "ciPullRequest"
CIRCLE_SHA1: "circleSha"
CIRCLE_BRANCH: "circleBranch"
CIRCLE_USERNAME: "circleUsername"
}, {clear: true})
expectsName("circle")
expectsCiParams({
circleJob: "circleJob"
circleBuildNum: "circleBuildNum"
circleBuildUrl: "circleBuildUrl"
circlePrNumber: "circlePrNumber"
circlePrReponame: "circlePrReponame"
circlePrUsername: "circlePrUsername"
circleCompareUrl: "circleCompareUrl"
circleWorkflowId: "circleWorkflowId"
circlePullRequest: "circlePullRequest"
circleRepositoryUrl: "circleRepositoryUrl"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "circleSha"
branch: "circleBranch"
authorName: "circleUsername"
})
it "codeshipBasic", ->
resetEnv = mockedEnv({
CODESHIP: "TRUE"
CI_NAME: "codeship"
CI_BUILD_ID: "ciBuildId"
CI_REPO_NAME: "ciRepoName"
CI_BUILD_URL: "ciBuildUrl"
CI_PROJECT_ID: "ciProjectId"
CI_BUILD_NUMBER: "ciBuildNumber"
CI_PULL_REQUEST: "ciPullRequest"
CI_COMMIT_ID: "ciCommitId"
CI_BRANCH: "ciBranch"
CI_COMMIT_MESSAGE: "ciCommitMessage"
CI_COMMITTER_NAME: "ciCommitterName"
CI_COMMITTER_EMAIL: "ciCommitterEmail"
}, {clear: true})
expectsName("codeshipBasic")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciBuildUrl: "ciBuildUrl"
ciProjectId: "ciProjectId"
ciBuildNumber: "ciBuildNumber"
ciPullRequest: "ciPullRequest"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "codeshipPro", ->
resetEnv = mockedEnv({
CI_NAME: "codeship"
CI_BUILD_ID: "ciBuildId"
CI_REPO_NAME: "ciRepoName"
CI_PROJECT_ID: "ciProjectId"
CI_COMMIT_ID: "ciCommitId"
CI_BRANCH: "ciBranch"
CI_COMMIT_MESSAGE: "ciCommitMessage"
CI_COMMITTER_NAME: "ciCommitterName"
CI_COMMITTER_EMAIL: "ciCommitterEmail"
}, {clear: true})
expectsName("codeshipPro")
expectsCiParams({
ciBuildId: "ciBuildId"
ciRepoName: "ciRepoName"
ciProjectId: "ciProjectId"
})
expectsCommitParams({
sha: "ciCommitId"
branch: "ciBranch"
message: "ciCommitMessage"
authorName: "ciCommitterName"
authorEmail: "ciCommitterEmail"
})
it "drone", ->
resetEnv = mockedEnv({
DRONE: "true"
DRONE_JOB_NUMBER: "droneJobNumber"
DRONE_BUILD_LINK: "droneBuildLink"
DRONE_BUILD_NUMBER: "droneBuildNumber"
DRONE_PULL_REQUEST: "dronePullRequest"
DRONE_COMMIT_SHA: "droneCommitSha"
DRONE_COMMIT_BRANCH: "droneCommitBranch"
DRONE_COMMIT_MESSAGE: "droneCommitMessage"
DRONE_COMMIT_AUTHOR: "droneCommitAuthor"
DRONE_COMMIT_AUTHOR_EMAIL: "droneCommitAuthorEmail"
DRONE_REPO_BRANCH: "droneRepoBranch"
}, {clear: true})
expectsName("drone")
expectsCiParams({
droneJobNumber: "droneJobNumber"
droneBuildLink: "droneBuildLink"
droneBuildNumber: "droneBuildNumber"
dronePullRequest: "dronePullRequest"
})
expectsCommitParams({
sha: "droneCommitSha"
branch: "droneCommitBranch"
message: "droneCommitMessage"
authorName: "droneCommitAuthor"
authorEmail: "droneCommitAuthorEmail"
defaultBranch: "droneRepoBranch"
})
it "gitlab", ->
resetEnv = mockedEnv({
GITLAB_CI: "true"
# Gitlab has job id and build id as synonyms
CI_BUILD_ID: "ciJobId"
CI_JOB_ID: "ciJobId"
CI_JOB_URL: "ciJobUrl"
CI_PIPELINE_ID: "ciPipelineId"
CI_PIPELINE_URL: "ciPipelineUrl"
GITLAB_HOST: "gitlabHost"
CI_PROJECT_ID: "ciProjectId"
CI_PROJECT_URL: "ciProjectUrl"
CI_REPOSITORY_URL: "ciRepositoryUrl"
CI_ENVIRONMENT_URL: "ciEnvironmentUrl"
CI_COMMIT_SHA: "ciCommitSha"
CI_COMMIT_REF_NAME: "ciCommitRefName"
CI_COMMIT_MESSAGE: "ciCommitMessage"
GITLAB_USER_NAME: "gitlabUserName"
GITLAB_USER_EMAIL: "gitlabUserEmail"
}, {clear: true})
expectsName("gitlab")
expectsCiParams({
ciJobId: "ciJobId"
ciJobUrl: "ciJobUrl"
ciBuildId: "ciJobId"
ciPipelineId: "ciPipelineId"
ciPipelineUrl: "ciPipelineUrl"
gitlabHost: "gitlabHost"
ciProjectId: "ciProjectId"
ciProjectUrl: "ciProjectUrl"
ciRepositoryUrl: "ciRepositoryUrl"
ciEnvironmentUrl: "ciEnvironmentUrl"
})
expectsCommitParams({
sha: "ciCommitSha"
branch: "ciCommitRefName"
message: "ciCommitMessage"
authorName: "gitlabUserName"
authorEmail: "gitlabUserPI:PASSWORD:<PASSWORD>END_PI"
})
resetEnv = mockedEnv({
CI_SERVER_NAME: "GitLab CI"
}, {clear: true})
expectsName("gitlab")
resetEnv = mockedEnv({
CI_SERVER_NAME: "GitLab"
}, {clear: true})
expectsName("gitlab")
it "google cloud", ->
resetEnv = mockedEnv({
GCP_PROJECT: "123"
BUILD_ID: "buildId"
PROJECT_ID: "projectId"
COMMIT_SHA: "commitSha"
BRANCH_NAME: "branchName"
}, {clear: true})
expectsName("googleCloud")
expectsCiParams({
buildId: "buildId"
projectId: "projectId"
commitSha: "commitSha"
branchName: "branchName"
})
expectsCommitParams({
sha: "commitSha"
branch: "branchName"
})
resetEnv = mockedEnv({
GCLOUD_PROJECT: "123"
}, {clear: true})
expectsName("googleCloud")
resetEnv = mockedEnv({
GOOGLE_CLOUD_PROJECT: "123"
}, {clear: true})
expectsName("googleCloud")
it "jenkins", ->
resetEnv = mockedEnv({
JENKINS_URL: "true"
BUILD_ID: "buildId"
BUILD_URL: "buildUrl"
BUILD_NUMBER: "buildNumber"
ghprbPullId: "gbprbPullId"
GIT_COMMIT: "gitCommit"
GIT_BRANCH: "gitBranch"
}, {clear: true})
expectsName("jenkins")
expectsCiParams({
buildId: "buildId"
buildUrl: "buildUrl"
buildNumber: "buildNumber"
ghprbPullId: "gbprbPullId"
})
expectsCommitParams({
sha: "gitCommit"
branch: "gitBranch"
})
resetEnv = mockedEnv({
JENKINS_HOME: "/path/to/jenkins"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
JENKINS_VERSION: "1.2.3"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
HUDSON_HOME: "/path/to/jenkins"
}, {clear: true})
expectsName("jenkins")
resetEnv = mockedEnv({
HUDSON_URL: "true"
}, {clear: true})
expectsName("jenkins")
it "semaphore", ->
resetEnv = mockedEnv({
SEMAPHORE: "true"
SEMAPHORE_BRANCH_ID: "semaphoreBranchId"
SEMAPHORE_BUILD_NUMBER: "semaphoreBuildNumber"
SEMAPHORE_CURRENT_JOB: "semaphoreCurrentJob"
SEMAPHORE_CURRENT_THREAD: "semaphoreCurrentThread"
SEMAPHORE_EXECUTABLE_UUID: "semaphoreExecutableUuid"
SEMAPHORE_JOB_COUNT: "semaphoreJobCount"
SEMAPHORE_JOB_UUID: "semaphoreJobUuid"
SEMAPHORE_PLATFORM: "semaphorePlatform"
SEMAPHORE_PROJECT_DIR: "semaphoreProjectDir"
SEMAPHORE_PROJECT_HASH_ID: "semaphoreProjectHashId"
SEMAPHORE_PROJECT_NAME: "semaphoreProjectName"
SEMAPHORE_PROJECT_UUID: "semaphoreProjectUuid"
SEMAPHORE_REPO_SLUG: "semaphoreRepoSlug"
SEMAPHORE_TRIGGER_SOURCE: "semaphoreTriggerSource"
PULL_REQUEST_NUMBER: "pullRequestNumber"
REVISION: "revision"
BRANCH_NAME: "branchName"
}, {clear: true})
expectsName("semaphore")
expectsCiParams({
pullRequestNumber: "pullRequestNumber"
semaphoreBranchId: "semaphoreBranchId"
semaphoreBuildNumber: "semaphoreBuildNumber"
semaphoreCurrentJob: "semaphoreCurrentJob"
semaphoreCurrentThread: "semaphoreCurrentThread"
semaphoreExecutableUuid: "semaphoreExecutableUuid"
semaphoreJobCount: "semaphoreJobCount"
semaphoreJobUuid: "semaphoreJobUuid"
semaphorePlatform: "semaphorePlatform"
semaphoreProjectDir: "semaphoreProjectDir"
semaphoreProjectHashId: "semaphoreProjectHashId"
semaphoreProjectName: "semaphoreProjectName"
semaphoreProjectUuid: "semaphoreProjectUuid"
semaphoreRepoSlug: "semaphoreRepoSlug"
semaphoreTriggerSource: "semaphoreTriggerSource"
})
expectsCommitParams({
sha: "revision"
branch: "branchName"
})
it "shippable", ->
resetEnv = mockedEnv({
SHIPPABLE: "true"
# build environment variables
SHIPPABLE_BUILD_ID: "buildId"
SHIPPABLE_BUILD_NUMBER: "buildNumber"
SHIPPABLE_COMMIT_RANGE: "commitRange"
SHIPPABLE_CONTAINER_NAME: "containerName"
SHIPPABLE_JOB_ID: "jobId"
SHIPPABLE_JOB_NUMBER: "jobNumber"
SHIPPABLE_REPO_SLUG: "repoSlug"
# additional information
IS_FORK: "isFork"
IS_GIT_TAG: "isGitTag"
IS_PRERELEASE: "isPrerelease"
IS_RELEASE: "isRelease"
REPOSITORY_URL: "repositoryUrl"
REPO_FULL_NAME: "repoFullName"
REPO_NAME: "repoName"
BUILD_URL: "buildUrl"
# pull request variables
BASE_BRANCH: "baseBranch"
HEAD_BRANCH: "headBranch"
IS_PULL_REQUEST: "isPullRequest"
PULL_REQUEST: "pullRequest"
PULL_REQUEST_BASE_BRANCH: "pullRequestBaseBranch"
PULL_REQUEST_REPO_FULL_NAME: "pullRequestRepoFullName"
# git information
COMMIT: "commit"
BRANCH: "branch"
COMMITTER: "committer"
COMMIT_MESSAGE: "commitMessage"
}, {clear: true})
expectsName("shippable")
expectsCiParams({
# build information
shippableBuildId: "buildId"
shippableBuildNumber: "buildNumber"
shippableCommitRange: "commitRange"
shippableContainerName: "containerName"
shippableJobId: "jobId"
shippableJobNumber: "jobNumber"
shippableRepoSlug: "repoSlug"
# additional information
isFork: "isFork"
isGitTag: "isGitTag"
isPrerelease: "isPrerelease"
isRelease: "isRelease"
repositoryUrl: "repositoryUrl"
repoFullName: "repoFullName"
repoName: "repoName"
buildUrl: "buildUrl"
# pull request information
baseBranch: "baseBranch"
headBranch: "headBranch"
isPullRequest: "isPullRequest"
pullRequest: "pullRequest"
pullRequestBaseBranch: "pullRequestBaseBranch"
pullRequestRepoFullName: "pullRequestRepoFullName"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "commitMessage"
authorName: "committer"
})
it "snap", ->
resetEnv = mockedEnv({
SNAP_CI: "true"
}, {clear: true})
expectsName("snap")
expectsCiParams(null)
expectsCommitParams(null)
it "teamcity", ->
resetEnv = mockedEnv({
TEAMCITY_VERSION: "true"
}, {clear: true})
expectsName("teamcity")
expectsCiParams(null)
expectsCommitParams(null)
it "azure", ->
resetEnv = mockedEnv({
# these two variables tell us it is Azure CI
TF_BUILD: "true"
AZURE_HTTP_USER_AGENT: "VSTS_5e0090d5-c5b9-4fab-8fd8-ce288e9fb666_build_2_0"
BUILD_BUILDID: "buildId"
BUILD_BUILDNUMBER: "buildNumber"
BUILD_CONTAINERID: "containerId"
BUILD_REPOSITORY_URI: "buildRepositoryUri"
BUILD_SOURCEVERSION: "commit"
BUILD_SOURCEBRANCHNAME: "branch"
BUILD_SOURCEVERSIONMESSAGE: "message"
BUILD_SOURCEVERSIONAUTHOR: "name"
BUILD_REQUESTEDFOREMAIL: "email"
}, {clear: true})
expectsName("azure")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
buildRepositoryUri: "buildRepositoryUri"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
authorEmail: "email"
})
it "teamfoundation", ->
resetEnv = mockedEnv({
TF_BUILD: "true"
TF_BUILD_BUILDNUMBER: "CIBuild_20130613.6"
BUILD_BUILDID: "buildId"
BUILD_BUILDNUMBER: "buildNumber"
BUILD_CONTAINERID: "containerId"
BUILD_SOURCEVERSION: "commit"
BUILD_SOURCEBRANCHNAME: "branch"
BUILD_SOURCEVERSIONMESSAGE: "message"
BUILD_SOURCEVERSIONAUTHOR: "name"
}, {clear: true})
expectsName("teamfoundation")
expectsCiParams({
buildBuildid: "buildId"
buildBuildnumber: "buildNumber"
buildContainerid: "containerId"
})
expectsCommitParams({
sha: "commit"
branch: "branch"
message: "message"
authorName: "name"
})
it "travis", ->
resetEnv = mockedEnv({
TRAVIS: "true"
TRAVIS_JOB_ID: "travisJobId"
TRAVIS_BUILD_ID: "travisBuildId"
TRAVIS_REPO_SLUG: "travisRepoSlug"
TRAVIS_JOB_NUMBER: "travisJobNumber"
TRAVIS_EVENT_TYPE: "travisEventType"
TRAVIS_COMMIT_RANGE: "travisCommitRange"
TRAVIS_BUILD_NUMBER: "travisBuildNumber"
TRAVIS_PULL_REQUEST: "travisPullRequest"
TRAVIS_PULL_REQUEST_BRANCH: "travisPullRequestBranch"
TRAVIS_COMMIT: "travisCommit"
TRAVIS_BRANCH: "travisBranch"
TRAVIS_COMMIT_MESSAGE: "travisCommitMessage"
}, {clear: true})
expectsName("travis")
expectsCiParams({
travisJobId: "travisJobId"
travisBuildId: "travisBuildId"
travisRepoSlug: "travisRepoSlug"
travisJobNumber: "travisJobNumber"
travisEventType: "travisEventType"
travisCommitRange: "travisCommitRange"
travisBuildNumber: "travisBuildNumber"
travisPullRequest: "travisPullRequest"
travisPullRequestBranch: "travisPullRequestBranch"
})
expectsCommitParams({
sha: "travisCommit"
branch: "travisPullRequestBranch"
message: "travisCommitMessage"
})
resetEnv = mockedEnv({
TRAVIS: "true"
TRAVIS_BRANCH: "travisBranch"
}, {clear: true})
expectsCommitParams({
branch: "travisBranch"
})
it "wercker", ->
resetEnv = mockedEnv({
WERCKER: "true"
}, {clear: true})
expectsName("wercker")
expectsCiParams(null)
expectsCommitParams(null)
resetEnv = mockedEnv({
WERCKER_MAIN_PIPELINE_STARTED: "true"
}, {clear: true})
expectsName("wercker")
|
[
{
"context": "tforms(\n mapH: mapH\n tileImageKey: 'balcony'\n , @game, @gui?.addOpenFolder('platforms'))",
"end": 6482,
"score": 0.9994368553161621,
"start": 6475,
"tag": "KEY",
"value": "balcony"
},
{
"context": " tween = @fadeTo(text, Timer.SECOND, 1)\n\n # photonstorm/phaser@aee0212\n _fixCamera: _.once ->\n @c",
"end": 7216,
"score": 0.997941792011261,
"start": 7205,
"tag": "USERNAME",
"value": "photonstorm"
}
] | src/state-play.coffee | hlfcoding/morning-stroll | 3 | # PlayState
# =========
# This is the main game class. It coordinates between the main game objects
# (including camera and music) and handles their interactions. It also handles
# ending the game, and any shortkeys. The exact list is long, but start tracing
# from `create` and `update` like any other Phaser state, and you should get
# far. Also note any logic that can be easily factored out is factored out of
# this file.
define [
'background', 'defines', 'helpers', 'in-state-menu', 'platforms', 'player'
], (Background, defines, Helpers, InStateMenu, Platforms, Player) ->
{Camera, Key, Keyboard, Physics, Point, Rectangle, State, Timer} = Phaser
{domStateEvents, fontLarge, fontSmall} = defines
{artH, mapH, deadzoneH, shakeFallH} = defines
{playerH, playerW, playerYOffset} = defines
{AnimationMixin, CameraMixin, TextMixin} = Helpers
{DebugMixin, DebugDisplayMixin} = Helpers
MateLastFrame = 14
class PlayState extends State
init: ->
if domStateEvents
e = document.createEvent('CustomEvent')
e.initCustomEvent('state:play', no, no, undefined)
@game.parent.dispatchEvent(e)
{@debugging, @developing} = defines
@detachedCamera = off
@ended = no
@debugDisplay = @gui = null
@cursors = null
@background = @mate = @platforms = @player = null
@textLayout = null
_.extend(@camera, CameraMixin)
@_fixCamera()
@game.onBlur.add(@onBlur)
@game.onFocus.add(@onFocus)
@_initDebugMixin
@_initDebugDisplayMixin(@game)
return
create: ->
@physics.startSystem(Physics.ARCADE)
@physics.arcade.gravity.y = 500
@cursors = @input.keyboard.createCursorKeys()
# Quit on Q
@quitKey = @_addKey(Keyboard.Q, @quit)
# Quit on click at end.
@input.onTap.add((trigger) =>
unless @quit(trigger)
@inStateMenu.toggle()
return
, @)
if @developing
@gui = new dat.GUI()
@gui.add(@, 'debugging').listen().onFinishChange =>
@background.debugging = @platforms.debugging = @player.debugging =
@debugging
@debugDisplay.reset() unless @debugging
return
@gui.add(@, 'detachedCamera').onFinishChange =>
@_toggleCameraAttachment()
return
@gui.addOpenFolder('gravity').addRange(@physics.arcade.gravity, 'y')
# First:
@_addMusic()
@_addBackground()
@_addPlatforms()
# Then:
@_addPlayer()
@_addMate()
# Last:
@_addInStateMenu()
@camera.deadzone = new Rectangle(
0, (@game.height - deadzoneH) / 2,
@game.width, deadzoneH
)
@_toggleCameraAttachment(on)
# Set after initial follow.
_.defer( => @camera.lerp.set(0.05); return )
return
update: ->
@physics.arcade.collide(@player.sprite, @platforms.layer)
@background.update()
@player.update()
@_updateVolumeOnPlayerLand()
@_shakeOnPlayerFall()
@camera.updatePositionWithCursors(@cursors) if @detachedCamera
@end() if @_isPlayerReadyToEnd()
return
render: ->
@_renderDebugDisplay() if @debugging
@_renderDebugOverlays() if @debugging
return
shutdown: ->
# Null references to disposable objects we don't own.
gameObject.destroy() for gameObject in [
@background, @inStateMenu, @music, @platforms, @player
]
@game.onBlur.remove(@onBlur)
@game.onFocus.remove(@onFocus)
@input.onTap.removeAll(@)
key.onDown.removeAll(@) for key in [
@loudKey, @muteKey, @quietKey, @quitKey
]
@gui?.destroy()
return
onBlur: =>
@music?.pause()
return
onFocus: =>
@music?.resume()
return
# Main own methods
# ----------------
end: ->
# First animate player.
animation = @player.startEnding(@mate)
animation.onComplete.addOnce =>
# Then animate mate.
animation = @mate.play('end')
animation.onComplete.addOnce =>
# Then lock them onto their final frames.
@player.animations.frame = Player.LastFrame
@mate.animations.frame = MateLastFrame
# Then render ending display.
_.delay( =>
@_renderEndingDisplay()
return
, 5 * Timer.SECOND)
return
quit: (trigger) ->
return no unless @ended or trigger instanceof Key
@inStateMenu.toggle(off)
_quit = =>
@state.startWithTransition(null, 'menu', yes)
return
if @music.volume is 0
_quit()
else
# Fade the music.
@music.fadeOut(3 * Timer.SECOND)
# Then go back to menu while clearing world.
@music.onFadeComplete.addOnce(_quit)
yes
# Subroutines
# -----------
_addBackground: ->
parallaxTolerance = mapH - artH
@background = new Background({ parallaxTolerance }, @game)
@background.addImages(_.template('bg<%= zIndex %>'), 16)
@background.layout()
return
_addInStateMenu: ->
@inStateMenu = new InStateMenu([
['Paused', { fontSize: fontLarge }]
['Hold arrow keys to accelerate', { fontSize: fontSmall }]
['Press 0, -, + for volume', { fontSize: fontSmall }]
['Press Q to quit', { fontSize: fontSmall }]
], @game, pauseHandler: (paused) =>
@player.control = not paused
return
)
return
_addKey: (keyCode, callback) ->
key = @input.keyboard.addKey(keyCode)
key.onDown.add(callback, @)
@input.keyboard.removeKeyCapture(keyCode)
key
_addMate: ->
{x, y} = @endingPoint
x += 20
y -= 10
@mate = @add.sprite(x, y, 'mate', 1)
@mate.anchor = new Point(0.5, 0.5)
@mate.animations.add('end', [4..MateLastFrame], 12)
return
_addMusic: ->
@userVolume = 1
@music = @add.audio('bgm', 0.2, yes)
@music.mute = @developing or @debugging
@music.play()
@gui?.add(@music, 'mute').listen()
increment = 0.1
@loudKey = @_addKey Keyboard.EQUALS, =>
@userVolume += increment; return
@muteKey = @_addKey Keyboard.ZERO, =>
@music.mute = not @music.mute; return
@quietKey = @_addKey Keyboard.UNDERSCORE, =>
@userVolume -= increment; return
return
_addPlatforms: ->
@platforms = new Platforms(
mapH: mapH
tileImageKey: 'balcony'
, @game, @gui?.addOpenFolder('platforms'))
@endingPoint = @platforms.ledges[-1...][0].createMidpoint(@platforms)
@startingPoint = new Point(
playerW, (@world.height - playerH + playerYOffset)
)
# Use for debugging ending.
#@startingPoint = @platforms.ledges[-2...-1][0].createMidpoint @platforms
return
_addPlayer: ->
origin = @startingPoint
@player = new Player(
{ origin }, @game, @cursors, @gui?.addOpenFolder('player')
)
return
_addText: (text, style) ->
_.defaults(style, { fill: '#fff', font: 'Enriqueta' })
text = @addCenteredText(text, @textLayout, style)
tween = @fadeTo(text, Timer.SECOND, 1)
# photonstorm/phaser@aee0212
_fixCamera: _.once ->
@camera.flawedUpdateTarget = @camera.updateTarget
@camera.updateTarget = =>
@camera.target.world.copyFrom(@camera.target.position)
@camera.flawedUpdateTarget()
return
return
_isPlayerReadyToEnd: ->
(@player.state is 'still' and @player.control is on and
@player.sprite.y <= @endingPoint.y)
_renderDebugDisplay: ->
@resetDebugDisplayLayout()
if @player.debugging
@renderDebugDisplayItems((layoutX, layoutY) =>
@debugDisplay.bodyInfo(@player.sprite, layoutX, layoutY)
return
, 6)
@renderDebugDisplayItems(@player.debugTextItems)
_renderDebugOverlays: ->
if @player.debugging
@debugDisplay.body(@player.sprite)
@debugDisplay.spriteBounds(@player.sprite)
return
_renderEndingDisplay: ->
@textLayout = { y: 120, baseline: 40 }
@_addText('The End', { fontSize: fontLarge })
.onComplete.addOnce =>
@_addText('Click to play again', { fontSize: fontSmall })
@ended = yes
return
return
_shakeOnPlayerFall: ->
return no unless (
@player.nextState is 'landing' and
@player.distanceFallen() > shakeFallH
)
force = no
@camera.shake(0.02, 0.1 * Timer.SECOND, force, Camera.SHAKE_VERTICAL)
return
_toggleCameraAttachment: (attached) ->
attached ?= not @detachedCamera
if attached
@camera.follow(@player.sprite)
@player.cursors ?= @cursors
else
@camera.unfollow()
@player.cursors = null
return
_updateVolumeOnPlayerLand: ->
return no unless @player.nextState is 'landing'
# The music gets louder the higher the player gets.
volume = ((@platforms.tilemap.heightInPixels - @player.sprite.y) /
@platforms.tilemap.heightInPixels) ** 1.3
volume *= @math.clamp(@userVolume, 0, 2) # Factor in user controls.
volume = @math.clamp(volume, 0.2, 0.8)
@music.fadeTo(Timer.SECOND, volume)
return
_.extend( PlayState::,
AnimationMixin, DebugMixin, DebugDisplayMixin, TextMixin
)
PlayState
| 120150 | # PlayState
# =========
# This is the main game class. It coordinates between the main game objects
# (including camera and music) and handles their interactions. It also handles
# ending the game, and any shortkeys. The exact list is long, but start tracing
# from `create` and `update` like any other Phaser state, and you should get
# far. Also note any logic that can be easily factored out is factored out of
# this file.
define [
'background', 'defines', 'helpers', 'in-state-menu', 'platforms', 'player'
], (Background, defines, Helpers, InStateMenu, Platforms, Player) ->
{Camera, Key, Keyboard, Physics, Point, Rectangle, State, Timer} = Phaser
{domStateEvents, fontLarge, fontSmall} = defines
{artH, mapH, deadzoneH, shakeFallH} = defines
{playerH, playerW, playerYOffset} = defines
{AnimationMixin, CameraMixin, TextMixin} = Helpers
{DebugMixin, DebugDisplayMixin} = Helpers
MateLastFrame = 14
class PlayState extends State
init: ->
if domStateEvents
e = document.createEvent('CustomEvent')
e.initCustomEvent('state:play', no, no, undefined)
@game.parent.dispatchEvent(e)
{@debugging, @developing} = defines
@detachedCamera = off
@ended = no
@debugDisplay = @gui = null
@cursors = null
@background = @mate = @platforms = @player = null
@textLayout = null
_.extend(@camera, CameraMixin)
@_fixCamera()
@game.onBlur.add(@onBlur)
@game.onFocus.add(@onFocus)
@_initDebugMixin
@_initDebugDisplayMixin(@game)
return
create: ->
@physics.startSystem(Physics.ARCADE)
@physics.arcade.gravity.y = 500
@cursors = @input.keyboard.createCursorKeys()
# Quit on Q
@quitKey = @_addKey(Keyboard.Q, @quit)
# Quit on click at end.
@input.onTap.add((trigger) =>
unless @quit(trigger)
@inStateMenu.toggle()
return
, @)
if @developing
@gui = new dat.GUI()
@gui.add(@, 'debugging').listen().onFinishChange =>
@background.debugging = @platforms.debugging = @player.debugging =
@debugging
@debugDisplay.reset() unless @debugging
return
@gui.add(@, 'detachedCamera').onFinishChange =>
@_toggleCameraAttachment()
return
@gui.addOpenFolder('gravity').addRange(@physics.arcade.gravity, 'y')
# First:
@_addMusic()
@_addBackground()
@_addPlatforms()
# Then:
@_addPlayer()
@_addMate()
# Last:
@_addInStateMenu()
@camera.deadzone = new Rectangle(
0, (@game.height - deadzoneH) / 2,
@game.width, deadzoneH
)
@_toggleCameraAttachment(on)
# Set after initial follow.
_.defer( => @camera.lerp.set(0.05); return )
return
update: ->
@physics.arcade.collide(@player.sprite, @platforms.layer)
@background.update()
@player.update()
@_updateVolumeOnPlayerLand()
@_shakeOnPlayerFall()
@camera.updatePositionWithCursors(@cursors) if @detachedCamera
@end() if @_isPlayerReadyToEnd()
return
render: ->
@_renderDebugDisplay() if @debugging
@_renderDebugOverlays() if @debugging
return
shutdown: ->
# Null references to disposable objects we don't own.
gameObject.destroy() for gameObject in [
@background, @inStateMenu, @music, @platforms, @player
]
@game.onBlur.remove(@onBlur)
@game.onFocus.remove(@onFocus)
@input.onTap.removeAll(@)
key.onDown.removeAll(@) for key in [
@loudKey, @muteKey, @quietKey, @quitKey
]
@gui?.destroy()
return
onBlur: =>
@music?.pause()
return
onFocus: =>
@music?.resume()
return
# Main own methods
# ----------------
end: ->
# First animate player.
animation = @player.startEnding(@mate)
animation.onComplete.addOnce =>
# Then animate mate.
animation = @mate.play('end')
animation.onComplete.addOnce =>
# Then lock them onto their final frames.
@player.animations.frame = Player.LastFrame
@mate.animations.frame = MateLastFrame
# Then render ending display.
_.delay( =>
@_renderEndingDisplay()
return
, 5 * Timer.SECOND)
return
quit: (trigger) ->
return no unless @ended or trigger instanceof Key
@inStateMenu.toggle(off)
_quit = =>
@state.startWithTransition(null, 'menu', yes)
return
if @music.volume is 0
_quit()
else
# Fade the music.
@music.fadeOut(3 * Timer.SECOND)
# Then go back to menu while clearing world.
@music.onFadeComplete.addOnce(_quit)
yes
# Subroutines
# -----------
_addBackground: ->
parallaxTolerance = mapH - artH
@background = new Background({ parallaxTolerance }, @game)
@background.addImages(_.template('bg<%= zIndex %>'), 16)
@background.layout()
return
_addInStateMenu: ->
@inStateMenu = new InStateMenu([
['Paused', { fontSize: fontLarge }]
['Hold arrow keys to accelerate', { fontSize: fontSmall }]
['Press 0, -, + for volume', { fontSize: fontSmall }]
['Press Q to quit', { fontSize: fontSmall }]
], @game, pauseHandler: (paused) =>
@player.control = not paused
return
)
return
_addKey: (keyCode, callback) ->
key = @input.keyboard.addKey(keyCode)
key.onDown.add(callback, @)
@input.keyboard.removeKeyCapture(keyCode)
key
_addMate: ->
{x, y} = @endingPoint
x += 20
y -= 10
@mate = @add.sprite(x, y, 'mate', 1)
@mate.anchor = new Point(0.5, 0.5)
@mate.animations.add('end', [4..MateLastFrame], 12)
return
_addMusic: ->
@userVolume = 1
@music = @add.audio('bgm', 0.2, yes)
@music.mute = @developing or @debugging
@music.play()
@gui?.add(@music, 'mute').listen()
increment = 0.1
@loudKey = @_addKey Keyboard.EQUALS, =>
@userVolume += increment; return
@muteKey = @_addKey Keyboard.ZERO, =>
@music.mute = not @music.mute; return
@quietKey = @_addKey Keyboard.UNDERSCORE, =>
@userVolume -= increment; return
return
_addPlatforms: ->
@platforms = new Platforms(
mapH: mapH
tileImageKey: '<KEY>'
, @game, @gui?.addOpenFolder('platforms'))
@endingPoint = @platforms.ledges[-1...][0].createMidpoint(@platforms)
@startingPoint = new Point(
playerW, (@world.height - playerH + playerYOffset)
)
# Use for debugging ending.
#@startingPoint = @platforms.ledges[-2...-1][0].createMidpoint @platforms
return
_addPlayer: ->
origin = @startingPoint
@player = new Player(
{ origin }, @game, @cursors, @gui?.addOpenFolder('player')
)
return
_addText: (text, style) ->
_.defaults(style, { fill: '#fff', font: 'Enriqueta' })
text = @addCenteredText(text, @textLayout, style)
tween = @fadeTo(text, Timer.SECOND, 1)
# photonstorm/phaser@aee0212
_fixCamera: _.once ->
@camera.flawedUpdateTarget = @camera.updateTarget
@camera.updateTarget = =>
@camera.target.world.copyFrom(@camera.target.position)
@camera.flawedUpdateTarget()
return
return
_isPlayerReadyToEnd: ->
(@player.state is 'still' and @player.control is on and
@player.sprite.y <= @endingPoint.y)
_renderDebugDisplay: ->
@resetDebugDisplayLayout()
if @player.debugging
@renderDebugDisplayItems((layoutX, layoutY) =>
@debugDisplay.bodyInfo(@player.sprite, layoutX, layoutY)
return
, 6)
@renderDebugDisplayItems(@player.debugTextItems)
_renderDebugOverlays: ->
if @player.debugging
@debugDisplay.body(@player.sprite)
@debugDisplay.spriteBounds(@player.sprite)
return
_renderEndingDisplay: ->
@textLayout = { y: 120, baseline: 40 }
@_addText('The End', { fontSize: fontLarge })
.onComplete.addOnce =>
@_addText('Click to play again', { fontSize: fontSmall })
@ended = yes
return
return
_shakeOnPlayerFall: ->
return no unless (
@player.nextState is 'landing' and
@player.distanceFallen() > shakeFallH
)
force = no
@camera.shake(0.02, 0.1 * Timer.SECOND, force, Camera.SHAKE_VERTICAL)
return
_toggleCameraAttachment: (attached) ->
attached ?= not @detachedCamera
if attached
@camera.follow(@player.sprite)
@player.cursors ?= @cursors
else
@camera.unfollow()
@player.cursors = null
return
_updateVolumeOnPlayerLand: ->
return no unless @player.nextState is 'landing'
# The music gets louder the higher the player gets.
volume = ((@platforms.tilemap.heightInPixels - @player.sprite.y) /
@platforms.tilemap.heightInPixels) ** 1.3
volume *= @math.clamp(@userVolume, 0, 2) # Factor in user controls.
volume = @math.clamp(volume, 0.2, 0.8)
@music.fadeTo(Timer.SECOND, volume)
return
_.extend( PlayState::,
AnimationMixin, DebugMixin, DebugDisplayMixin, TextMixin
)
PlayState
| true | # PlayState
# =========
# This is the main game class. It coordinates between the main game objects
# (including camera and music) and handles their interactions. It also handles
# ending the game, and any shortkeys. The exact list is long, but start tracing
# from `create` and `update` like any other Phaser state, and you should get
# far. Also note any logic that can be easily factored out is factored out of
# this file.
define [
'background', 'defines', 'helpers', 'in-state-menu', 'platforms', 'player'
], (Background, defines, Helpers, InStateMenu, Platforms, Player) ->
{Camera, Key, Keyboard, Physics, Point, Rectangle, State, Timer} = Phaser
{domStateEvents, fontLarge, fontSmall} = defines
{artH, mapH, deadzoneH, shakeFallH} = defines
{playerH, playerW, playerYOffset} = defines
{AnimationMixin, CameraMixin, TextMixin} = Helpers
{DebugMixin, DebugDisplayMixin} = Helpers
MateLastFrame = 14
class PlayState extends State
init: ->
if domStateEvents
e = document.createEvent('CustomEvent')
e.initCustomEvent('state:play', no, no, undefined)
@game.parent.dispatchEvent(e)
{@debugging, @developing} = defines
@detachedCamera = off
@ended = no
@debugDisplay = @gui = null
@cursors = null
@background = @mate = @platforms = @player = null
@textLayout = null
_.extend(@camera, CameraMixin)
@_fixCamera()
@game.onBlur.add(@onBlur)
@game.onFocus.add(@onFocus)
@_initDebugMixin
@_initDebugDisplayMixin(@game)
return
create: ->
@physics.startSystem(Physics.ARCADE)
@physics.arcade.gravity.y = 500
@cursors = @input.keyboard.createCursorKeys()
# Quit on Q
@quitKey = @_addKey(Keyboard.Q, @quit)
# Quit on click at end.
@input.onTap.add((trigger) =>
unless @quit(trigger)
@inStateMenu.toggle()
return
, @)
if @developing
@gui = new dat.GUI()
@gui.add(@, 'debugging').listen().onFinishChange =>
@background.debugging = @platforms.debugging = @player.debugging =
@debugging
@debugDisplay.reset() unless @debugging
return
@gui.add(@, 'detachedCamera').onFinishChange =>
@_toggleCameraAttachment()
return
@gui.addOpenFolder('gravity').addRange(@physics.arcade.gravity, 'y')
# First:
@_addMusic()
@_addBackground()
@_addPlatforms()
# Then:
@_addPlayer()
@_addMate()
# Last:
@_addInStateMenu()
@camera.deadzone = new Rectangle(
0, (@game.height - deadzoneH) / 2,
@game.width, deadzoneH
)
@_toggleCameraAttachment(on)
# Set after initial follow.
_.defer( => @camera.lerp.set(0.05); return )
return
update: ->
@physics.arcade.collide(@player.sprite, @platforms.layer)
@background.update()
@player.update()
@_updateVolumeOnPlayerLand()
@_shakeOnPlayerFall()
@camera.updatePositionWithCursors(@cursors) if @detachedCamera
@end() if @_isPlayerReadyToEnd()
return
render: ->
@_renderDebugDisplay() if @debugging
@_renderDebugOverlays() if @debugging
return
shutdown: ->
# Null references to disposable objects we don't own.
gameObject.destroy() for gameObject in [
@background, @inStateMenu, @music, @platforms, @player
]
@game.onBlur.remove(@onBlur)
@game.onFocus.remove(@onFocus)
@input.onTap.removeAll(@)
key.onDown.removeAll(@) for key in [
@loudKey, @muteKey, @quietKey, @quitKey
]
@gui?.destroy()
return
onBlur: =>
@music?.pause()
return
onFocus: =>
@music?.resume()
return
# Main own methods
# ----------------
end: ->
# First animate player.
animation = @player.startEnding(@mate)
animation.onComplete.addOnce =>
# Then animate mate.
animation = @mate.play('end')
animation.onComplete.addOnce =>
# Then lock them onto their final frames.
@player.animations.frame = Player.LastFrame
@mate.animations.frame = MateLastFrame
# Then render ending display.
_.delay( =>
@_renderEndingDisplay()
return
, 5 * Timer.SECOND)
return
quit: (trigger) ->
return no unless @ended or trigger instanceof Key
@inStateMenu.toggle(off)
_quit = =>
@state.startWithTransition(null, 'menu', yes)
return
if @music.volume is 0
_quit()
else
# Fade the music.
@music.fadeOut(3 * Timer.SECOND)
# Then go back to menu while clearing world.
@music.onFadeComplete.addOnce(_quit)
yes
# Subroutines
# -----------
_addBackground: ->
parallaxTolerance = mapH - artH
@background = new Background({ parallaxTolerance }, @game)
@background.addImages(_.template('bg<%= zIndex %>'), 16)
@background.layout()
return
_addInStateMenu: ->
@inStateMenu = new InStateMenu([
['Paused', { fontSize: fontLarge }]
['Hold arrow keys to accelerate', { fontSize: fontSmall }]
['Press 0, -, + for volume', { fontSize: fontSmall }]
['Press Q to quit', { fontSize: fontSmall }]
], @game, pauseHandler: (paused) =>
@player.control = not paused
return
)
return
_addKey: (keyCode, callback) ->
key = @input.keyboard.addKey(keyCode)
key.onDown.add(callback, @)
@input.keyboard.removeKeyCapture(keyCode)
key
_addMate: ->
{x, y} = @endingPoint
x += 20
y -= 10
@mate = @add.sprite(x, y, 'mate', 1)
@mate.anchor = new Point(0.5, 0.5)
@mate.animations.add('end', [4..MateLastFrame], 12)
return
_addMusic: ->
@userVolume = 1
@music = @add.audio('bgm', 0.2, yes)
@music.mute = @developing or @debugging
@music.play()
@gui?.add(@music, 'mute').listen()
increment = 0.1
@loudKey = @_addKey Keyboard.EQUALS, =>
@userVolume += increment; return
@muteKey = @_addKey Keyboard.ZERO, =>
@music.mute = not @music.mute; return
@quietKey = @_addKey Keyboard.UNDERSCORE, =>
@userVolume -= increment; return
return
_addPlatforms: ->
@platforms = new Platforms(
mapH: mapH
tileImageKey: 'PI:KEY:<KEY>END_PI'
, @game, @gui?.addOpenFolder('platforms'))
@endingPoint = @platforms.ledges[-1...][0].createMidpoint(@platforms)
@startingPoint = new Point(
playerW, (@world.height - playerH + playerYOffset)
)
# Use for debugging ending.
#@startingPoint = @platforms.ledges[-2...-1][0].createMidpoint @platforms
return
_addPlayer: ->
origin = @startingPoint
@player = new Player(
{ origin }, @game, @cursors, @gui?.addOpenFolder('player')
)
return
_addText: (text, style) ->
_.defaults(style, { fill: '#fff', font: 'Enriqueta' })
text = @addCenteredText(text, @textLayout, style)
tween = @fadeTo(text, Timer.SECOND, 1)
# photonstorm/phaser@aee0212
_fixCamera: _.once ->
@camera.flawedUpdateTarget = @camera.updateTarget
@camera.updateTarget = =>
@camera.target.world.copyFrom(@camera.target.position)
@camera.flawedUpdateTarget()
return
return
_isPlayerReadyToEnd: ->
(@player.state is 'still' and @player.control is on and
@player.sprite.y <= @endingPoint.y)
_renderDebugDisplay: ->
@resetDebugDisplayLayout()
if @player.debugging
@renderDebugDisplayItems((layoutX, layoutY) =>
@debugDisplay.bodyInfo(@player.sprite, layoutX, layoutY)
return
, 6)
@renderDebugDisplayItems(@player.debugTextItems)
_renderDebugOverlays: ->
if @player.debugging
@debugDisplay.body(@player.sprite)
@debugDisplay.spriteBounds(@player.sprite)
return
_renderEndingDisplay: ->
@textLayout = { y: 120, baseline: 40 }
@_addText('The End', { fontSize: fontLarge })
.onComplete.addOnce =>
@_addText('Click to play again', { fontSize: fontSmall })
@ended = yes
return
return
_shakeOnPlayerFall: ->
return no unless (
@player.nextState is 'landing' and
@player.distanceFallen() > shakeFallH
)
force = no
@camera.shake(0.02, 0.1 * Timer.SECOND, force, Camera.SHAKE_VERTICAL)
return
_toggleCameraAttachment: (attached) ->
attached ?= not @detachedCamera
if attached
@camera.follow(@player.sprite)
@player.cursors ?= @cursors
else
@camera.unfollow()
@player.cursors = null
return
_updateVolumeOnPlayerLand: ->
return no unless @player.nextState is 'landing'
# The music gets louder the higher the player gets.
volume = ((@platforms.tilemap.heightInPixels - @player.sprite.y) /
@platforms.tilemap.heightInPixels) ** 1.3
volume *= @math.clamp(@userVolume, 0, 2) # Factor in user controls.
volume = @math.clamp(volume, 0.2, 0.8)
@music.fadeTo(Timer.SECOND, volume)
return
_.extend( PlayState::,
AnimationMixin, DebugMixin, DebugDisplayMixin, TextMixin
)
PlayState
|
[
{
"context": "ct:user/#{propObj.user_id}\"\n # displayName: \"Aron\"\n jiveDisplay: [ \"inbox\" ]\n\n activityWrapper ",
"end": 3486,
"score": 0.9960063695907593,
"start": 3482,
"tag": "NAME",
"value": "Aron"
},
{
"context": "yWrapper, creds, callback\n\n# activity.title = \"${@actor} has given you props.\"\n# exports.postAction jive",
"end": 3707,
"score": 0.7636582851409912,
"start": 3701,
"tag": "USERNAME",
"value": "@actor"
}
] | applications/props/props-server/lib/activity.coffee | yingjieg/jiveapps | 13 | # Copyright 2013 Jive Software
#
# 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.
scopedClient = require "scoped-http-client"
oauth = require "oauth"
util = require './util.js'
config =
streamPath: "/gateway/api/activity/v1/update/"
inboxPath: "/gateway/api/activity/v1/updateInbox/"
signHMAC = (url, creds) ->
oauthobj = new oauth.OAuth(`undefined`, `undefined`, config.key, creds.secret, "1.0", `undefined`, "HMAC-SHA1", `undefined`)
oauthobj.signUrl url, `undefined`, `undefined`, "POST"
# activitySimple = items: [
# title: "Test activity title2"
# body: "From an external client"
# object:
# title: "object title"
# summary: "this is an object summary"
# ]
# activityComplex = items: [
# body: "From an external client"
# title: "More complex example 4"
# object:
# objectType: "article"
# title: "object title"
# summary: "${@actor} gave ${@target} props."
# mediaLink:
# mediaType: "photo"
# url: "http://apphosting.jivesoftware.com/apps/dev/props/img/trophies/captain-america-with-reflection.png"
# target:
# id: "urn:jiveObject:user/2008"
# displayName: "Aron"
# ]
exports.postAction = (jiveId, giverId, receiverId, activity, creds, callback=()->) ->
postUrl = creds.gateway + config.streamPath + jiveId + "/" + creds.id + "/" + giverId + '?deliverTo=' + receiverId
console.log("Posting prop notification to " + postUrl);
client = scopedClient.create(signHMAC(postUrl, creds))
client.header "Content-Type", "application/json"
client.header "Accept", "application/json"
client.header "X-Jive-App-Id", creds.id
client.header "Host", creds.gateway.match(/https?:\/\/(.+)/)[1]
if client.options.port
util.makePostRequest client, JSON.stringify(activity), callback
else
client.post JSON.stringify(activity), (err, resp, body) ->
callback err, resp, body
exports.postActivity = (jiveId, userId, activity, creds, callback=()->) ->
postUrl = creds.gateway + config.streamPath + jiveId + "/" + creds.id + "/" + userId
console.log("Posting prop activity to " + postUrl);
client = scopedClient.create(signHMAC(postUrl, creds))
client.header "Content-Type", "application/json"
client.header "Accept", "application/json"
client.header "X-Jive-App-Id", creds.id
client.header "Host", creds.gateway.match(/https?:\/\/(.+)/)[1]
if client.options.port
util.makePostRequest client, JSON.stringify(activity), callback
else
client.post JSON.stringify(activity), (err, resp, body) ->
callback err, resp, body
exports.postProp = (jiveId, propObj, propImageUrl, creds, callback=()->) ->
activity =
body: "${@actor} has given you props."
title: "Jive Props"
object:
objectType: "article"
title: "object title"
summary: propObj.message
mediaLink:
mediaType: "photo"
url: propImageUrl
target:
id: "urn:jiveObject:user/#{propObj.user_id}"
# displayName: "Aron"
jiveDisplay: [ "inbox" ]
activityWrapper = items: [activity]
jiveId = jiveId.replace(/^dev/, '');
exports.postActivity jiveId, propObj.user_id, activityWrapper, creds, callback
# activity.title = "${@actor} has given you props."
# exports.postAction jiveId, propObj.giver_id, propObj.user_id, activityWrapper, creds, callback
| 107815 | # Copyright 2013 Jive Software
#
# 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.
scopedClient = require "scoped-http-client"
oauth = require "oauth"
util = require './util.js'
config =
streamPath: "/gateway/api/activity/v1/update/"
inboxPath: "/gateway/api/activity/v1/updateInbox/"
signHMAC = (url, creds) ->
oauthobj = new oauth.OAuth(`undefined`, `undefined`, config.key, creds.secret, "1.0", `undefined`, "HMAC-SHA1", `undefined`)
oauthobj.signUrl url, `undefined`, `undefined`, "POST"
# activitySimple = items: [
# title: "Test activity title2"
# body: "From an external client"
# object:
# title: "object title"
# summary: "this is an object summary"
# ]
# activityComplex = items: [
# body: "From an external client"
# title: "More complex example 4"
# object:
# objectType: "article"
# title: "object title"
# summary: "${@actor} gave ${@target} props."
# mediaLink:
# mediaType: "photo"
# url: "http://apphosting.jivesoftware.com/apps/dev/props/img/trophies/captain-america-with-reflection.png"
# target:
# id: "urn:jiveObject:user/2008"
# displayName: "Aron"
# ]
exports.postAction = (jiveId, giverId, receiverId, activity, creds, callback=()->) ->
postUrl = creds.gateway + config.streamPath + jiveId + "/" + creds.id + "/" + giverId + '?deliverTo=' + receiverId
console.log("Posting prop notification to " + postUrl);
client = scopedClient.create(signHMAC(postUrl, creds))
client.header "Content-Type", "application/json"
client.header "Accept", "application/json"
client.header "X-Jive-App-Id", creds.id
client.header "Host", creds.gateway.match(/https?:\/\/(.+)/)[1]
if client.options.port
util.makePostRequest client, JSON.stringify(activity), callback
else
client.post JSON.stringify(activity), (err, resp, body) ->
callback err, resp, body
exports.postActivity = (jiveId, userId, activity, creds, callback=()->) ->
postUrl = creds.gateway + config.streamPath + jiveId + "/" + creds.id + "/" + userId
console.log("Posting prop activity to " + postUrl);
client = scopedClient.create(signHMAC(postUrl, creds))
client.header "Content-Type", "application/json"
client.header "Accept", "application/json"
client.header "X-Jive-App-Id", creds.id
client.header "Host", creds.gateway.match(/https?:\/\/(.+)/)[1]
if client.options.port
util.makePostRequest client, JSON.stringify(activity), callback
else
client.post JSON.stringify(activity), (err, resp, body) ->
callback err, resp, body
exports.postProp = (jiveId, propObj, propImageUrl, creds, callback=()->) ->
activity =
body: "${@actor} has given you props."
title: "Jive Props"
object:
objectType: "article"
title: "object title"
summary: propObj.message
mediaLink:
mediaType: "photo"
url: propImageUrl
target:
id: "urn:jiveObject:user/#{propObj.user_id}"
# displayName: "<NAME>"
jiveDisplay: [ "inbox" ]
activityWrapper = items: [activity]
jiveId = jiveId.replace(/^dev/, '');
exports.postActivity jiveId, propObj.user_id, activityWrapper, creds, callback
# activity.title = "${@actor} has given you props."
# exports.postAction jiveId, propObj.giver_id, propObj.user_id, activityWrapper, creds, callback
| true | # Copyright 2013 Jive Software
#
# 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.
scopedClient = require "scoped-http-client"
oauth = require "oauth"
util = require './util.js'
config =
streamPath: "/gateway/api/activity/v1/update/"
inboxPath: "/gateway/api/activity/v1/updateInbox/"
signHMAC = (url, creds) ->
oauthobj = new oauth.OAuth(`undefined`, `undefined`, config.key, creds.secret, "1.0", `undefined`, "HMAC-SHA1", `undefined`)
oauthobj.signUrl url, `undefined`, `undefined`, "POST"
# activitySimple = items: [
# title: "Test activity title2"
# body: "From an external client"
# object:
# title: "object title"
# summary: "this is an object summary"
# ]
# activityComplex = items: [
# body: "From an external client"
# title: "More complex example 4"
# object:
# objectType: "article"
# title: "object title"
# summary: "${@actor} gave ${@target} props."
# mediaLink:
# mediaType: "photo"
# url: "http://apphosting.jivesoftware.com/apps/dev/props/img/trophies/captain-america-with-reflection.png"
# target:
# id: "urn:jiveObject:user/2008"
# displayName: "Aron"
# ]
exports.postAction = (jiveId, giverId, receiverId, activity, creds, callback=()->) ->
postUrl = creds.gateway + config.streamPath + jiveId + "/" + creds.id + "/" + giverId + '?deliverTo=' + receiverId
console.log("Posting prop notification to " + postUrl);
client = scopedClient.create(signHMAC(postUrl, creds))
client.header "Content-Type", "application/json"
client.header "Accept", "application/json"
client.header "X-Jive-App-Id", creds.id
client.header "Host", creds.gateway.match(/https?:\/\/(.+)/)[1]
if client.options.port
util.makePostRequest client, JSON.stringify(activity), callback
else
client.post JSON.stringify(activity), (err, resp, body) ->
callback err, resp, body
exports.postActivity = (jiveId, userId, activity, creds, callback=()->) ->
postUrl = creds.gateway + config.streamPath + jiveId + "/" + creds.id + "/" + userId
console.log("Posting prop activity to " + postUrl);
client = scopedClient.create(signHMAC(postUrl, creds))
client.header "Content-Type", "application/json"
client.header "Accept", "application/json"
client.header "X-Jive-App-Id", creds.id
client.header "Host", creds.gateway.match(/https?:\/\/(.+)/)[1]
if client.options.port
util.makePostRequest client, JSON.stringify(activity), callback
else
client.post JSON.stringify(activity), (err, resp, body) ->
callback err, resp, body
exports.postProp = (jiveId, propObj, propImageUrl, creds, callback=()->) ->
activity =
body: "${@actor} has given you props."
title: "Jive Props"
object:
objectType: "article"
title: "object title"
summary: propObj.message
mediaLink:
mediaType: "photo"
url: propImageUrl
target:
id: "urn:jiveObject:user/#{propObj.user_id}"
# displayName: "PI:NAME:<NAME>END_PI"
jiveDisplay: [ "inbox" ]
activityWrapper = items: [activity]
jiveId = jiveId.replace(/^dev/, '');
exports.postActivity jiveId, propObj.user_id, activityWrapper, creds, callback
# activity.title = "${@actor} has given you props."
# exports.postAction jiveId, propObj.giver_id, propObj.user_id, activityWrapper, creds, callback
|
[
{
"context": "scription: Analytics for programmers.\nMaintainer: WakaTime <support@wakatime.com>\nLicense: BSD, see LICE",
"end": 74,
"score": 0.9873784184455872,
"start": 66,
"tag": "USERNAME",
"value": "WakaTime"
},
{
"context": "Analytics for programmers.\nMaintainer: WakaTime <support@wakatime.com>\nLicense: BSD, see LICENSE for more details.\n",
"end": 96,
"score": 0.9999260902404785,
"start": 76,
"tag": "EMAIL",
"value": "support@wakatime.com"
},
{
"context": "ify')\n url: 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py'\n request.",
"end": 12176,
"score": 0.9994254112243652,
"start": 12168,
"tag": "USERNAME",
"value": "wakatime"
},
{
"context": "ing wakatime-cli...')\n url = 'https://github.com/wakatime/wakatime/archive/master.zip'\n zipFile = __dirnam",
"end": 12922,
"score": 0.9995815753936768,
"start": 12914,
"tag": "USERNAME",
"value": "wakatime"
},
{
"context": " args.push('--no-ssl-verify')\n\n # fix for wakatime/atom-wakatime#65\n args.push('--config')\n ",
"end": 15166,
"score": 0.8614373803138733,
"start": 15158,
"tag": "USERNAME",
"value": "wakatime"
}
] | lib/wakatime.coffee | mkg20001/atom-wakatime | 0 | ###
WakaTime
Description: Analytics for programmers.
Maintainer: WakaTime <support@wakatime.com>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
###
StatusBarTileView = require './status-bar-tile-view'
Logger = require './logger'
# dependencies lazy-loaded to improve startup time
AdmZip = null
fs = null
os = null
path = null
child_process = null
request = null
rimraf = null
ini = null
# package-global attributes
log = null
packageVersion = null
lastHeartbeat = 0
lastFile = ''
lastTodayFetch = 0
fetchTodayInterval = 60000
cachedToday = ''
statusBarIcon = null
pluginReady = false
module.exports =
activate: (state) ->
log = new Logger('WakaTime')
if atom.config.get 'wakatime.debug'
log.setLevel('DEBUG')
packageVersion = atom.packages.getLoadedPackage('wakatime').metadata.version
log.debug 'Initializing WakaTime v' + packageVersion + '...'
requestIdleCallback @delayedActivate, {timeout: 10000}
delayedActivate: ->
loadDependencies()
setupConfigs()
@settingChangedObserver = atom.config.observe 'wakatime', settingChangedHandler
checkPython()
consumeStatusBar: (statusBar) ->
statusBarIcon = new StatusBarTileView()
statusBarIcon.init()
@statusBarTile = statusBar?.addRightTile(item: statusBarIcon, priority: 300)
# set status bar icon visibility
if atom.config.get 'wakatime.showStatusBarIcon'
statusBarIcon.show()
else
statusBarIcon.hide()
if pluginReady
statusBarIcon.setTitle('WakaTime ready')
statusBarIcon.setStatus(cachedToday)
deactivate: ->
@statusBarTile?.destroy()
statusBarIcon?.destroy()
@settingChangedObserver?.dispose()
checkPython = () ->
isPythonInstalled((installed) ->
if not installed
if os.type() is 'Windows_NT'
installPython(checkCLI)
else
window.alert('Please install Python (https://www.python.org/downloads/) and restart Atom to enable the WakaTime plugin.')
else
checkCLI()
)
checkCLI = () ->
if not isCLIInstalled()
installCLI(->
log.debug 'Finished installing wakatime-cli.'
finishActivation()
)
else
getLastCheckedForUpdates((lastChecked) ->
# only check for updates to wakatime-cli every 24 hours
hours = 24
currentTime = Math.round (new Date).getTime() / 1000
beenLongEnough = lastChecked + 3600 * hours < currentTime
if beenLongEnough or atom.config.get('wakatime.debug')
setLastCheckedForUpdates(currentTime)
isCLILatest((latest) ->
if not latest
installCLI(->
log.debug 'Finished installing wakatime-cli.'
finishActivation()
)
else
finishActivation()
)
else
finishActivation()
)
getLastCheckedForUpdates = (callback) ->
filePath = path.join cliFolder(), 'last-checked-for-updates'
if fs.existsSync(filePath)
fs.readFile filePath, 'utf-8', (err, contents) ->
if err?
if callback?
callback(0)
return
if contents?
try
if callback?
callback(parseInt(contents.trim(), 10) or 0)
return
if callback?
callback(0)
else
if callback?
callback(0)
setLastCheckedForUpdates = (lastChecked) ->
filePath = path.join cliFolder(), 'last-checked-for-updates'
fs.writeFile filePath, lastChecked.toString(), {encoding: 'utf-8'}, (err) ->
if err?
log.debug 'Unable to save last checked for updates timestamp.'
finishActivation = () ->
pluginReady = true
setupEventHandlers()
# set status bar icon visibility
if atom.config.get 'wakatime.showStatusBarIcon'
statusBarIcon?.show()
else
statusBarIcon?.hide()
statusBarIcon?.setTitle('WakaTime ready')
statusBarIcon?.setStatus(cachedToday)
getToday()
log.debug 'Finished initializing WakaTime.'
settingChangedHandler = (settings, initial) ->
if settings.showStatusBarIcon
statusBarIcon?.show()
else
statusBarIcon?.hide()
if atom.config.get 'wakatime.debug'
log.setLevel('DEBUG')
else
log.setLevel('INFO')
apiKey = settings.apikey
if isValidApiKey(apiKey)
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Saved in your ~/.wakatime.cfg file'
saveApiKey apiKey
else if initial
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Enter your api key...'
saveApiKey = (apiKey) ->
configFile = path.join getUserHome(), '.wakatime.cfg'
fs.readFile configFile, 'utf-8', (err, inp) ->
if err?
log.debug 'Error: could not read wakatime config file'
String::startsWith ?= (s) -> @slice(0, s.length) == s
String::endsWith ?= (s) -> s == '' or @slice(-s.length) == s
contents = []
currentSection = ''
found = false
if inp?
for line in inp.split('\n')
if line.trim().startsWith('[') and line.trim().endsWith(']')
if currentSection == 'settings' and not found
contents.push('api_key = ' + apiKey)
found = true
currentSection = line.trim().substring(1, line.trim().length - 1).toLowerCase()
contents.push(line)
else if currentSection == 'settings'
parts = line.split('=')
currentKey = parts[0].trim()
if currentKey == 'api_key'
if not found
contents.push('api_key = ' + apiKey)
found = true
else
contents.push(line)
else
contents.push(line)
if not found
if currentSection != 'settings'
contents.push('[settings]')
contents.push('api_key = ' + apiKey)
fs.writeFile configFile, contents.join('\n'), {encoding: 'utf-8'}, (err2) ->
if err2?
msg = 'Error: could not write to wakatime config file'
log.error msg
statusBarIcon?.setStatus('Error')
statusBarIcon?.setTitle(msg)
getUserHome = ->
process.env[if process.platform == 'win32' then 'USERPROFILE' else 'HOME'] || ''
loadDependencies = ->
AdmZip = require 'adm-zip'
fs = require 'fs'
os = require 'os'
path = require 'path'
child_process = require 'child_process'
request = require 'request'
rimraf = require 'rimraf'
ini = require 'ini'
setupConfigs = ->
configFile = path.join getUserHome(), '.wakatime.cfg'
fs.readFile configFile, 'utf-8', (err, configContent) ->
if err?
log.debug 'Error: could not read wakatime config file'
settingChangedHandler atom.config.get('wakatime'), true
return
commonConfigs = ini.decode configContent
if commonConfigs? and commonConfigs.settings? and isValidApiKey(commonConfigs.settings.api_key)
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Saved in your ~/.wakatime.cfg file'
else
settingChangedHandler atom.config.get('wakatime'), true
isValidApiKey = (key) ->
if not key?
return false
re = new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'i')
return re.test key
enoughTimePassed = (time) ->
return lastHeartbeat + 120000 < time
setupEventHandlers = (callback) ->
atom.workspace.observeTextEditors (editor) ->
try
buffer = editor.getBuffer()
buffer.onDidSave (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno, true)
buffer.onDidChange (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno)
editor.onDidChangeCursorPosition (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno)
if callback?
callback()
isPythonInstalled = (callback) ->
pythonLocation((result) ->
callback(result?)
)
pythonLocation = (callback) ->
if global.cachedPythonLocation?
callback(global.cachedPythonLocation)
return
locations = [
__dirname + path.sep + 'python' + path.sep + 'pythonw',
'python3',
'pythonw',
'python',
'/usr/local/bin/python3',
'/usr/local/bin/python',
'/usr/bin/python3',
'/usr/bin/python',
]
i = 39
while i >= 27
if i < 30 or i > 32
locations.push '\\python' + i + '\\pythonw'
locations.push '\\Python' + i + '\\pythonw'
i--
findPython(locations, callback)
findPython = (locations, callback) ->
if locations.length is 0
callback(null)
return
binary = locations.shift()
log.debug 'Looking for python at: ' + binary
args = ['--version']
child_process.execFile(binary, args, (error, stdout, stderr) ->
output = stdout.toString() + stderr.toString()
if not error and isSupportedPythonVersion(binary, output)
global.cachedPythonLocation = binary
log.debug 'Valid python version: ' + output
callback(binary)
else
log.debug 'Invalid python version: ' + output
findPython(locations, callback)
)
isSupportedPythonVersion = (binary, versionString) ->
# Only support Python 2.7+ because 2.6 has SSL problems
if binary.toLowerCase().includes('python26')
return false
anaconda = /continuum|anaconda/gi
isAnaconda = not not anaconda.test(versionString)
re = /python\s+(\d+)\.(\d+)\.(\d+)\s/gi
ver = re.exec(versionString)
if not ver?
return isAnaconda
# Older Ananconda python distributions not supported
if isAnaconda
if parseInt(ver[1]) >= 3 and parseInt(ver[2]) >= 5
return true
else
# Only support Python 2.7+ because 2.6 has SSL problems
if parseInt(ver[1]) >= 2 or parseInt(ver[2]) >= 7
return true
return false
installPython = (callback) ->
pyVer = '3.5.2'
arch = 'win32'
if os.arch().indexOf('x64') > -1
arch = 'amd64'
url = 'https://www.python.org/ftp/python/' + pyVer + '/python-' + pyVer + '-embed-' + arch + '.zip'
log.debug 'downloading python...'
statusBarIcon?.setStatus('downloading python...')
zipFile = __dirname + path.sep + 'python.zip'
downloadFile(url, zipFile, ->
log.debug 'extracting python...'
statusBarIcon?.setStatus('extracting python...')
unzip(zipFile, __dirname + path.sep + 'python', ->
fs.unlink(zipFile, (e) ->
if e?
log.warn e
log.debug 'Finished installing python.'
if callback?
callback()
)
)
)
isCLIInstalled = () ->
return fs.existsSync(cliLocation())
isCLILatest = (callback) ->
pythonLocation((python) ->
if python?
args = [cliLocation(), '--version']
child_process.execFile(python, args, (error, stdout, stderr) ->
if not error?
currentVersion = stderr.trim()
log.debug 'Current wakatime-cli version is ' + currentVersion
log.debug 'Checking for updates to wakatime-cli...'
getLatestCliVersion((latestVersion) ->
if currentVersion == latestVersion
log.debug 'wakatime-cli is up to date.'
if callback?
callback(true)
else
if latestVersion?
log.debug 'Found an updated wakatime-cli v' + latestVersion
if callback?
callback(false)
else
log.debug 'Unable to find latest wakatime-cli version from GitHub.'
if callback?
callback(true)
)
else
if callback?
callback(false)
)
else
if callback?
callback(false)
)
getLatestCliVersion = (callback) ->
options =
strictSSL: not atom.config.get('wakatime.disableSSLCertVerify')
url: 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py'
request.get(options, (error, response, body) ->
version = null
if !error and response.statusCode == 200
re = new RegExp(/__version_info__ = \('([0-9]+)', '([0-9]+)', '([0-9]+)'\)/g)
for line in body.split('\n')
match = re.exec(line)
if match?
version = match[1] + '.' + match[2] + '.' + match[3]
if callback?
callback(version)
)
cliLocation = () ->
return path.join cliFolder(), 'cli.py'
cliFolder = () ->
dir = path.join __dirname, 'wakatime-master', 'wakatime'
return dir
installCLI = (callback) ->
log.debug 'Downloading wakatime-cli...'
statusBarIcon?.setStatus('downloading wakatime-cli...')
url = 'https://github.com/wakatime/wakatime/archive/master.zip'
zipFile = __dirname + path.sep + 'wakatime-master.zip'
downloadFile(url, zipFile, ->
extractCLI(zipFile, callback)
)
extractCLI = (zipFile, callback) ->
log.debug 'Extracting wakatime-master.zip file...'
statusBarIcon?.setStatus('extracting wakatime-cli...')
removeCLI(->
unzip(zipFile, __dirname, callback)
)
removeCLI = (callback) ->
if fs.existsSync(__dirname + path.sep + 'wakatime-master')
try
rimraf(__dirname + path.sep + 'wakatime-master', ->
if callback?
callback()
)
catch e
log.warn e
if callback?
callback()
else
if callback?
callback()
downloadFile = (url, outputFile, callback) ->
options =
strictSSL: not atom.config.get('wakatime.disableSSLCertVerify')
url: url
r = request(options)
out = fs.createWriteStream(outputFile)
r.pipe(out)
r.on('end', ->
out.on('finish', ->
if callback?
callback()
)
)
unzip = (file, outputDir, callback) ->
if fs.existsSync(file)
try
zip = new AdmZip(file)
zip.extractAllTo(outputDir, true)
catch e
log.warn e
finally
fs.unlink(file, (err) ->
if err?
log.warn err
if callback?
callback()
)
sendHeartbeat = (file, lineno, isWrite) ->
if (not file.path? or file.path is undefined) and (not file.getPath? or file.getPath() is undefined)
log.debug 'Skipping file because path does not exist: ' + file.path
return
currentFile = file.path or file.getPath()
if fileIsIgnored(currentFile)
log.debug 'Skipping file because path matches ignore pattern: ' + currentFile
return
time = Date.now()
if isWrite or enoughTimePassed(time) or lastFile isnt currentFile
pythonLocation (python) ->
return unless python?
args = [cliLocation(), '--file', currentFile, '--plugin', 'atom-wakatime/' + packageVersion]
if isWrite
args.push('--write')
if lineno?
args.push('--lineno')
args.push(lineno)
if atom.config.get 'wakatime.debug'
args.push('--verbose')
if atom.config.get 'wakatime.disableSSLCertVerify'
args.push('--no-ssl-verify')
# fix for wakatime/atom-wakatime#65
args.push('--config')
args.push(path.join getUserHome(), '.wakatime.cfg')
if atom.project.contains(currentFile)
for rootDir in atom.project.rootDirectories
realPath = rootDir.realPath
if currentFile.indexOf(realPath) > -1
args.push('--alternate-project')
args.push(path.basename(realPath))
break
lastHeartbeat = time
lastFile = currentFile
log.debug python + ' ' + args.join(' ')
executeHeartbeatProcess python, args, 0
getToday()
executeHeartbeatProcess = (python, args, tries) ->
max_retries = 5
try
proc = child_process.execFile(python, args, (error, stdout, stderr) ->
if error?
if stderr? and stderr != ''
log.warn stderr
if stdout? and stdout != ''
log.warn stdout
if proc.exitCode == 102
msg = null
status = null
title = 'WakaTime Offline, coding activity will sync when online.'
else if proc.exitCode == 103
msg = 'An error occured while parsing ~/.wakatime.cfg. Check ~/.wakatime.log for more info.'
status = 'Error'
title = msg
else if proc.exitCode == 104
msg = 'Invalid API Key. Make sure your API Key is correct!'
status = 'Error'
title = msg
else
msg = error
status = 'Error'
title = 'Unknown Error (' + proc.exitCode + '); Check your Dev Console and ~/.wakatime.log for more info.'
if msg?
log.warn msg
statusBarIcon?.setStatus(status)
statusBarIcon?.setTitle(title)
else
statusBarIcon?.setStatus(cachedToday)
today = new Date()
statusBarIcon?.setTitle('Last heartbeat sent ' + formatDate(today))
)
catch e
tries++
retry_in = 2
if tries < max_retries
log.debug 'Failed to send heartbeat when executing wakatime-cli background process, will retry in ' + retry_in + ' seconds...'
setTimeout ->
executeHeartbeatProcess(python, args, tries)
, retry_in * 1000
else
log.error 'Failed to send heartbeat when executing wakatime-cli background process.'
throw e
getToday = () ->
cutoff = Date.now() - fetchTodayInterval
if lastTodayFetch > cutoff
return
lastTodayFetch = Date.now()
pythonLocation (python) ->
return unless python?
args = [cliLocation(), '--today', '--plugin', 'atom-wakatime/' + packageVersion]
if atom.config.get 'wakatime.disableSSLCertVerify'
args.push('--no-ssl-verify')
args.push('--config')
args.push(path.join getUserHome(), '.wakatime.cfg')
try
proc = child_process.execFile(python, args, (error, stdout, stderr) ->
if error?
if stderr? and stderr != ''
log.debug stderr
if stdout? and stdout != ''
log.debug stderr
else
cachedToday = 'Today: ' + stdout
statusBarIcon?.setStatus(cachedToday, true)
)
catch e
log.debug e
fileIsIgnored = (file) ->
if endsWith(file, 'COMMIT_EDITMSG') or endsWith(file, 'PULLREQ_EDITMSG') or endsWith(file, 'MERGE_MSG') or endsWith(file, 'TAG_EDITMSG')
return true
patterns = atom.config.get('wakatime.ignore')
if not patterns?
return true
ignore = false
for pattern in patterns
re = new RegExp(pattern, 'gi')
if re.test(file)
ignore = true
break
return ignore
endsWith = (str, suffix) ->
if str? and suffix?
return str.indexOf(suffix, str.length - suffix.length) != -1
return false
formatDate = (date) ->
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]
ampm = 'AM'
hour = date.getHours()
if (hour > 11)
ampm = 'PM'
hour = hour - 12
if (hour == 0)
hour = 12
minute = date.getMinutes()
if (minute < 10)
minute = '0' + minute
return months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hour + ':' + minute + ' ' + ampm
debug = (callback) ->
if fs.existsSync(__dirname + path.sep + 'wakatime-master')
try
rimraf(__dirname + path.sep + 'wakatime-master', ->
if callback?
callback()
)
catch e
log.warn e
if callback?
callback()
else
if callback?
callback()
| 218431 | ###
WakaTime
Description: Analytics for programmers.
Maintainer: WakaTime <<EMAIL>>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
###
StatusBarTileView = require './status-bar-tile-view'
Logger = require './logger'
# dependencies lazy-loaded to improve startup time
AdmZip = null
fs = null
os = null
path = null
child_process = null
request = null
rimraf = null
ini = null
# package-global attributes
log = null
packageVersion = null
lastHeartbeat = 0
lastFile = ''
lastTodayFetch = 0
fetchTodayInterval = 60000
cachedToday = ''
statusBarIcon = null
pluginReady = false
module.exports =
activate: (state) ->
log = new Logger('WakaTime')
if atom.config.get 'wakatime.debug'
log.setLevel('DEBUG')
packageVersion = atom.packages.getLoadedPackage('wakatime').metadata.version
log.debug 'Initializing WakaTime v' + packageVersion + '...'
requestIdleCallback @delayedActivate, {timeout: 10000}
delayedActivate: ->
loadDependencies()
setupConfigs()
@settingChangedObserver = atom.config.observe 'wakatime', settingChangedHandler
checkPython()
consumeStatusBar: (statusBar) ->
statusBarIcon = new StatusBarTileView()
statusBarIcon.init()
@statusBarTile = statusBar?.addRightTile(item: statusBarIcon, priority: 300)
# set status bar icon visibility
if atom.config.get 'wakatime.showStatusBarIcon'
statusBarIcon.show()
else
statusBarIcon.hide()
if pluginReady
statusBarIcon.setTitle('WakaTime ready')
statusBarIcon.setStatus(cachedToday)
deactivate: ->
@statusBarTile?.destroy()
statusBarIcon?.destroy()
@settingChangedObserver?.dispose()
checkPython = () ->
isPythonInstalled((installed) ->
if not installed
if os.type() is 'Windows_NT'
installPython(checkCLI)
else
window.alert('Please install Python (https://www.python.org/downloads/) and restart Atom to enable the WakaTime plugin.')
else
checkCLI()
)
checkCLI = () ->
if not isCLIInstalled()
installCLI(->
log.debug 'Finished installing wakatime-cli.'
finishActivation()
)
else
getLastCheckedForUpdates((lastChecked) ->
# only check for updates to wakatime-cli every 24 hours
hours = 24
currentTime = Math.round (new Date).getTime() / 1000
beenLongEnough = lastChecked + 3600 * hours < currentTime
if beenLongEnough or atom.config.get('wakatime.debug')
setLastCheckedForUpdates(currentTime)
isCLILatest((latest) ->
if not latest
installCLI(->
log.debug 'Finished installing wakatime-cli.'
finishActivation()
)
else
finishActivation()
)
else
finishActivation()
)
getLastCheckedForUpdates = (callback) ->
filePath = path.join cliFolder(), 'last-checked-for-updates'
if fs.existsSync(filePath)
fs.readFile filePath, 'utf-8', (err, contents) ->
if err?
if callback?
callback(0)
return
if contents?
try
if callback?
callback(parseInt(contents.trim(), 10) or 0)
return
if callback?
callback(0)
else
if callback?
callback(0)
setLastCheckedForUpdates = (lastChecked) ->
filePath = path.join cliFolder(), 'last-checked-for-updates'
fs.writeFile filePath, lastChecked.toString(), {encoding: 'utf-8'}, (err) ->
if err?
log.debug 'Unable to save last checked for updates timestamp.'
finishActivation = () ->
pluginReady = true
setupEventHandlers()
# set status bar icon visibility
if atom.config.get 'wakatime.showStatusBarIcon'
statusBarIcon?.show()
else
statusBarIcon?.hide()
statusBarIcon?.setTitle('WakaTime ready')
statusBarIcon?.setStatus(cachedToday)
getToday()
log.debug 'Finished initializing WakaTime.'
settingChangedHandler = (settings, initial) ->
if settings.showStatusBarIcon
statusBarIcon?.show()
else
statusBarIcon?.hide()
if atom.config.get 'wakatime.debug'
log.setLevel('DEBUG')
else
log.setLevel('INFO')
apiKey = settings.apikey
if isValidApiKey(apiKey)
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Saved in your ~/.wakatime.cfg file'
saveApiKey apiKey
else if initial
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Enter your api key...'
saveApiKey = (apiKey) ->
configFile = path.join getUserHome(), '.wakatime.cfg'
fs.readFile configFile, 'utf-8', (err, inp) ->
if err?
log.debug 'Error: could not read wakatime config file'
String::startsWith ?= (s) -> @slice(0, s.length) == s
String::endsWith ?= (s) -> s == '' or @slice(-s.length) == s
contents = []
currentSection = ''
found = false
if inp?
for line in inp.split('\n')
if line.trim().startsWith('[') and line.trim().endsWith(']')
if currentSection == 'settings' and not found
contents.push('api_key = ' + apiKey)
found = true
currentSection = line.trim().substring(1, line.trim().length - 1).toLowerCase()
contents.push(line)
else if currentSection == 'settings'
parts = line.split('=')
currentKey = parts[0].trim()
if currentKey == 'api_key'
if not found
contents.push('api_key = ' + apiKey)
found = true
else
contents.push(line)
else
contents.push(line)
if not found
if currentSection != 'settings'
contents.push('[settings]')
contents.push('api_key = ' + apiKey)
fs.writeFile configFile, contents.join('\n'), {encoding: 'utf-8'}, (err2) ->
if err2?
msg = 'Error: could not write to wakatime config file'
log.error msg
statusBarIcon?.setStatus('Error')
statusBarIcon?.setTitle(msg)
getUserHome = ->
process.env[if process.platform == 'win32' then 'USERPROFILE' else 'HOME'] || ''
loadDependencies = ->
AdmZip = require 'adm-zip'
fs = require 'fs'
os = require 'os'
path = require 'path'
child_process = require 'child_process'
request = require 'request'
rimraf = require 'rimraf'
ini = require 'ini'
setupConfigs = ->
configFile = path.join getUserHome(), '.wakatime.cfg'
fs.readFile configFile, 'utf-8', (err, configContent) ->
if err?
log.debug 'Error: could not read wakatime config file'
settingChangedHandler atom.config.get('wakatime'), true
return
commonConfigs = ini.decode configContent
if commonConfigs? and commonConfigs.settings? and isValidApiKey(commonConfigs.settings.api_key)
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Saved in your ~/.wakatime.cfg file'
else
settingChangedHandler atom.config.get('wakatime'), true
isValidApiKey = (key) ->
if not key?
return false
re = new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'i')
return re.test key
enoughTimePassed = (time) ->
return lastHeartbeat + 120000 < time
setupEventHandlers = (callback) ->
atom.workspace.observeTextEditors (editor) ->
try
buffer = editor.getBuffer()
buffer.onDidSave (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno, true)
buffer.onDidChange (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno)
editor.onDidChangeCursorPosition (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno)
if callback?
callback()
isPythonInstalled = (callback) ->
pythonLocation((result) ->
callback(result?)
)
pythonLocation = (callback) ->
if global.cachedPythonLocation?
callback(global.cachedPythonLocation)
return
locations = [
__dirname + path.sep + 'python' + path.sep + 'pythonw',
'python3',
'pythonw',
'python',
'/usr/local/bin/python3',
'/usr/local/bin/python',
'/usr/bin/python3',
'/usr/bin/python',
]
i = 39
while i >= 27
if i < 30 or i > 32
locations.push '\\python' + i + '\\pythonw'
locations.push '\\Python' + i + '\\pythonw'
i--
findPython(locations, callback)
findPython = (locations, callback) ->
if locations.length is 0
callback(null)
return
binary = locations.shift()
log.debug 'Looking for python at: ' + binary
args = ['--version']
child_process.execFile(binary, args, (error, stdout, stderr) ->
output = stdout.toString() + stderr.toString()
if not error and isSupportedPythonVersion(binary, output)
global.cachedPythonLocation = binary
log.debug 'Valid python version: ' + output
callback(binary)
else
log.debug 'Invalid python version: ' + output
findPython(locations, callback)
)
isSupportedPythonVersion = (binary, versionString) ->
# Only support Python 2.7+ because 2.6 has SSL problems
if binary.toLowerCase().includes('python26')
return false
anaconda = /continuum|anaconda/gi
isAnaconda = not not anaconda.test(versionString)
re = /python\s+(\d+)\.(\d+)\.(\d+)\s/gi
ver = re.exec(versionString)
if not ver?
return isAnaconda
# Older Ananconda python distributions not supported
if isAnaconda
if parseInt(ver[1]) >= 3 and parseInt(ver[2]) >= 5
return true
else
# Only support Python 2.7+ because 2.6 has SSL problems
if parseInt(ver[1]) >= 2 or parseInt(ver[2]) >= 7
return true
return false
installPython = (callback) ->
pyVer = '3.5.2'
arch = 'win32'
if os.arch().indexOf('x64') > -1
arch = 'amd64'
url = 'https://www.python.org/ftp/python/' + pyVer + '/python-' + pyVer + '-embed-' + arch + '.zip'
log.debug 'downloading python...'
statusBarIcon?.setStatus('downloading python...')
zipFile = __dirname + path.sep + 'python.zip'
downloadFile(url, zipFile, ->
log.debug 'extracting python...'
statusBarIcon?.setStatus('extracting python...')
unzip(zipFile, __dirname + path.sep + 'python', ->
fs.unlink(zipFile, (e) ->
if e?
log.warn e
log.debug 'Finished installing python.'
if callback?
callback()
)
)
)
isCLIInstalled = () ->
return fs.existsSync(cliLocation())
isCLILatest = (callback) ->
pythonLocation((python) ->
if python?
args = [cliLocation(), '--version']
child_process.execFile(python, args, (error, stdout, stderr) ->
if not error?
currentVersion = stderr.trim()
log.debug 'Current wakatime-cli version is ' + currentVersion
log.debug 'Checking for updates to wakatime-cli...'
getLatestCliVersion((latestVersion) ->
if currentVersion == latestVersion
log.debug 'wakatime-cli is up to date.'
if callback?
callback(true)
else
if latestVersion?
log.debug 'Found an updated wakatime-cli v' + latestVersion
if callback?
callback(false)
else
log.debug 'Unable to find latest wakatime-cli version from GitHub.'
if callback?
callback(true)
)
else
if callback?
callback(false)
)
else
if callback?
callback(false)
)
getLatestCliVersion = (callback) ->
options =
strictSSL: not atom.config.get('wakatime.disableSSLCertVerify')
url: 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py'
request.get(options, (error, response, body) ->
version = null
if !error and response.statusCode == 200
re = new RegExp(/__version_info__ = \('([0-9]+)', '([0-9]+)', '([0-9]+)'\)/g)
for line in body.split('\n')
match = re.exec(line)
if match?
version = match[1] + '.' + match[2] + '.' + match[3]
if callback?
callback(version)
)
cliLocation = () ->
return path.join cliFolder(), 'cli.py'
cliFolder = () ->
dir = path.join __dirname, 'wakatime-master', 'wakatime'
return dir
installCLI = (callback) ->
log.debug 'Downloading wakatime-cli...'
statusBarIcon?.setStatus('downloading wakatime-cli...')
url = 'https://github.com/wakatime/wakatime/archive/master.zip'
zipFile = __dirname + path.sep + 'wakatime-master.zip'
downloadFile(url, zipFile, ->
extractCLI(zipFile, callback)
)
extractCLI = (zipFile, callback) ->
log.debug 'Extracting wakatime-master.zip file...'
statusBarIcon?.setStatus('extracting wakatime-cli...')
removeCLI(->
unzip(zipFile, __dirname, callback)
)
removeCLI = (callback) ->
if fs.existsSync(__dirname + path.sep + 'wakatime-master')
try
rimraf(__dirname + path.sep + 'wakatime-master', ->
if callback?
callback()
)
catch e
log.warn e
if callback?
callback()
else
if callback?
callback()
downloadFile = (url, outputFile, callback) ->
options =
strictSSL: not atom.config.get('wakatime.disableSSLCertVerify')
url: url
r = request(options)
out = fs.createWriteStream(outputFile)
r.pipe(out)
r.on('end', ->
out.on('finish', ->
if callback?
callback()
)
)
unzip = (file, outputDir, callback) ->
if fs.existsSync(file)
try
zip = new AdmZip(file)
zip.extractAllTo(outputDir, true)
catch e
log.warn e
finally
fs.unlink(file, (err) ->
if err?
log.warn err
if callback?
callback()
)
sendHeartbeat = (file, lineno, isWrite) ->
if (not file.path? or file.path is undefined) and (not file.getPath? or file.getPath() is undefined)
log.debug 'Skipping file because path does not exist: ' + file.path
return
currentFile = file.path or file.getPath()
if fileIsIgnored(currentFile)
log.debug 'Skipping file because path matches ignore pattern: ' + currentFile
return
time = Date.now()
if isWrite or enoughTimePassed(time) or lastFile isnt currentFile
pythonLocation (python) ->
return unless python?
args = [cliLocation(), '--file', currentFile, '--plugin', 'atom-wakatime/' + packageVersion]
if isWrite
args.push('--write')
if lineno?
args.push('--lineno')
args.push(lineno)
if atom.config.get 'wakatime.debug'
args.push('--verbose')
if atom.config.get 'wakatime.disableSSLCertVerify'
args.push('--no-ssl-verify')
# fix for wakatime/atom-wakatime#65
args.push('--config')
args.push(path.join getUserHome(), '.wakatime.cfg')
if atom.project.contains(currentFile)
for rootDir in atom.project.rootDirectories
realPath = rootDir.realPath
if currentFile.indexOf(realPath) > -1
args.push('--alternate-project')
args.push(path.basename(realPath))
break
lastHeartbeat = time
lastFile = currentFile
log.debug python + ' ' + args.join(' ')
executeHeartbeatProcess python, args, 0
getToday()
executeHeartbeatProcess = (python, args, tries) ->
max_retries = 5
try
proc = child_process.execFile(python, args, (error, stdout, stderr) ->
if error?
if stderr? and stderr != ''
log.warn stderr
if stdout? and stdout != ''
log.warn stdout
if proc.exitCode == 102
msg = null
status = null
title = 'WakaTime Offline, coding activity will sync when online.'
else if proc.exitCode == 103
msg = 'An error occured while parsing ~/.wakatime.cfg. Check ~/.wakatime.log for more info.'
status = 'Error'
title = msg
else if proc.exitCode == 104
msg = 'Invalid API Key. Make sure your API Key is correct!'
status = 'Error'
title = msg
else
msg = error
status = 'Error'
title = 'Unknown Error (' + proc.exitCode + '); Check your Dev Console and ~/.wakatime.log for more info.'
if msg?
log.warn msg
statusBarIcon?.setStatus(status)
statusBarIcon?.setTitle(title)
else
statusBarIcon?.setStatus(cachedToday)
today = new Date()
statusBarIcon?.setTitle('Last heartbeat sent ' + formatDate(today))
)
catch e
tries++
retry_in = 2
if tries < max_retries
log.debug 'Failed to send heartbeat when executing wakatime-cli background process, will retry in ' + retry_in + ' seconds...'
setTimeout ->
executeHeartbeatProcess(python, args, tries)
, retry_in * 1000
else
log.error 'Failed to send heartbeat when executing wakatime-cli background process.'
throw e
getToday = () ->
cutoff = Date.now() - fetchTodayInterval
if lastTodayFetch > cutoff
return
lastTodayFetch = Date.now()
pythonLocation (python) ->
return unless python?
args = [cliLocation(), '--today', '--plugin', 'atom-wakatime/' + packageVersion]
if atom.config.get 'wakatime.disableSSLCertVerify'
args.push('--no-ssl-verify')
args.push('--config')
args.push(path.join getUserHome(), '.wakatime.cfg')
try
proc = child_process.execFile(python, args, (error, stdout, stderr) ->
if error?
if stderr? and stderr != ''
log.debug stderr
if stdout? and stdout != ''
log.debug stderr
else
cachedToday = 'Today: ' + stdout
statusBarIcon?.setStatus(cachedToday, true)
)
catch e
log.debug e
fileIsIgnored = (file) ->
if endsWith(file, 'COMMIT_EDITMSG') or endsWith(file, 'PULLREQ_EDITMSG') or endsWith(file, 'MERGE_MSG') or endsWith(file, 'TAG_EDITMSG')
return true
patterns = atom.config.get('wakatime.ignore')
if not patterns?
return true
ignore = false
for pattern in patterns
re = new RegExp(pattern, 'gi')
if re.test(file)
ignore = true
break
return ignore
endsWith = (str, suffix) ->
if str? and suffix?
return str.indexOf(suffix, str.length - suffix.length) != -1
return false
formatDate = (date) ->
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]
ampm = 'AM'
hour = date.getHours()
if (hour > 11)
ampm = 'PM'
hour = hour - 12
if (hour == 0)
hour = 12
minute = date.getMinutes()
if (minute < 10)
minute = '0' + minute
return months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hour + ':' + minute + ' ' + ampm
debug = (callback) ->
if fs.existsSync(__dirname + path.sep + 'wakatime-master')
try
rimraf(__dirname + path.sep + 'wakatime-master', ->
if callback?
callback()
)
catch e
log.warn e
if callback?
callback()
else
if callback?
callback()
| true | ###
WakaTime
Description: Analytics for programmers.
Maintainer: WakaTime <PI:EMAIL:<EMAIL>END_PI>
License: BSD, see LICENSE for more details.
Website: https://wakatime.com/
###
StatusBarTileView = require './status-bar-tile-view'
Logger = require './logger'
# dependencies lazy-loaded to improve startup time
AdmZip = null
fs = null
os = null
path = null
child_process = null
request = null
rimraf = null
ini = null
# package-global attributes
log = null
packageVersion = null
lastHeartbeat = 0
lastFile = ''
lastTodayFetch = 0
fetchTodayInterval = 60000
cachedToday = ''
statusBarIcon = null
pluginReady = false
module.exports =
activate: (state) ->
log = new Logger('WakaTime')
if atom.config.get 'wakatime.debug'
log.setLevel('DEBUG')
packageVersion = atom.packages.getLoadedPackage('wakatime').metadata.version
log.debug 'Initializing WakaTime v' + packageVersion + '...'
requestIdleCallback @delayedActivate, {timeout: 10000}
delayedActivate: ->
loadDependencies()
setupConfigs()
@settingChangedObserver = atom.config.observe 'wakatime', settingChangedHandler
checkPython()
consumeStatusBar: (statusBar) ->
statusBarIcon = new StatusBarTileView()
statusBarIcon.init()
@statusBarTile = statusBar?.addRightTile(item: statusBarIcon, priority: 300)
# set status bar icon visibility
if atom.config.get 'wakatime.showStatusBarIcon'
statusBarIcon.show()
else
statusBarIcon.hide()
if pluginReady
statusBarIcon.setTitle('WakaTime ready')
statusBarIcon.setStatus(cachedToday)
deactivate: ->
@statusBarTile?.destroy()
statusBarIcon?.destroy()
@settingChangedObserver?.dispose()
checkPython = () ->
isPythonInstalled((installed) ->
if not installed
if os.type() is 'Windows_NT'
installPython(checkCLI)
else
window.alert('Please install Python (https://www.python.org/downloads/) and restart Atom to enable the WakaTime plugin.')
else
checkCLI()
)
checkCLI = () ->
if not isCLIInstalled()
installCLI(->
log.debug 'Finished installing wakatime-cli.'
finishActivation()
)
else
getLastCheckedForUpdates((lastChecked) ->
# only check for updates to wakatime-cli every 24 hours
hours = 24
currentTime = Math.round (new Date).getTime() / 1000
beenLongEnough = lastChecked + 3600 * hours < currentTime
if beenLongEnough or atom.config.get('wakatime.debug')
setLastCheckedForUpdates(currentTime)
isCLILatest((latest) ->
if not latest
installCLI(->
log.debug 'Finished installing wakatime-cli.'
finishActivation()
)
else
finishActivation()
)
else
finishActivation()
)
getLastCheckedForUpdates = (callback) ->
filePath = path.join cliFolder(), 'last-checked-for-updates'
if fs.existsSync(filePath)
fs.readFile filePath, 'utf-8', (err, contents) ->
if err?
if callback?
callback(0)
return
if contents?
try
if callback?
callback(parseInt(contents.trim(), 10) or 0)
return
if callback?
callback(0)
else
if callback?
callback(0)
setLastCheckedForUpdates = (lastChecked) ->
filePath = path.join cliFolder(), 'last-checked-for-updates'
fs.writeFile filePath, lastChecked.toString(), {encoding: 'utf-8'}, (err) ->
if err?
log.debug 'Unable to save last checked for updates timestamp.'
finishActivation = () ->
pluginReady = true
setupEventHandlers()
# set status bar icon visibility
if atom.config.get 'wakatime.showStatusBarIcon'
statusBarIcon?.show()
else
statusBarIcon?.hide()
statusBarIcon?.setTitle('WakaTime ready')
statusBarIcon?.setStatus(cachedToday)
getToday()
log.debug 'Finished initializing WakaTime.'
settingChangedHandler = (settings, initial) ->
if settings.showStatusBarIcon
statusBarIcon?.show()
else
statusBarIcon?.hide()
if atom.config.get 'wakatime.debug'
log.setLevel('DEBUG')
else
log.setLevel('INFO')
apiKey = settings.apikey
if isValidApiKey(apiKey)
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Saved in your ~/.wakatime.cfg file'
saveApiKey apiKey
else if initial
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Enter your api key...'
saveApiKey = (apiKey) ->
configFile = path.join getUserHome(), '.wakatime.cfg'
fs.readFile configFile, 'utf-8', (err, inp) ->
if err?
log.debug 'Error: could not read wakatime config file'
String::startsWith ?= (s) -> @slice(0, s.length) == s
String::endsWith ?= (s) -> s == '' or @slice(-s.length) == s
contents = []
currentSection = ''
found = false
if inp?
for line in inp.split('\n')
if line.trim().startsWith('[') and line.trim().endsWith(']')
if currentSection == 'settings' and not found
contents.push('api_key = ' + apiKey)
found = true
currentSection = line.trim().substring(1, line.trim().length - 1).toLowerCase()
contents.push(line)
else if currentSection == 'settings'
parts = line.split('=')
currentKey = parts[0].trim()
if currentKey == 'api_key'
if not found
contents.push('api_key = ' + apiKey)
found = true
else
contents.push(line)
else
contents.push(line)
if not found
if currentSection != 'settings'
contents.push('[settings]')
contents.push('api_key = ' + apiKey)
fs.writeFile configFile, contents.join('\n'), {encoding: 'utf-8'}, (err2) ->
if err2?
msg = 'Error: could not write to wakatime config file'
log.error msg
statusBarIcon?.setStatus('Error')
statusBarIcon?.setTitle(msg)
getUserHome = ->
process.env[if process.platform == 'win32' then 'USERPROFILE' else 'HOME'] || ''
loadDependencies = ->
AdmZip = require 'adm-zip'
fs = require 'fs'
os = require 'os'
path = require 'path'
child_process = require 'child_process'
request = require 'request'
rimraf = require 'rimraf'
ini = require 'ini'
setupConfigs = ->
configFile = path.join getUserHome(), '.wakatime.cfg'
fs.readFile configFile, 'utf-8', (err, configContent) ->
if err?
log.debug 'Error: could not read wakatime config file'
settingChangedHandler atom.config.get('wakatime'), true
return
commonConfigs = ini.decode configContent
if commonConfigs? and commonConfigs.settings? and isValidApiKey(commonConfigs.settings.api_key)
atom.config.set 'wakatime.apikey', '' # clear setting so it updates in UI
atom.config.set 'wakatime.apikey', 'Saved in your ~/.wakatime.cfg file'
else
settingChangedHandler atom.config.get('wakatime'), true
isValidApiKey = (key) ->
if not key?
return false
re = new RegExp('^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$', 'i')
return re.test key
enoughTimePassed = (time) ->
return lastHeartbeat + 120000 < time
setupEventHandlers = (callback) ->
atom.workspace.observeTextEditors (editor) ->
try
buffer = editor.getBuffer()
buffer.onDidSave (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno, true)
buffer.onDidChange (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno)
editor.onDidChangeCursorPosition (e) ->
file = buffer.file
if file? and file
lineno = null
if editor.cursors.length > 0
lineno = editor.cursors[0].getCurrentLineBufferRange().end.row + 1
sendHeartbeat(file, lineno)
if callback?
callback()
isPythonInstalled = (callback) ->
pythonLocation((result) ->
callback(result?)
)
pythonLocation = (callback) ->
if global.cachedPythonLocation?
callback(global.cachedPythonLocation)
return
locations = [
__dirname + path.sep + 'python' + path.sep + 'pythonw',
'python3',
'pythonw',
'python',
'/usr/local/bin/python3',
'/usr/local/bin/python',
'/usr/bin/python3',
'/usr/bin/python',
]
i = 39
while i >= 27
if i < 30 or i > 32
locations.push '\\python' + i + '\\pythonw'
locations.push '\\Python' + i + '\\pythonw'
i--
findPython(locations, callback)
findPython = (locations, callback) ->
if locations.length is 0
callback(null)
return
binary = locations.shift()
log.debug 'Looking for python at: ' + binary
args = ['--version']
child_process.execFile(binary, args, (error, stdout, stderr) ->
output = stdout.toString() + stderr.toString()
if not error and isSupportedPythonVersion(binary, output)
global.cachedPythonLocation = binary
log.debug 'Valid python version: ' + output
callback(binary)
else
log.debug 'Invalid python version: ' + output
findPython(locations, callback)
)
isSupportedPythonVersion = (binary, versionString) ->
# Only support Python 2.7+ because 2.6 has SSL problems
if binary.toLowerCase().includes('python26')
return false
anaconda = /continuum|anaconda/gi
isAnaconda = not not anaconda.test(versionString)
re = /python\s+(\d+)\.(\d+)\.(\d+)\s/gi
ver = re.exec(versionString)
if not ver?
return isAnaconda
# Older Ananconda python distributions not supported
if isAnaconda
if parseInt(ver[1]) >= 3 and parseInt(ver[2]) >= 5
return true
else
# Only support Python 2.7+ because 2.6 has SSL problems
if parseInt(ver[1]) >= 2 or parseInt(ver[2]) >= 7
return true
return false
installPython = (callback) ->
pyVer = '3.5.2'
arch = 'win32'
if os.arch().indexOf('x64') > -1
arch = 'amd64'
url = 'https://www.python.org/ftp/python/' + pyVer + '/python-' + pyVer + '-embed-' + arch + '.zip'
log.debug 'downloading python...'
statusBarIcon?.setStatus('downloading python...')
zipFile = __dirname + path.sep + 'python.zip'
downloadFile(url, zipFile, ->
log.debug 'extracting python...'
statusBarIcon?.setStatus('extracting python...')
unzip(zipFile, __dirname + path.sep + 'python', ->
fs.unlink(zipFile, (e) ->
if e?
log.warn e
log.debug 'Finished installing python.'
if callback?
callback()
)
)
)
isCLIInstalled = () ->
return fs.existsSync(cliLocation())
isCLILatest = (callback) ->
pythonLocation((python) ->
if python?
args = [cliLocation(), '--version']
child_process.execFile(python, args, (error, stdout, stderr) ->
if not error?
currentVersion = stderr.trim()
log.debug 'Current wakatime-cli version is ' + currentVersion
log.debug 'Checking for updates to wakatime-cli...'
getLatestCliVersion((latestVersion) ->
if currentVersion == latestVersion
log.debug 'wakatime-cli is up to date.'
if callback?
callback(true)
else
if latestVersion?
log.debug 'Found an updated wakatime-cli v' + latestVersion
if callback?
callback(false)
else
log.debug 'Unable to find latest wakatime-cli version from GitHub.'
if callback?
callback(true)
)
else
if callback?
callback(false)
)
else
if callback?
callback(false)
)
getLatestCliVersion = (callback) ->
options =
strictSSL: not atom.config.get('wakatime.disableSSLCertVerify')
url: 'https://raw.githubusercontent.com/wakatime/wakatime/master/wakatime/__about__.py'
request.get(options, (error, response, body) ->
version = null
if !error and response.statusCode == 200
re = new RegExp(/__version_info__ = \('([0-9]+)', '([0-9]+)', '([0-9]+)'\)/g)
for line in body.split('\n')
match = re.exec(line)
if match?
version = match[1] + '.' + match[2] + '.' + match[3]
if callback?
callback(version)
)
cliLocation = () ->
return path.join cliFolder(), 'cli.py'
cliFolder = () ->
dir = path.join __dirname, 'wakatime-master', 'wakatime'
return dir
installCLI = (callback) ->
log.debug 'Downloading wakatime-cli...'
statusBarIcon?.setStatus('downloading wakatime-cli...')
url = 'https://github.com/wakatime/wakatime/archive/master.zip'
zipFile = __dirname + path.sep + 'wakatime-master.zip'
downloadFile(url, zipFile, ->
extractCLI(zipFile, callback)
)
extractCLI = (zipFile, callback) ->
log.debug 'Extracting wakatime-master.zip file...'
statusBarIcon?.setStatus('extracting wakatime-cli...')
removeCLI(->
unzip(zipFile, __dirname, callback)
)
removeCLI = (callback) ->
if fs.existsSync(__dirname + path.sep + 'wakatime-master')
try
rimraf(__dirname + path.sep + 'wakatime-master', ->
if callback?
callback()
)
catch e
log.warn e
if callback?
callback()
else
if callback?
callback()
downloadFile = (url, outputFile, callback) ->
options =
strictSSL: not atom.config.get('wakatime.disableSSLCertVerify')
url: url
r = request(options)
out = fs.createWriteStream(outputFile)
r.pipe(out)
r.on('end', ->
out.on('finish', ->
if callback?
callback()
)
)
unzip = (file, outputDir, callback) ->
if fs.existsSync(file)
try
zip = new AdmZip(file)
zip.extractAllTo(outputDir, true)
catch e
log.warn e
finally
fs.unlink(file, (err) ->
if err?
log.warn err
if callback?
callback()
)
sendHeartbeat = (file, lineno, isWrite) ->
if (not file.path? or file.path is undefined) and (not file.getPath? or file.getPath() is undefined)
log.debug 'Skipping file because path does not exist: ' + file.path
return
currentFile = file.path or file.getPath()
if fileIsIgnored(currentFile)
log.debug 'Skipping file because path matches ignore pattern: ' + currentFile
return
time = Date.now()
if isWrite or enoughTimePassed(time) or lastFile isnt currentFile
pythonLocation (python) ->
return unless python?
args = [cliLocation(), '--file', currentFile, '--plugin', 'atom-wakatime/' + packageVersion]
if isWrite
args.push('--write')
if lineno?
args.push('--lineno')
args.push(lineno)
if atom.config.get 'wakatime.debug'
args.push('--verbose')
if atom.config.get 'wakatime.disableSSLCertVerify'
args.push('--no-ssl-verify')
# fix for wakatime/atom-wakatime#65
args.push('--config')
args.push(path.join getUserHome(), '.wakatime.cfg')
if atom.project.contains(currentFile)
for rootDir in atom.project.rootDirectories
realPath = rootDir.realPath
if currentFile.indexOf(realPath) > -1
args.push('--alternate-project')
args.push(path.basename(realPath))
break
lastHeartbeat = time
lastFile = currentFile
log.debug python + ' ' + args.join(' ')
executeHeartbeatProcess python, args, 0
getToday()
executeHeartbeatProcess = (python, args, tries) ->
max_retries = 5
try
proc = child_process.execFile(python, args, (error, stdout, stderr) ->
if error?
if stderr? and stderr != ''
log.warn stderr
if stdout? and stdout != ''
log.warn stdout
if proc.exitCode == 102
msg = null
status = null
title = 'WakaTime Offline, coding activity will sync when online.'
else if proc.exitCode == 103
msg = 'An error occured while parsing ~/.wakatime.cfg. Check ~/.wakatime.log for more info.'
status = 'Error'
title = msg
else if proc.exitCode == 104
msg = 'Invalid API Key. Make sure your API Key is correct!'
status = 'Error'
title = msg
else
msg = error
status = 'Error'
title = 'Unknown Error (' + proc.exitCode + '); Check your Dev Console and ~/.wakatime.log for more info.'
if msg?
log.warn msg
statusBarIcon?.setStatus(status)
statusBarIcon?.setTitle(title)
else
statusBarIcon?.setStatus(cachedToday)
today = new Date()
statusBarIcon?.setTitle('Last heartbeat sent ' + formatDate(today))
)
catch e
tries++
retry_in = 2
if tries < max_retries
log.debug 'Failed to send heartbeat when executing wakatime-cli background process, will retry in ' + retry_in + ' seconds...'
setTimeout ->
executeHeartbeatProcess(python, args, tries)
, retry_in * 1000
else
log.error 'Failed to send heartbeat when executing wakatime-cli background process.'
throw e
getToday = () ->
cutoff = Date.now() - fetchTodayInterval
if lastTodayFetch > cutoff
return
lastTodayFetch = Date.now()
pythonLocation (python) ->
return unless python?
args = [cliLocation(), '--today', '--plugin', 'atom-wakatime/' + packageVersion]
if atom.config.get 'wakatime.disableSSLCertVerify'
args.push('--no-ssl-verify')
args.push('--config')
args.push(path.join getUserHome(), '.wakatime.cfg')
try
proc = child_process.execFile(python, args, (error, stdout, stderr) ->
if error?
if stderr? and stderr != ''
log.debug stderr
if stdout? and stdout != ''
log.debug stderr
else
cachedToday = 'Today: ' + stdout
statusBarIcon?.setStatus(cachedToday, true)
)
catch e
log.debug e
fileIsIgnored = (file) ->
if endsWith(file, 'COMMIT_EDITMSG') or endsWith(file, 'PULLREQ_EDITMSG') or endsWith(file, 'MERGE_MSG') or endsWith(file, 'TAG_EDITMSG')
return true
patterns = atom.config.get('wakatime.ignore')
if not patterns?
return true
ignore = false
for pattern in patterns
re = new RegExp(pattern, 'gi')
if re.test(file)
ignore = true
break
return ignore
endsWith = (str, suffix) ->
if str? and suffix?
return str.indexOf(suffix, str.length - suffix.length) != -1
return false
formatDate = (date) ->
months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
]
ampm = 'AM'
hour = date.getHours()
if (hour > 11)
ampm = 'PM'
hour = hour - 12
if (hour == 0)
hour = 12
minute = date.getMinutes()
if (minute < 10)
minute = '0' + minute
return months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hour + ':' + minute + ' ' + ampm
debug = (callback) ->
if fs.existsSync(__dirname + path.sep + 'wakatime-master')
try
rimraf(__dirname + path.sep + 'wakatime-master', ->
if callback?
callback()
)
catch e
log.warn e
if callback?
callback()
else
if callback?
callback()
|
[
{
"context": "'name': 'test'\n'scopeName': 'nested'\n'patterns': [\n {\n 'nam",
"end": 13,
"score": 0.5056272745132446,
"start": 9,
"tag": "NAME",
"value": "test"
}
] | spec/fixtures/nested-captures.cson | DeeDeeG/first-mate | 80 | 'name': 'test'
'scopeName': 'nested'
'patterns': [
{
'name': 'text'
'match': '(a(b))'
'captures':
'1':
'patterns': [
{
'match': 'ab'
'name': 'a'
}
]
'2':
'name': 'b'
}
]
| 145167 | 'name': '<NAME>'
'scopeName': 'nested'
'patterns': [
{
'name': 'text'
'match': '(a(b))'
'captures':
'1':
'patterns': [
{
'match': 'ab'
'name': 'a'
}
]
'2':
'name': 'b'
}
]
| true | 'name': 'PI:NAME:<NAME>END_PI'
'scopeName': 'nested'
'patterns': [
{
'name': 'text'
'match': '(a(b))'
'captures':
'1':
'patterns': [
{
'match': 'ab'
'name': 'a'
}
]
'2':
'name': 'b'
}
]
|
[
{
"context": "tion: results[0].geometry.location,\n title: name,\n optimized: false\n }\n myoverlay",
"end": 2790,
"score": 0.9934647679328918,
"start": 2786,
"tag": "NAME",
"value": "name"
}
] | app/assets/javascripts/map.coffee | hpham17/esential | 0 | markersArray = []
inactive = false
QUERY_DELAY = 400;
jQuery ->
window.initMap = ->
map = new google.maps.Map document.getElementById('map'), {
center: {lat: 37.871933, lng: -122.258583}
zoom: 14
}
search map
###*
# Makes a post request to the server with the search term and
# populates the map with the response businesses
#
# param: map - the Google map object
###
search = (map) ->
if inactive == true
return
# post to the search with the search term, take the response data
# and process it
$.get '/communities', {format: 'json'}, (data) ->
inactive = true
# do some clean up
$('#results').show()
$('#results').empty()
clearMarkers()
# iterate through each business in the response capture the data
# within a closure.
i = 0
while i < data.length
capture i, map, data[i]
i++
return
return
###*
# Capture the specific business objects within a closure for setTimeout
# or else it'll execute only on the last business in the array
#
# param: i - the index the business was at in the array, used to the
# timeout delay
# param: map - the Google map object used for geocoding and marker placement
# param: business - the business object from the response
###
capture = (i, map, community) ->
setTimeout (->
if i == 15
inactive = false
# get the geocoded address for the business's location
geocode_address map, community['name'], community['address'], community, i
return
), QUERY_DELAY * i
# the delay on the timeout
return
###*
# Builds the div that'll display the business result from the API
#
# param: business - object of the business response
###
build_results_container = (community, i) ->
[
"<div class='result'>",
" <h5><a id='#{community['name']}' href='/communities/#{i+1}'>",
community['name'],
" </a></h5>",
" <p>",
community['address'],
"</p>",
"</div>"
].join("\n");
###*
# Geocode the address from the business and drop a marker on it's
# location on the map
#
# param: map - the Google map object to drop a marker on
# param: name - the name of the business, used for when you hover
# over the dropped marker
# param: location_object - an object of the businesses address
###
geocode_address = (map, name, address, community, i) ->
geocoder = new (google.maps.Geocoder)
# geocode the address and get the lat/lng
geocoder.geocode { address: address }, (results, status) ->
if status == google.maps.GeocoderStatus.OK
# create a marker and drop it on the name on the geocoded location
marker = new google.maps.Marker {
animation: google.maps.Animation.DROP,
map: map,
position: results[0].geometry.location,
title: name,
optimized: false
}
myoverlay = new google.maps.OverlayView()
myoverlay.draw = ->
this.getPanes().markerLayer.id = 'markers'
return
myoverlay.setMap map
infowindow = new (google.maps.InfoWindow)(content: build_results_container(community, i))
marker.addListener 'click', ->
infowindow.open map, marker
return
# save the marker object so we can delete it later
markersArray.push marker
else
console.log 'Geocode was not successful for the following reason: ' + status
return
return
###*
# Remove all of the markers from the map by setting them
# to null
###
clearMarkers = ->
markersArray.forEach (marker) ->
marker.setMap null
return
markersArray = []
return
| 79541 | markersArray = []
inactive = false
QUERY_DELAY = 400;
jQuery ->
window.initMap = ->
map = new google.maps.Map document.getElementById('map'), {
center: {lat: 37.871933, lng: -122.258583}
zoom: 14
}
search map
###*
# Makes a post request to the server with the search term and
# populates the map with the response businesses
#
# param: map - the Google map object
###
search = (map) ->
if inactive == true
return
# post to the search with the search term, take the response data
# and process it
$.get '/communities', {format: 'json'}, (data) ->
inactive = true
# do some clean up
$('#results').show()
$('#results').empty()
clearMarkers()
# iterate through each business in the response capture the data
# within a closure.
i = 0
while i < data.length
capture i, map, data[i]
i++
return
return
###*
# Capture the specific business objects within a closure for setTimeout
# or else it'll execute only on the last business in the array
#
# param: i - the index the business was at in the array, used to the
# timeout delay
# param: map - the Google map object used for geocoding and marker placement
# param: business - the business object from the response
###
capture = (i, map, community) ->
setTimeout (->
if i == 15
inactive = false
# get the geocoded address for the business's location
geocode_address map, community['name'], community['address'], community, i
return
), QUERY_DELAY * i
# the delay on the timeout
return
###*
# Builds the div that'll display the business result from the API
#
# param: business - object of the business response
###
build_results_container = (community, i) ->
[
"<div class='result'>",
" <h5><a id='#{community['name']}' href='/communities/#{i+1}'>",
community['name'],
" </a></h5>",
" <p>",
community['address'],
"</p>",
"</div>"
].join("\n");
###*
# Geocode the address from the business and drop a marker on it's
# location on the map
#
# param: map - the Google map object to drop a marker on
# param: name - the name of the business, used for when you hover
# over the dropped marker
# param: location_object - an object of the businesses address
###
geocode_address = (map, name, address, community, i) ->
geocoder = new (google.maps.Geocoder)
# geocode the address and get the lat/lng
geocoder.geocode { address: address }, (results, status) ->
if status == google.maps.GeocoderStatus.OK
# create a marker and drop it on the name on the geocoded location
marker = new google.maps.Marker {
animation: google.maps.Animation.DROP,
map: map,
position: results[0].geometry.location,
title: <NAME>,
optimized: false
}
myoverlay = new google.maps.OverlayView()
myoverlay.draw = ->
this.getPanes().markerLayer.id = 'markers'
return
myoverlay.setMap map
infowindow = new (google.maps.InfoWindow)(content: build_results_container(community, i))
marker.addListener 'click', ->
infowindow.open map, marker
return
# save the marker object so we can delete it later
markersArray.push marker
else
console.log 'Geocode was not successful for the following reason: ' + status
return
return
###*
# Remove all of the markers from the map by setting them
# to null
###
clearMarkers = ->
markersArray.forEach (marker) ->
marker.setMap null
return
markersArray = []
return
| true | markersArray = []
inactive = false
QUERY_DELAY = 400;
jQuery ->
window.initMap = ->
map = new google.maps.Map document.getElementById('map'), {
center: {lat: 37.871933, lng: -122.258583}
zoom: 14
}
search map
###*
# Makes a post request to the server with the search term and
# populates the map with the response businesses
#
# param: map - the Google map object
###
search = (map) ->
if inactive == true
return
# post to the search with the search term, take the response data
# and process it
$.get '/communities', {format: 'json'}, (data) ->
inactive = true
# do some clean up
$('#results').show()
$('#results').empty()
clearMarkers()
# iterate through each business in the response capture the data
# within a closure.
i = 0
while i < data.length
capture i, map, data[i]
i++
return
return
###*
# Capture the specific business objects within a closure for setTimeout
# or else it'll execute only on the last business in the array
#
# param: i - the index the business was at in the array, used to the
# timeout delay
# param: map - the Google map object used for geocoding and marker placement
# param: business - the business object from the response
###
capture = (i, map, community) ->
setTimeout (->
if i == 15
inactive = false
# get the geocoded address for the business's location
geocode_address map, community['name'], community['address'], community, i
return
), QUERY_DELAY * i
# the delay on the timeout
return
###*
# Builds the div that'll display the business result from the API
#
# param: business - object of the business response
###
build_results_container = (community, i) ->
[
"<div class='result'>",
" <h5><a id='#{community['name']}' href='/communities/#{i+1}'>",
community['name'],
" </a></h5>",
" <p>",
community['address'],
"</p>",
"</div>"
].join("\n");
###*
# Geocode the address from the business and drop a marker on it's
# location on the map
#
# param: map - the Google map object to drop a marker on
# param: name - the name of the business, used for when you hover
# over the dropped marker
# param: location_object - an object of the businesses address
###
geocode_address = (map, name, address, community, i) ->
geocoder = new (google.maps.Geocoder)
# geocode the address and get the lat/lng
geocoder.geocode { address: address }, (results, status) ->
if status == google.maps.GeocoderStatus.OK
# create a marker and drop it on the name on the geocoded location
marker = new google.maps.Marker {
animation: google.maps.Animation.DROP,
map: map,
position: results[0].geometry.location,
title: PI:NAME:<NAME>END_PI,
optimized: false
}
myoverlay = new google.maps.OverlayView()
myoverlay.draw = ->
this.getPanes().markerLayer.id = 'markers'
return
myoverlay.setMap map
infowindow = new (google.maps.InfoWindow)(content: build_results_container(community, i))
marker.addListener 'click', ->
infowindow.open map, marker
return
# save the marker object so we can delete it later
markersArray.push marker
else
console.log 'Geocode was not successful for the following reason: ' + status
return
return
###*
# Remove all of the markers from the map by setting them
# to null
###
clearMarkers = ->
markersArray.forEach (marker) ->
marker.setMap null
return
markersArray = []
return
|
[
{
"context": "# @fileoverview Prohibit implicit calls.\n# @author Julian Rosse\n###\n'use strict'\n\n# -----------------------------",
"end": 68,
"score": 0.9998649954795837,
"start": 56,
"tag": "NAME",
"value": "Julian Rosse"
}
] | src/tests/rules/implicit-call.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Prohibit implicit calls.
# @author Julian Rosse
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/implicit-call'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester.run 'implicit-call', rule,
valid: [
'f()'
'f(a)'
'do ->'
'''
f(
a
b
)
'''
'new A'
'new A()'
'new A(b)'
,
code: 'f()'
]
invalid: [
code: 'f a'
errors: 1
,
code: '''
f
a: 1
b: 2
'''
errors: 1
,
code: 'new A b'
errors: 1
,
code: 'f a'
errors: 1
,
code: '''
->
f a for a in b
'''
errors: 1
]
| 197375 | ###*
# @fileoverview Prohibit implicit calls.
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/implicit-call'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester.run 'implicit-call', rule,
valid: [
'f()'
'f(a)'
'do ->'
'''
f(
a
b
)
'''
'new A'
'new A()'
'new A(b)'
,
code: 'f()'
]
invalid: [
code: 'f a'
errors: 1
,
code: '''
f
a: 1
b: 2
'''
errors: 1
,
code: 'new A b'
errors: 1
,
code: 'f a'
errors: 1
,
code: '''
->
f a for a in b
'''
errors: 1
]
| true | ###*
# @fileoverview Prohibit implicit calls.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/implicit-call'
{RuleTester} = require 'eslint'
path = require 'path'
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester.run 'implicit-call', rule,
valid: [
'f()'
'f(a)'
'do ->'
'''
f(
a
b
)
'''
'new A'
'new A()'
'new A(b)'
,
code: 'f()'
]
invalid: [
code: 'f a'
errors: 1
,
code: '''
f
a: 1
b: 2
'''
errors: 1
,
code: 'new A b'
errors: 1
,
code: 'f a'
errors: 1
,
code: '''
->
f a for a in b
'''
errors: 1
]
|
[
{
"context": " perObj =\n id: '1'\n name: 'foo'\n\n p1 = Per.create(perObj)\n p1.id()",
"end": 3020,
"score": 0.9605439305305481,
"start": 3017,
"tag": "NAME",
"value": "foo"
},
{
"context": ".should.equal '1'\n p1.name().should.equal 'foo'\n\n done()\n\n it 'Creating multiple model",
"end": 3123,
"score": 0.8061103224754333,
"start": 3120,
"tag": "NAME",
"value": "foo"
},
{
"context": ".should.equal '1'\n p1.name().should.equal 'foo'\n p2.id().should.equal '2'\n p2.name",
"end": 3955,
"score": 0.5604012608528137,
"start": 3952,
"tag": "NAME",
"value": "foo"
},
{
"context": "ate()\n p1.name('foo')\n p1.password('secret')\n p1.toJSON().should.deep.equal {name: 'f",
"end": 6972,
"score": 0.9992794990539551,
"start": 6966,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "1.toJSON('private').should.deep.equal {password: 'secret'}\n p1.toJSON('*').should.deep.equal {passw",
"end": 7092,
"score": 0.9989853501319885,
"start": 7086,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": " p1.toJSON('*').should.deep.equal {password: 'secret', name: 'foo'}\n p1.toJSON('!private').shou",
"end": 7154,
"score": 0.9970623850822449,
"start": 7148,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": "me('foo')\n p1.age(10)\n p1.password('secret')\n\n p1.update(\n name: 'bar'\n ",
"end": 7564,
"score": 0.9992724657058716,
"start": 7558,
"tag": "PASSWORD",
"value": "secret"
},
{
"context": " 'bar'\n age: 20\n password: 'ignore!'\n )\n\n p1.name().should.equal 'bar'\n ",
"end": 7660,
"score": 0.9974995851516724,
"start": 7654,
"tag": "PASSWORD",
"value": "ignore"
}
] | samplenode/samplenode/node_modules/nodejs-model/test/test-basic_model.coffee | thakurarun/Basic-nodejs-express-app | 19 | u = require 'util'
model = require '../lib/index'
describe 'Model creations', ->
it 'model should be a factory function', (done) ->
if typeof(model) is 'function'
done()
it 'Create a basic model', (done) ->
foo = model("Foo")
foo.getType().should.equal 'Foo'
foo.attrsDefs().should.deep.equal {}
done()
it 'model should be created with simple attributes, chained', (done) ->
foo = model("Foo")
.attr('id')
.attr('content')
foo.attrsDefs().should.have.property('id')
foo.attrsDefs().should.have.property('content')
done()
it 'Model should be created with meta attributes, chained', (done) ->
meta =
validations:
presence:
message: 'required!'
converters:
to_capital: true
foo = model("Foo")
.attr('id', meta
)
.attr('content')
foo.attrsDefs().id.should.deep.equal meta
done()
it 'Instantiating a model instance', (done) ->
P = model("Person")
.attr('id')
.attr('name')
p = P.create()
if p.id() isnt undefined
throw 'p.id() Should be undefined!'
p.id('1').name('foo')
#By default models instances are indicated as new
p.isNew().should.equal true
p.id().should.equal '1'
p.name().should.equal 'foo'
done()
it 'Setting an attribute to null should delete the attribute from the model instance', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.name('foo')
p1.attrs.should.contain.property('name', 'foo')
p1.name(null)
p1.attrs.should.not.contain.property('name')
done()
it 'Accessors for var_with_underscore should be camelized', (done) ->
P = model('Person').attr('creation_date')
p = P.create()
p.should.not.have.method('creation_date')
p.should.have.method('creationDate')
p.creationDate('foo')
p.creationDate().should.equal 'foo'
done()
it 'Initializing model via the init() method', (done) ->
P = model('Person').attr('name').attr('creation_date')
d = new Date()
P.init = (instance) ->
instance.creationDate(d)
p1 = P.create()
p1.creationDate().should.equal d
done()
it 'Creating a model instance should produce a create event', (done) ->
P = model('Person')
.attr('id')
P.on('model:created', (p) ->
p.getType().should.equal 'Person'
done()
)
Post = model('Post')
Post.on('model:created', () ->
done()
)
P.create()
it 'Create a model instance by supplying existing object', (done) ->
Per = model("Person").attr("id").attr("name")
perObj =
id: '1'
name: 'foo'
p1 = Per.create(perObj)
p1.id().should.equal '1'
p1.name().should.equal 'foo'
done()
it 'Creating multiple model defs / instances should have different scopes', (done) ->
Per = model("Person").attr("id").attr("name")
Post = model("Post").attr("id").attr("body").attr("created_at")
Object.keys(Per.attrsDefs()).length.should.equal 2
Per.attrsDefs().should.have.property('id')
Per.attrsDefs().should.have.property('name')
Object.keys(Post.attrsDefs()).length.should.equal 3
Post.attrsDefs().should.have.property('id')
Post.attrsDefs().should.have.property('body')
Post.attrsDefs().should.have.property('created_at')
p1 = Per.create()
p1.id('1')
p1.name('foo')
p2 = Per.create()
p2.id('2')
p2.name('bar')
p1.id().should.equal '1'
p1.name().should.equal 'foo'
p2.id().should.equal '2'
p2.name().should.equal 'bar'
done()
it 'Validate a simple model with presence validator', (done) ->
P = model("Person").attr('name',
validations:
presence:
message: 'Required!'
)
p1 = P.create()
p1.errors.should.have.length 0
p1.isValid.should.equal false
p1.validate().then((validated) ->
Object.keys(p1.errors).should.have.length 1
p1.errors.should.deep.equal {name: ['Required!']}
p1.isValid.should.equal false
true
).then(() ->
p1.name('foo')
p1.validate().then((validated) ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
)
it 'Ensure validation dont fail when having attributes with _', (done) ->
P = model("Person").attr('creation_date',
validations:
precense:
message: 'Required!'
)
p1 = P.create()
p1.creationDate new Date()
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
it 'Validate a model with combined validators', (done) ->
P = model("Person").attr('name',
validations:
presence:
message: 'Required!'
).attr('title'
validations:
length:
messages:
tooShort: 'too short!'
tooLong: 'too long!'
minimum: 5
maximum: 10
allowBlank: false
)
p1 = P.create()
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 2
p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too short!' ] }
p1.isValid.should.equal false
true
).then(() ->
p1.title('hello')
p1.validate().then(() ->
p1.errors.should.deep.equal {name: ['Required!' ]}
true
)
).then(() ->
p1.title('hello-world')
p1.validate().then(() ->
p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too long!' ] }
p1.isValid.should.equal false
true
)
).then(() ->
p1.name('foo')
p1.title('hello')
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
)
it 'Test TOJSON', (done) ->
P = model("User").attr("password",
tags: ['private']
).attr("name")
p1 = P.create()
p1.name('foo')
p1.password('secret')
p1.toJSON().should.deep.equal {name: 'foo'}
p1.toJSON('private').should.deep.equal {password: 'secret'}
p1.toJSON('*').should.deep.equal {password: 'secret', name: 'foo'}
p1.toJSON('!private').should.deep.equal {name: 'foo'}
p1.toJSON('none').should.deep.equal {}
done()
it 'Update model instance via update()', (done) ->
P = model("Person").attr('name').attr('age')
.attr('password',
tags: ['private']
)
p1 = P.create()
p1.name('foo')
p1.age(10)
p1.password('secret')
p1.update(
name: 'bar'
age: 20
password: 'ignore!'
)
p1.name().should.equal 'bar'
p1.age().should.equal 20
p1.password().should.equal 'secret'
done()
it 'Ensure undefined attributes are not causing errors nor updating the model', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.name 'foo'
newObj =
name: 'bar'
other: 'baz'
p1.update(newObj, '*')
p1.name().should.equal 'bar'
if p1.other isnt undefined
throw 'Expected p1.other to be undefined!'
p1.attrs.should.not.have.property('other')
done()
it 'Ensure set model.isNew to false works', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.isNew().should.equal true
p1.setNew(false)
p1.isNew().should.equal false
done()
### | 199461 | u = require 'util'
model = require '../lib/index'
describe 'Model creations', ->
it 'model should be a factory function', (done) ->
if typeof(model) is 'function'
done()
it 'Create a basic model', (done) ->
foo = model("Foo")
foo.getType().should.equal 'Foo'
foo.attrsDefs().should.deep.equal {}
done()
it 'model should be created with simple attributes, chained', (done) ->
foo = model("Foo")
.attr('id')
.attr('content')
foo.attrsDefs().should.have.property('id')
foo.attrsDefs().should.have.property('content')
done()
it 'Model should be created with meta attributes, chained', (done) ->
meta =
validations:
presence:
message: 'required!'
converters:
to_capital: true
foo = model("Foo")
.attr('id', meta
)
.attr('content')
foo.attrsDefs().id.should.deep.equal meta
done()
it 'Instantiating a model instance', (done) ->
P = model("Person")
.attr('id')
.attr('name')
p = P.create()
if p.id() isnt undefined
throw 'p.id() Should be undefined!'
p.id('1').name('foo')
#By default models instances are indicated as new
p.isNew().should.equal true
p.id().should.equal '1'
p.name().should.equal 'foo'
done()
it 'Setting an attribute to null should delete the attribute from the model instance', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.name('foo')
p1.attrs.should.contain.property('name', 'foo')
p1.name(null)
p1.attrs.should.not.contain.property('name')
done()
it 'Accessors for var_with_underscore should be camelized', (done) ->
P = model('Person').attr('creation_date')
p = P.create()
p.should.not.have.method('creation_date')
p.should.have.method('creationDate')
p.creationDate('foo')
p.creationDate().should.equal 'foo'
done()
it 'Initializing model via the init() method', (done) ->
P = model('Person').attr('name').attr('creation_date')
d = new Date()
P.init = (instance) ->
instance.creationDate(d)
p1 = P.create()
p1.creationDate().should.equal d
done()
it 'Creating a model instance should produce a create event', (done) ->
P = model('Person')
.attr('id')
P.on('model:created', (p) ->
p.getType().should.equal 'Person'
done()
)
Post = model('Post')
Post.on('model:created', () ->
done()
)
P.create()
it 'Create a model instance by supplying existing object', (done) ->
Per = model("Person").attr("id").attr("name")
perObj =
id: '1'
name: '<NAME>'
p1 = Per.create(perObj)
p1.id().should.equal '1'
p1.name().should.equal '<NAME>'
done()
it 'Creating multiple model defs / instances should have different scopes', (done) ->
Per = model("Person").attr("id").attr("name")
Post = model("Post").attr("id").attr("body").attr("created_at")
Object.keys(Per.attrsDefs()).length.should.equal 2
Per.attrsDefs().should.have.property('id')
Per.attrsDefs().should.have.property('name')
Object.keys(Post.attrsDefs()).length.should.equal 3
Post.attrsDefs().should.have.property('id')
Post.attrsDefs().should.have.property('body')
Post.attrsDefs().should.have.property('created_at')
p1 = Per.create()
p1.id('1')
p1.name('foo')
p2 = Per.create()
p2.id('2')
p2.name('bar')
p1.id().should.equal '1'
p1.name().should.equal '<NAME>'
p2.id().should.equal '2'
p2.name().should.equal 'bar'
done()
it 'Validate a simple model with presence validator', (done) ->
P = model("Person").attr('name',
validations:
presence:
message: 'Required!'
)
p1 = P.create()
p1.errors.should.have.length 0
p1.isValid.should.equal false
p1.validate().then((validated) ->
Object.keys(p1.errors).should.have.length 1
p1.errors.should.deep.equal {name: ['Required!']}
p1.isValid.should.equal false
true
).then(() ->
p1.name('foo')
p1.validate().then((validated) ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
)
it 'Ensure validation dont fail when having attributes with _', (done) ->
P = model("Person").attr('creation_date',
validations:
precense:
message: 'Required!'
)
p1 = P.create()
p1.creationDate new Date()
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
it 'Validate a model with combined validators', (done) ->
P = model("Person").attr('name',
validations:
presence:
message: 'Required!'
).attr('title'
validations:
length:
messages:
tooShort: 'too short!'
tooLong: 'too long!'
minimum: 5
maximum: 10
allowBlank: false
)
p1 = P.create()
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 2
p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too short!' ] }
p1.isValid.should.equal false
true
).then(() ->
p1.title('hello')
p1.validate().then(() ->
p1.errors.should.deep.equal {name: ['Required!' ]}
true
)
).then(() ->
p1.title('hello-world')
p1.validate().then(() ->
p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too long!' ] }
p1.isValid.should.equal false
true
)
).then(() ->
p1.name('foo')
p1.title('hello')
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
)
it 'Test TOJSON', (done) ->
P = model("User").attr("password",
tags: ['private']
).attr("name")
p1 = P.create()
p1.name('foo')
p1.password('<PASSWORD>')
p1.toJSON().should.deep.equal {name: 'foo'}
p1.toJSON('private').should.deep.equal {password: '<PASSWORD>'}
p1.toJSON('*').should.deep.equal {password: '<PASSWORD>', name: 'foo'}
p1.toJSON('!private').should.deep.equal {name: 'foo'}
p1.toJSON('none').should.deep.equal {}
done()
it 'Update model instance via update()', (done) ->
P = model("Person").attr('name').attr('age')
.attr('password',
tags: ['private']
)
p1 = P.create()
p1.name('foo')
p1.age(10)
p1.password('<PASSWORD>')
p1.update(
name: 'bar'
age: 20
password: '<PASSWORD>!'
)
p1.name().should.equal 'bar'
p1.age().should.equal 20
p1.password().should.equal 'secret'
done()
it 'Ensure undefined attributes are not causing errors nor updating the model', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.name 'foo'
newObj =
name: 'bar'
other: 'baz'
p1.update(newObj, '*')
p1.name().should.equal 'bar'
if p1.other isnt undefined
throw 'Expected p1.other to be undefined!'
p1.attrs.should.not.have.property('other')
done()
it 'Ensure set model.isNew to false works', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.isNew().should.equal true
p1.setNew(false)
p1.isNew().should.equal false
done()
### | true | u = require 'util'
model = require '../lib/index'
describe 'Model creations', ->
it 'model should be a factory function', (done) ->
if typeof(model) is 'function'
done()
it 'Create a basic model', (done) ->
foo = model("Foo")
foo.getType().should.equal 'Foo'
foo.attrsDefs().should.deep.equal {}
done()
it 'model should be created with simple attributes, chained', (done) ->
foo = model("Foo")
.attr('id')
.attr('content')
foo.attrsDefs().should.have.property('id')
foo.attrsDefs().should.have.property('content')
done()
it 'Model should be created with meta attributes, chained', (done) ->
meta =
validations:
presence:
message: 'required!'
converters:
to_capital: true
foo = model("Foo")
.attr('id', meta
)
.attr('content')
foo.attrsDefs().id.should.deep.equal meta
done()
it 'Instantiating a model instance', (done) ->
P = model("Person")
.attr('id')
.attr('name')
p = P.create()
if p.id() isnt undefined
throw 'p.id() Should be undefined!'
p.id('1').name('foo')
#By default models instances are indicated as new
p.isNew().should.equal true
p.id().should.equal '1'
p.name().should.equal 'foo'
done()
it 'Setting an attribute to null should delete the attribute from the model instance', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.name('foo')
p1.attrs.should.contain.property('name', 'foo')
p1.name(null)
p1.attrs.should.not.contain.property('name')
done()
it 'Accessors for var_with_underscore should be camelized', (done) ->
P = model('Person').attr('creation_date')
p = P.create()
p.should.not.have.method('creation_date')
p.should.have.method('creationDate')
p.creationDate('foo')
p.creationDate().should.equal 'foo'
done()
it 'Initializing model via the init() method', (done) ->
P = model('Person').attr('name').attr('creation_date')
d = new Date()
P.init = (instance) ->
instance.creationDate(d)
p1 = P.create()
p1.creationDate().should.equal d
done()
it 'Creating a model instance should produce a create event', (done) ->
P = model('Person')
.attr('id')
P.on('model:created', (p) ->
p.getType().should.equal 'Person'
done()
)
Post = model('Post')
Post.on('model:created', () ->
done()
)
P.create()
it 'Create a model instance by supplying existing object', (done) ->
Per = model("Person").attr("id").attr("name")
perObj =
id: '1'
name: 'PI:NAME:<NAME>END_PI'
p1 = Per.create(perObj)
p1.id().should.equal '1'
p1.name().should.equal 'PI:NAME:<NAME>END_PI'
done()
it 'Creating multiple model defs / instances should have different scopes', (done) ->
Per = model("Person").attr("id").attr("name")
Post = model("Post").attr("id").attr("body").attr("created_at")
Object.keys(Per.attrsDefs()).length.should.equal 2
Per.attrsDefs().should.have.property('id')
Per.attrsDefs().should.have.property('name')
Object.keys(Post.attrsDefs()).length.should.equal 3
Post.attrsDefs().should.have.property('id')
Post.attrsDefs().should.have.property('body')
Post.attrsDefs().should.have.property('created_at')
p1 = Per.create()
p1.id('1')
p1.name('foo')
p2 = Per.create()
p2.id('2')
p2.name('bar')
p1.id().should.equal '1'
p1.name().should.equal 'PI:NAME:<NAME>END_PI'
p2.id().should.equal '2'
p2.name().should.equal 'bar'
done()
it 'Validate a simple model with presence validator', (done) ->
P = model("Person").attr('name',
validations:
presence:
message: 'Required!'
)
p1 = P.create()
p1.errors.should.have.length 0
p1.isValid.should.equal false
p1.validate().then((validated) ->
Object.keys(p1.errors).should.have.length 1
p1.errors.should.deep.equal {name: ['Required!']}
p1.isValid.should.equal false
true
).then(() ->
p1.name('foo')
p1.validate().then((validated) ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
)
it 'Ensure validation dont fail when having attributes with _', (done) ->
P = model("Person").attr('creation_date',
validations:
precense:
message: 'Required!'
)
p1 = P.create()
p1.creationDate new Date()
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
it 'Validate a model with combined validators', (done) ->
P = model("Person").attr('name',
validations:
presence:
message: 'Required!'
).attr('title'
validations:
length:
messages:
tooShort: 'too short!'
tooLong: 'too long!'
minimum: 5
maximum: 10
allowBlank: false
)
p1 = P.create()
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 2
p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too short!' ] }
p1.isValid.should.equal false
true
).then(() ->
p1.title('hello')
p1.validate().then(() ->
p1.errors.should.deep.equal {name: ['Required!' ]}
true
)
).then(() ->
p1.title('hello-world')
p1.validate().then(() ->
p1.errors.should.deep.equal { name: [ 'Required!' ], title: [ 'too long!' ] }
p1.isValid.should.equal false
true
)
).then(() ->
p1.name('foo')
p1.title('hello')
p1.validate().then(() ->
Object.keys(p1.errors).should.have.length 0
p1.isValid.should.equal true
done()
)
)
it 'Test TOJSON', (done) ->
P = model("User").attr("password",
tags: ['private']
).attr("name")
p1 = P.create()
p1.name('foo')
p1.password('PI:PASSWORD:<PASSWORD>END_PI')
p1.toJSON().should.deep.equal {name: 'foo'}
p1.toJSON('private').should.deep.equal {password: 'PI:PASSWORD:<PASSWORD>END_PI'}
p1.toJSON('*').should.deep.equal {password: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'foo'}
p1.toJSON('!private').should.deep.equal {name: 'foo'}
p1.toJSON('none').should.deep.equal {}
done()
it 'Update model instance via update()', (done) ->
P = model("Person").attr('name').attr('age')
.attr('password',
tags: ['private']
)
p1 = P.create()
p1.name('foo')
p1.age(10)
p1.password('PI:PASSWORD:<PASSWORD>END_PI')
p1.update(
name: 'bar'
age: 20
password: 'PI:PASSWORD:<PASSWORD>END_PI!'
)
p1.name().should.equal 'bar'
p1.age().should.equal 20
p1.password().should.equal 'secret'
done()
it 'Ensure undefined attributes are not causing errors nor updating the model', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.name 'foo'
newObj =
name: 'bar'
other: 'baz'
p1.update(newObj, '*')
p1.name().should.equal 'bar'
if p1.other isnt undefined
throw 'Expected p1.other to be undefined!'
p1.attrs.should.not.have.property('other')
done()
it 'Ensure set model.isNew to false works', (done) ->
P = model("Person").attr('name')
p1 = P.create()
p1.isNew().should.equal true
p1.setNew(false)
p1.isNew().should.equal false
done()
### |
[
{
"context": "he text highlighting engine\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Painter\n\n #\n # Basic constructor\n #\n ",
"end": 73,
"score": 0.9998809099197388,
"start": 56,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | src/painter.coffee | MadRabbit/osom-area | 1 | #
# The text highlighting engine
#
# Copyright (C) 2012 Nikolay Nemshilov
#
class Painter
#
# Basic constructor
#
# @param {OsomArea} the textarea reference
# @return {OsomArea.Painter} this
#
constructor: (osom_area)->
@textarea = osom_area
@markers = []
@reset()
#
# Removes all the highlighting tags
#
# @return {OsomArea.Painter} this
#
reset: ->
@textarea.mirror.reset();
return @
#
# Figures which blocks of texts should be painted and how
#
# @param {String|Number|Regexp} a string/regexp patter to highlight, or an integer starting index
# @param {Number|String} highlighting end position or the highighting color
# @param {String|undefined} the highlighting color
# @param {Boolean} pass `true` if you want to keep all previous markers
# @return {OsomArea.Painter} this
#
highlight: (first, second, third, keep)->
@markers = [] unless keep
@markers.push([first, second, third])
@paint()
#
# Repaints the textarea mirror according the current list of markers
#
# @return {OsomArea.Painter} this
#
paint: (text)->
text or= @textarea._.value; html = ''; index = 0
for marker in @getMarkers(text)
html += text.substring(index, marker[0])
html += '<span class="highlight'
html += '" style="background:'+ marker[2] if marker[2]
html += '">'+ text.substring(marker[0], marker[1]) + '</span>'
index = marker[1]
html = if marker then html + text.substring(marker[1]) else text
@textarea.mirror._.innerHTML = html
return @
# protected
#
# Builds the list of position/color markers out of saved patterns
#
# @return {Array} list of markers
#
getMarkers: (text)->
return [] if @markers.length is 0
text or= @textarea._.value; markers = []
for [first, second, third] in @markers
position = 0; index = 0;
# a simple point to point marker
if isNumber(first) and isNumber(second)
markers.push([first, second, third])
# a regular expression based marker
else if first instanceof RegExp
while match = text.substr(position).match(first)
index = text.substr(position).indexOf(match[0])
markers.push([position += index, position += match[0].length, second])
# a plain text based marker
else if isString(first)
while (index = text.substr(position).indexOf(first)) isnt -1
markers.push([position += index, position += first.length, second])
markers.sort (a,b)-> a[0] - b[0]
clean_list = []; prev_marker = [0,0,undefined]
while marker = markers.shift()
if marker[0] < prev_marker[1] # if current marker intersects with the previous one
if marker[2] is prev_marker[2] # if the markers have the same color
prev_marker[1] = marker[1] # extenting the previous marker to the end of current one
continue # and don't push it into the clean list
else # if colors are different colors
prev_marker[1] = marker[0] # shrinking the previous marker to the beginning of the current one
clean_list.push(marker)
return clean_list | 176470 | #
# The text highlighting engine
#
# Copyright (C) 2012 <NAME>
#
class Painter
#
# Basic constructor
#
# @param {OsomArea} the textarea reference
# @return {OsomArea.Painter} this
#
constructor: (osom_area)->
@textarea = osom_area
@markers = []
@reset()
#
# Removes all the highlighting tags
#
# @return {OsomArea.Painter} this
#
reset: ->
@textarea.mirror.reset();
return @
#
# Figures which blocks of texts should be painted and how
#
# @param {String|Number|Regexp} a string/regexp patter to highlight, or an integer starting index
# @param {Number|String} highlighting end position or the highighting color
# @param {String|undefined} the highlighting color
# @param {Boolean} pass `true` if you want to keep all previous markers
# @return {OsomArea.Painter} this
#
highlight: (first, second, third, keep)->
@markers = [] unless keep
@markers.push([first, second, third])
@paint()
#
# Repaints the textarea mirror according the current list of markers
#
# @return {OsomArea.Painter} this
#
paint: (text)->
text or= @textarea._.value; html = ''; index = 0
for marker in @getMarkers(text)
html += text.substring(index, marker[0])
html += '<span class="highlight'
html += '" style="background:'+ marker[2] if marker[2]
html += '">'+ text.substring(marker[0], marker[1]) + '</span>'
index = marker[1]
html = if marker then html + text.substring(marker[1]) else text
@textarea.mirror._.innerHTML = html
return @
# protected
#
# Builds the list of position/color markers out of saved patterns
#
# @return {Array} list of markers
#
getMarkers: (text)->
return [] if @markers.length is 0
text or= @textarea._.value; markers = []
for [first, second, third] in @markers
position = 0; index = 0;
# a simple point to point marker
if isNumber(first) and isNumber(second)
markers.push([first, second, third])
# a regular expression based marker
else if first instanceof RegExp
while match = text.substr(position).match(first)
index = text.substr(position).indexOf(match[0])
markers.push([position += index, position += match[0].length, second])
# a plain text based marker
else if isString(first)
while (index = text.substr(position).indexOf(first)) isnt -1
markers.push([position += index, position += first.length, second])
markers.sort (a,b)-> a[0] - b[0]
clean_list = []; prev_marker = [0,0,undefined]
while marker = markers.shift()
if marker[0] < prev_marker[1] # if current marker intersects with the previous one
if marker[2] is prev_marker[2] # if the markers have the same color
prev_marker[1] = marker[1] # extenting the previous marker to the end of current one
continue # and don't push it into the clean list
else # if colors are different colors
prev_marker[1] = marker[0] # shrinking the previous marker to the beginning of the current one
clean_list.push(marker)
return clean_list | true | #
# The text highlighting engine
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
class Painter
#
# Basic constructor
#
# @param {OsomArea} the textarea reference
# @return {OsomArea.Painter} this
#
constructor: (osom_area)->
@textarea = osom_area
@markers = []
@reset()
#
# Removes all the highlighting tags
#
# @return {OsomArea.Painter} this
#
reset: ->
@textarea.mirror.reset();
return @
#
# Figures which blocks of texts should be painted and how
#
# @param {String|Number|Regexp} a string/regexp patter to highlight, or an integer starting index
# @param {Number|String} highlighting end position or the highighting color
# @param {String|undefined} the highlighting color
# @param {Boolean} pass `true` if you want to keep all previous markers
# @return {OsomArea.Painter} this
#
highlight: (first, second, third, keep)->
@markers = [] unless keep
@markers.push([first, second, third])
@paint()
#
# Repaints the textarea mirror according the current list of markers
#
# @return {OsomArea.Painter} this
#
paint: (text)->
text or= @textarea._.value; html = ''; index = 0
for marker in @getMarkers(text)
html += text.substring(index, marker[0])
html += '<span class="highlight'
html += '" style="background:'+ marker[2] if marker[2]
html += '">'+ text.substring(marker[0], marker[1]) + '</span>'
index = marker[1]
html = if marker then html + text.substring(marker[1]) else text
@textarea.mirror._.innerHTML = html
return @
# protected
#
# Builds the list of position/color markers out of saved patterns
#
# @return {Array} list of markers
#
getMarkers: (text)->
return [] if @markers.length is 0
text or= @textarea._.value; markers = []
for [first, second, third] in @markers
position = 0; index = 0;
# a simple point to point marker
if isNumber(first) and isNumber(second)
markers.push([first, second, third])
# a regular expression based marker
else if first instanceof RegExp
while match = text.substr(position).match(first)
index = text.substr(position).indexOf(match[0])
markers.push([position += index, position += match[0].length, second])
# a plain text based marker
else if isString(first)
while (index = text.substr(position).indexOf(first)) isnt -1
markers.push([position += index, position += first.length, second])
markers.sort (a,b)-> a[0] - b[0]
clean_list = []; prev_marker = [0,0,undefined]
while marker = markers.shift()
if marker[0] < prev_marker[1] # if current marker intersects with the previous one
if marker[2] is prev_marker[2] # if the markers have the same color
prev_marker[1] = marker[1] # extenting the previous marker to the end of current one
continue # and don't push it into the clean list
else # if colors are different colors
prev_marker[1] = marker[0] # shrinking the previous marker to the beginning of the current one
clean_list.push(marker)
return clean_list |
[
{
"context": "ervices/rest/?method=flickr.photos.search&api_key=8162cbed138466b501453381c1ce5bc9&group_id=34427469792%40N01&per_page=31&page=1&for",
"end": 126,
"score": 0.9997333884239197,
"start": 94,
"tag": "KEY",
"value": "8162cbed138466b501453381c1ce5bc9"
}
] | 065-atom/background-pic/lib/pics.coffee | sayanee/build-podcast | 156 | # Flick public API: https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=8162cbed138466b501453381c1ce5bc9&group_id=34427469792%40N01&per_page=31&page=1&format=json&nojsoncallback=1&api_sig=ee4ea61ab9ce363012ef88a85b77a4d1
module.exports = [
'https://farm2.staticflickr.com/1603/23819326999_3fe596c1f0_b.jpg',
'https://farm2.staticflickr.com/1495/24187109185_6c9517773c_b.jpg',
'https://farm2.staticflickr.com/1610/24161021586_aa646b46f4_b.jpg',
'https://farm2.staticflickr.com/1680/24187102495_da2f3d4265_b.jpg',
'https://farm2.staticflickr.com/1686/24160948936_d01c53cc14_b.jpg',
'https://farm2.staticflickr.com/1610/23819233639_b5d19f8694_b.jpg',
'https://farm2.staticflickr.com/1445/24104409251_282815ef84_b.jpg',
'https://farm2.staticflickr.com/1706/23890907050_d4e449afe6_b.jpg',
'https://farm9.staticflickr.com/8200/8238598911_d7536c59ae_b.jpg',
'https://farm2.staticflickr.com/1458/23819108959_1b3ae830b8_b.jpg',
'https://farm2.staticflickr.com/1525/23891271130_50d1161381_b.jpg',
'https://farm2.staticflickr.com/1517/24186855355_f93a784725_b.jpg',
'https://farm2.staticflickr.com/1643/23891210160_3b6ee37724_b.jpg',
'https://farm2.staticflickr.com/1496/23560002053_8088b8fc1a_b.jpg',
'https://farm2.staticflickr.com/1678/23496202063_ef173d40b7_b.jpg',
'https://farm2.staticflickr.com/1549/24068550745_70a91d89d6_b.jpg',
'https://farm6.staticflickr.com/5772/23434500254_e49c8a3698_b.jpg',
'https://farm9.staticflickr.com/8710/17031744172_68e19127ce_b.jpg',
'https://farm9.staticflickr.com/8692/16825775947_fc722e4818_b.jpg',
'https://farm6.staticflickr.com/5536/12805566734_e4c5976acb_b.jpg',
'https://farm4.staticflickr.com/3770/10139764336_4cba024e21_b.jpg',
'https://farm8.staticflickr.com/7009/6544274849_b2c43a0f10_b.jpg',
'https://farm2.staticflickr.com/1611/23891174850_36dc32b3e4_b.jpg',
'https://farm2.staticflickr.com/1673/23559957353_45aa078ef3_b.jpg',
'https://farm6.staticflickr.com/5445/17603766045_39125b4e8e_b.jpg',
'https://farm2.staticflickr.com/1672/23818854979_fef67b8c77_b.jpg',
'https://farm2.staticflickr.com/1519/24186603425_e16bc7c073_b.jpg',
'https://farm2.staticflickr.com/1554/24078503102_43963149fd_b.jpg',
'https://farm2.staticflickr.com/1634/24103891481_f57ae4dd45_b.jpg',
'https://farm2.staticflickr.com/1669/24160931936_0c17f717ae_b.jpg',
'https://farm2.staticflickr.com/1671/24140635526_fbaa6a0091_b.jpg'
]
| 217893 | # Flick public API: https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=<KEY>&group_id=34427469792%40N01&per_page=31&page=1&format=json&nojsoncallback=1&api_sig=ee4ea61ab9ce363012ef88a85b77a4d1
module.exports = [
'https://farm2.staticflickr.com/1603/23819326999_3fe596c1f0_b.jpg',
'https://farm2.staticflickr.com/1495/24187109185_6c9517773c_b.jpg',
'https://farm2.staticflickr.com/1610/24161021586_aa646b46f4_b.jpg',
'https://farm2.staticflickr.com/1680/24187102495_da2f3d4265_b.jpg',
'https://farm2.staticflickr.com/1686/24160948936_d01c53cc14_b.jpg',
'https://farm2.staticflickr.com/1610/23819233639_b5d19f8694_b.jpg',
'https://farm2.staticflickr.com/1445/24104409251_282815ef84_b.jpg',
'https://farm2.staticflickr.com/1706/23890907050_d4e449afe6_b.jpg',
'https://farm9.staticflickr.com/8200/8238598911_d7536c59ae_b.jpg',
'https://farm2.staticflickr.com/1458/23819108959_1b3ae830b8_b.jpg',
'https://farm2.staticflickr.com/1525/23891271130_50d1161381_b.jpg',
'https://farm2.staticflickr.com/1517/24186855355_f93a784725_b.jpg',
'https://farm2.staticflickr.com/1643/23891210160_3b6ee37724_b.jpg',
'https://farm2.staticflickr.com/1496/23560002053_8088b8fc1a_b.jpg',
'https://farm2.staticflickr.com/1678/23496202063_ef173d40b7_b.jpg',
'https://farm2.staticflickr.com/1549/24068550745_70a91d89d6_b.jpg',
'https://farm6.staticflickr.com/5772/23434500254_e49c8a3698_b.jpg',
'https://farm9.staticflickr.com/8710/17031744172_68e19127ce_b.jpg',
'https://farm9.staticflickr.com/8692/16825775947_fc722e4818_b.jpg',
'https://farm6.staticflickr.com/5536/12805566734_e4c5976acb_b.jpg',
'https://farm4.staticflickr.com/3770/10139764336_4cba024e21_b.jpg',
'https://farm8.staticflickr.com/7009/6544274849_b2c43a0f10_b.jpg',
'https://farm2.staticflickr.com/1611/23891174850_36dc32b3e4_b.jpg',
'https://farm2.staticflickr.com/1673/23559957353_45aa078ef3_b.jpg',
'https://farm6.staticflickr.com/5445/17603766045_39125b4e8e_b.jpg',
'https://farm2.staticflickr.com/1672/23818854979_fef67b8c77_b.jpg',
'https://farm2.staticflickr.com/1519/24186603425_e16bc7c073_b.jpg',
'https://farm2.staticflickr.com/1554/24078503102_43963149fd_b.jpg',
'https://farm2.staticflickr.com/1634/24103891481_f57ae4dd45_b.jpg',
'https://farm2.staticflickr.com/1669/24160931936_0c17f717ae_b.jpg',
'https://farm2.staticflickr.com/1671/24140635526_fbaa6a0091_b.jpg'
]
| true | # Flick public API: https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=PI:KEY:<KEY>END_PI&group_id=34427469792%40N01&per_page=31&page=1&format=json&nojsoncallback=1&api_sig=ee4ea61ab9ce363012ef88a85b77a4d1
module.exports = [
'https://farm2.staticflickr.com/1603/23819326999_3fe596c1f0_b.jpg',
'https://farm2.staticflickr.com/1495/24187109185_6c9517773c_b.jpg',
'https://farm2.staticflickr.com/1610/24161021586_aa646b46f4_b.jpg',
'https://farm2.staticflickr.com/1680/24187102495_da2f3d4265_b.jpg',
'https://farm2.staticflickr.com/1686/24160948936_d01c53cc14_b.jpg',
'https://farm2.staticflickr.com/1610/23819233639_b5d19f8694_b.jpg',
'https://farm2.staticflickr.com/1445/24104409251_282815ef84_b.jpg',
'https://farm2.staticflickr.com/1706/23890907050_d4e449afe6_b.jpg',
'https://farm9.staticflickr.com/8200/8238598911_d7536c59ae_b.jpg',
'https://farm2.staticflickr.com/1458/23819108959_1b3ae830b8_b.jpg',
'https://farm2.staticflickr.com/1525/23891271130_50d1161381_b.jpg',
'https://farm2.staticflickr.com/1517/24186855355_f93a784725_b.jpg',
'https://farm2.staticflickr.com/1643/23891210160_3b6ee37724_b.jpg',
'https://farm2.staticflickr.com/1496/23560002053_8088b8fc1a_b.jpg',
'https://farm2.staticflickr.com/1678/23496202063_ef173d40b7_b.jpg',
'https://farm2.staticflickr.com/1549/24068550745_70a91d89d6_b.jpg',
'https://farm6.staticflickr.com/5772/23434500254_e49c8a3698_b.jpg',
'https://farm9.staticflickr.com/8710/17031744172_68e19127ce_b.jpg',
'https://farm9.staticflickr.com/8692/16825775947_fc722e4818_b.jpg',
'https://farm6.staticflickr.com/5536/12805566734_e4c5976acb_b.jpg',
'https://farm4.staticflickr.com/3770/10139764336_4cba024e21_b.jpg',
'https://farm8.staticflickr.com/7009/6544274849_b2c43a0f10_b.jpg',
'https://farm2.staticflickr.com/1611/23891174850_36dc32b3e4_b.jpg',
'https://farm2.staticflickr.com/1673/23559957353_45aa078ef3_b.jpg',
'https://farm6.staticflickr.com/5445/17603766045_39125b4e8e_b.jpg',
'https://farm2.staticflickr.com/1672/23818854979_fef67b8c77_b.jpg',
'https://farm2.staticflickr.com/1519/24186603425_e16bc7c073_b.jpg',
'https://farm2.staticflickr.com/1554/24078503102_43963149fd_b.jpg',
'https://farm2.staticflickr.com/1634/24103891481_f57ae4dd45_b.jpg',
'https://farm2.staticflickr.com/1669/24160931936_0c17f717ae_b.jpg',
'https://farm2.staticflickr.com/1671/24140635526_fbaa6a0091_b.jpg'
]
|
[
{
"context": "X all the Y\n# hubot <text> that would be great - Bill Lumbergh from Office Space\n# hubot <text> too damn <text",
"end": 1020,
"score": 0.9781874418258667,
"start": 1007,
"tag": "NAME",
"value": "Bill Lumbergh"
},
{
"context": "ot time for that\n# hubot <text> I guarantee it - George Zimmer\n# hubot <text> and it's gone - South Park Banke",
"end": 1469,
"score": 0.9918074607849121,
"start": 1456,
"tag": "NAME",
"value": "George Zimmer"
},
{
"context": " on - Triumph the Comic insult dog\n#\n# Author:\n# dylanwenzlau\n\n\ninspect = require('util').inspect\n\nmodule.expor",
"end": 1905,
"score": 0.9993711113929749,
"start": 1893,
"tag": "USERNAME",
"value": "dylanwenzlau"
},
{
"context": "me = process.env.IMGFLIP_API_USERNAME\n password = process.env.IMGFLIP_API_PASSWORD\n\n if (username or password)",
"end": 4736,
"score": 0.8464722633361816,
"start": 4725,
"tag": "PASSWORD",
"value": "process.env"
},
{
"context": "d!'\n return\n\n if not username\n username = 'imgflip_hubot'\n password = 'imgflip_hubot'\n\n msg.http('http",
"end": 4970,
"score": 0.9994224309921265,
"start": 4957,
"tag": "USERNAME",
"value": "imgflip_hubot"
},
{
"context": "me\n username = 'imgflip_hubot'\n password = 'imgflip_hubot'\n\n msg.http('https://api.imgflip.com/caption_ima",
"end": 5001,
"score": 0.9993508458137512,
"start": 4988,
"tag": "PASSWORD",
"value": "imgflip_hubot"
},
{
"context": "ry\n template_id: template_id,\n username: username,\n password: password,\n text0: text0,\n ",
"end": 5121,
"score": 0.9438236355781555,
"start": 5113,
"tag": "USERNAME",
"value": "username"
},
{
"context": "late_id,\n username: username,\n password: password,\n text0: text0,\n text1: text1\n .post()",
"end": 5147,
"score": 0.9991069436073303,
"start": 5139,
"tag": "PASSWORD",
"value": "password"
}
] | Hubot/imgflip.coffee | FaytLeingod007/JabbR | 3 | # Description:
# Generates memes via the Imgflip Meme Generator API
#
# Dependencies:
# None
#
# Configuration:
# IMGFLIP_API_USERNAME [optional, overrides default imgflip_hubot account]
# IMGFLIP_API_PASSWORD [optional, overrides default imgflip_hubot account]
#
# Commands:
# hubot One does not simply <text> - Lord of the Rings Boromir
# hubot I don't always <text> but when i do <text> - The Most Interesting man in the World
# hubot aliens <text> - Ancient Aliens History Channel Guy
# hubot I'm not saying <text> but <text> - Ancient Aliens History Channel Guy
# hubot grumpy cat <text> - Grumpy Cat with text on the bottom
# hubot <text>, <text> everywhere - X, X Everywhere (Buzz and Woody from Toy Story)
# hubot Not sure if <text> or <text> - Futurama Fry
# hubot Y U NO <text> - Y U NO Guy
# hubot Brace yourselves <text> - Brace Yourselves X is Coming (Imminent Ned, Game of Thrones)
# hubot <text> all the <text> - X all the Y
# hubot <text> that would be great - Bill Lumbergh from Office Space
# hubot <text> too damn <text> - The rent is too damn high
# hubot Yo dawg <text> so <text> - Yo Dawg Heard You (Xzibit)
# hubot <text> you're gonna have a bad time - Super Cool Ski Instructor from South Park
# hubot Am I the only one around here <text> - The Big Lebowski
# hubot What if I told you <text> - Matrix Morpheus
# hubot <text> ain't nobody got time for that
# hubot <text> I guarantee it - George Zimmer
# hubot <text> and it's gone - South Park Banker Guy
# hubot <text> nobody bats an eye <text> everyone loses their minds - Heath Ledger Joker
# hubot back in my day <text> - Grumpy old man
# hubot picardWTF <text>:<text> - Picard WTF is this meme
# hubot badluckbrian <text>:<text> - Bad luck Brian
# hubot wat <text> - Wat lady
# hubot <text> for me to poop on - Triumph the Comic insult dog
#
# Author:
# dylanwenzlau
inspect = require('util').inspect
module.exports = (robot) ->
unless robot.brain.data.imgflip_memes?
robot.brain.data.imgflip_memes = [
{
regex: /(one does not simply) (.*)/i,
template_id: 61579
},
{
regex: /(i don'?t always .*) (but when i do,? .*)/i,
template_id: 61532
},
{
regex: /aliens ()(.*)/i,
template_id: 101470
},
{
regex: /(I'm not saying .*) (but .*)/i,
template_id: 101470
},
{
regex: /grumpy cat ()(.*)/i,
template_id: 405658
},
{
regex: /(.*),? (\1 everywhere)/i,
template_id: 347390
},
{
regex: /(not sure if .*) (or .*)/i,
template_id: 61520
},
{
regex: /(y u no) (.+)/i,
template_id: 61527
},
{
regex: /(brace yoursel[^\s]+) (.*)/i,
template_id: 61546
},
{
regex: /(.*) (all the .*)/i,
template_id: 61533
},
{
regex: /(.*) (that would be great|that'?d be great)/i,
template_id: 563423
},
{
regex: /(.*) (\w+\stoo damn .*)/i,
template_id: 61580
},
{
regex: /(yo dawg .*) (so .*)/i,
template_id: 101716
},
{
regex: /(.*) (.* gonna have a bad time)/i,
template_id: 100951
},
{
regex: /(am i the only one around here) (.*)/i,
template_id: 259680
},
{
regex: /(what if i told you) (.*)/i,
template_id: 100947
},
{
regex: /(.*) (ain'?t nobody got time for? that)/i,
template_id: 442575
},
{
regex: /(.*) (i guarantee it)/i,
template_id: 10672255
},
{
regex: /(.*) (a+n+d+ it'?s gone)/i,
template_id: 766986
},
{
regex: /(.* bats an eye) (.* loses their minds?)/i,
template_id: 1790995
},
{
regex: /(back in my day) (.*)/i,
template_id: 718432
},
{
regex: /picardWTF (.*):(.*)/i,
template_id: 245898
},
{
regex: /badluckbrian (.*):(.*)/i,
template_id: 61585
},
{
regex: /(wat) (.*)/i,
template_id: 3643225
},
{
regex: /(.*) (and you should feel bad)/,
template_id: 35747
},
{
regex: /(.*) (for me to poop on)/,
template_id: 16852201
}
]
for meme in robot.brain.data.imgflip_memes
setupResponder robot, meme
setupResponder = (robot, meme) ->
robot.respond meme.regex, (msg) ->
generateMeme msg, meme.template_id, msg.match[1], msg.match[2]
generateMeme = (msg, template_id, text0, text1) ->
username = process.env.IMGFLIP_API_USERNAME
password = process.env.IMGFLIP_API_PASSWORD
if (username or password) and not (username and password)
msg.reply 'To use your own Imgflip account, you need to specify username and password!'
return
if not username
username = 'imgflip_hubot'
password = 'imgflip_hubot'
msg.http('https://api.imgflip.com/caption_image')
.query
template_id: template_id,
username: username,
password: password,
text0: text0,
text1: text1
.post() (error, res, body) ->
if error
msg.reply "I got an error when talking to imgflip:", inspect(error)
return
result = JSON.parse(body)
success = result.success
errorMessage = result.error_message
if not success
msg.reply "Imgflip API request failed: #{errorMessage}"
return
msg.send result.data.url
| 118557 | # Description:
# Generates memes via the Imgflip Meme Generator API
#
# Dependencies:
# None
#
# Configuration:
# IMGFLIP_API_USERNAME [optional, overrides default imgflip_hubot account]
# IMGFLIP_API_PASSWORD [optional, overrides default imgflip_hubot account]
#
# Commands:
# hubot One does not simply <text> - Lord of the Rings Boromir
# hubot I don't always <text> but when i do <text> - The Most Interesting man in the World
# hubot aliens <text> - Ancient Aliens History Channel Guy
# hubot I'm not saying <text> but <text> - Ancient Aliens History Channel Guy
# hubot grumpy cat <text> - Grumpy Cat with text on the bottom
# hubot <text>, <text> everywhere - X, X Everywhere (Buzz and Woody from Toy Story)
# hubot Not sure if <text> or <text> - Futurama Fry
# hubot Y U NO <text> - Y U NO Guy
# hubot Brace yourselves <text> - Brace Yourselves X is Coming (Imminent Ned, Game of Thrones)
# hubot <text> all the <text> - X all the Y
# hubot <text> that would be great - <NAME> from Office Space
# hubot <text> too damn <text> - The rent is too damn high
# hubot Yo dawg <text> so <text> - Yo Dawg Heard You (Xzibit)
# hubot <text> you're gonna have a bad time - Super Cool Ski Instructor from South Park
# hubot Am I the only one around here <text> - The Big Lebowski
# hubot What if I told you <text> - Matrix Morpheus
# hubot <text> ain't nobody got time for that
# hubot <text> I guarantee it - <NAME>
# hubot <text> and it's gone - South Park Banker Guy
# hubot <text> nobody bats an eye <text> everyone loses their minds - Heath Ledger Joker
# hubot back in my day <text> - Grumpy old man
# hubot picardWTF <text>:<text> - Picard WTF is this meme
# hubot badluckbrian <text>:<text> - Bad luck Brian
# hubot wat <text> - Wat lady
# hubot <text> for me to poop on - Triumph the Comic insult dog
#
# Author:
# dylanwenzlau
inspect = require('util').inspect
module.exports = (robot) ->
unless robot.brain.data.imgflip_memes?
robot.brain.data.imgflip_memes = [
{
regex: /(one does not simply) (.*)/i,
template_id: 61579
},
{
regex: /(i don'?t always .*) (but when i do,? .*)/i,
template_id: 61532
},
{
regex: /aliens ()(.*)/i,
template_id: 101470
},
{
regex: /(I'm not saying .*) (but .*)/i,
template_id: 101470
},
{
regex: /grumpy cat ()(.*)/i,
template_id: 405658
},
{
regex: /(.*),? (\1 everywhere)/i,
template_id: 347390
},
{
regex: /(not sure if .*) (or .*)/i,
template_id: 61520
},
{
regex: /(y u no) (.+)/i,
template_id: 61527
},
{
regex: /(brace yoursel[^\s]+) (.*)/i,
template_id: 61546
},
{
regex: /(.*) (all the .*)/i,
template_id: 61533
},
{
regex: /(.*) (that would be great|that'?d be great)/i,
template_id: 563423
},
{
regex: /(.*) (\w+\stoo damn .*)/i,
template_id: 61580
},
{
regex: /(yo dawg .*) (so .*)/i,
template_id: 101716
},
{
regex: /(.*) (.* gonna have a bad time)/i,
template_id: 100951
},
{
regex: /(am i the only one around here) (.*)/i,
template_id: 259680
},
{
regex: /(what if i told you) (.*)/i,
template_id: 100947
},
{
regex: /(.*) (ain'?t nobody got time for? that)/i,
template_id: 442575
},
{
regex: /(.*) (i guarantee it)/i,
template_id: 10672255
},
{
regex: /(.*) (a+n+d+ it'?s gone)/i,
template_id: 766986
},
{
regex: /(.* bats an eye) (.* loses their minds?)/i,
template_id: 1790995
},
{
regex: /(back in my day) (.*)/i,
template_id: 718432
},
{
regex: /picardWTF (.*):(.*)/i,
template_id: 245898
},
{
regex: /badluckbrian (.*):(.*)/i,
template_id: 61585
},
{
regex: /(wat) (.*)/i,
template_id: 3643225
},
{
regex: /(.*) (and you should feel bad)/,
template_id: 35747
},
{
regex: /(.*) (for me to poop on)/,
template_id: 16852201
}
]
for meme in robot.brain.data.imgflip_memes
setupResponder robot, meme
setupResponder = (robot, meme) ->
robot.respond meme.regex, (msg) ->
generateMeme msg, meme.template_id, msg.match[1], msg.match[2]
generateMeme = (msg, template_id, text0, text1) ->
username = process.env.IMGFLIP_API_USERNAME
password = <PASSWORD>.IMGFLIP_API_PASSWORD
if (username or password) and not (username and password)
msg.reply 'To use your own Imgflip account, you need to specify username and password!'
return
if not username
username = 'imgflip_hubot'
password = '<PASSWORD>'
msg.http('https://api.imgflip.com/caption_image')
.query
template_id: template_id,
username: username,
password: <PASSWORD>,
text0: text0,
text1: text1
.post() (error, res, body) ->
if error
msg.reply "I got an error when talking to imgflip:", inspect(error)
return
result = JSON.parse(body)
success = result.success
errorMessage = result.error_message
if not success
msg.reply "Imgflip API request failed: #{errorMessage}"
return
msg.send result.data.url
| true | # Description:
# Generates memes via the Imgflip Meme Generator API
#
# Dependencies:
# None
#
# Configuration:
# IMGFLIP_API_USERNAME [optional, overrides default imgflip_hubot account]
# IMGFLIP_API_PASSWORD [optional, overrides default imgflip_hubot account]
#
# Commands:
# hubot One does not simply <text> - Lord of the Rings Boromir
# hubot I don't always <text> but when i do <text> - The Most Interesting man in the World
# hubot aliens <text> - Ancient Aliens History Channel Guy
# hubot I'm not saying <text> but <text> - Ancient Aliens History Channel Guy
# hubot grumpy cat <text> - Grumpy Cat with text on the bottom
# hubot <text>, <text> everywhere - X, X Everywhere (Buzz and Woody from Toy Story)
# hubot Not sure if <text> or <text> - Futurama Fry
# hubot Y U NO <text> - Y U NO Guy
# hubot Brace yourselves <text> - Brace Yourselves X is Coming (Imminent Ned, Game of Thrones)
# hubot <text> all the <text> - X all the Y
# hubot <text> that would be great - PI:NAME:<NAME>END_PI from Office Space
# hubot <text> too damn <text> - The rent is too damn high
# hubot Yo dawg <text> so <text> - Yo Dawg Heard You (Xzibit)
# hubot <text> you're gonna have a bad time - Super Cool Ski Instructor from South Park
# hubot Am I the only one around here <text> - The Big Lebowski
# hubot What if I told you <text> - Matrix Morpheus
# hubot <text> ain't nobody got time for that
# hubot <text> I guarantee it - PI:NAME:<NAME>END_PI
# hubot <text> and it's gone - South Park Banker Guy
# hubot <text> nobody bats an eye <text> everyone loses their minds - Heath Ledger Joker
# hubot back in my day <text> - Grumpy old man
# hubot picardWTF <text>:<text> - Picard WTF is this meme
# hubot badluckbrian <text>:<text> - Bad luck Brian
# hubot wat <text> - Wat lady
# hubot <text> for me to poop on - Triumph the Comic insult dog
#
# Author:
# dylanwenzlau
inspect = require('util').inspect
module.exports = (robot) ->
unless robot.brain.data.imgflip_memes?
robot.brain.data.imgflip_memes = [
{
regex: /(one does not simply) (.*)/i,
template_id: 61579
},
{
regex: /(i don'?t always .*) (but when i do,? .*)/i,
template_id: 61532
},
{
regex: /aliens ()(.*)/i,
template_id: 101470
},
{
regex: /(I'm not saying .*) (but .*)/i,
template_id: 101470
},
{
regex: /grumpy cat ()(.*)/i,
template_id: 405658
},
{
regex: /(.*),? (\1 everywhere)/i,
template_id: 347390
},
{
regex: /(not sure if .*) (or .*)/i,
template_id: 61520
},
{
regex: /(y u no) (.+)/i,
template_id: 61527
},
{
regex: /(brace yoursel[^\s]+) (.*)/i,
template_id: 61546
},
{
regex: /(.*) (all the .*)/i,
template_id: 61533
},
{
regex: /(.*) (that would be great|that'?d be great)/i,
template_id: 563423
},
{
regex: /(.*) (\w+\stoo damn .*)/i,
template_id: 61580
},
{
regex: /(yo dawg .*) (so .*)/i,
template_id: 101716
},
{
regex: /(.*) (.* gonna have a bad time)/i,
template_id: 100951
},
{
regex: /(am i the only one around here) (.*)/i,
template_id: 259680
},
{
regex: /(what if i told you) (.*)/i,
template_id: 100947
},
{
regex: /(.*) (ain'?t nobody got time for? that)/i,
template_id: 442575
},
{
regex: /(.*) (i guarantee it)/i,
template_id: 10672255
},
{
regex: /(.*) (a+n+d+ it'?s gone)/i,
template_id: 766986
},
{
regex: /(.* bats an eye) (.* loses their minds?)/i,
template_id: 1790995
},
{
regex: /(back in my day) (.*)/i,
template_id: 718432
},
{
regex: /picardWTF (.*):(.*)/i,
template_id: 245898
},
{
regex: /badluckbrian (.*):(.*)/i,
template_id: 61585
},
{
regex: /(wat) (.*)/i,
template_id: 3643225
},
{
regex: /(.*) (and you should feel bad)/,
template_id: 35747
},
{
regex: /(.*) (for me to poop on)/,
template_id: 16852201
}
]
for meme in robot.brain.data.imgflip_memes
setupResponder robot, meme
setupResponder = (robot, meme) ->
robot.respond meme.regex, (msg) ->
generateMeme msg, meme.template_id, msg.match[1], msg.match[2]
generateMeme = (msg, template_id, text0, text1) ->
username = process.env.IMGFLIP_API_USERNAME
password = PI:PASSWORD:<PASSWORD>END_PI.IMGFLIP_API_PASSWORD
if (username or password) and not (username and password)
msg.reply 'To use your own Imgflip account, you need to specify username and password!'
return
if not username
username = 'imgflip_hubot'
password = 'PI:PASSWORD:<PASSWORD>END_PI'
msg.http('https://api.imgflip.com/caption_image')
.query
template_id: template_id,
username: username,
password: PI:PASSWORD:<PASSWORD>END_PI,
text0: text0,
text1: text1
.post() (error, res, body) ->
if error
msg.reply "I got an error when talking to imgflip:", inspect(error)
return
result = JSON.parse(body)
success = result.success
errorMessage = result.error_message
if not success
msg.reply "Imgflip API request failed: #{errorMessage}"
return
msg.send result.data.url
|
[
{
"context": "tring} Password to login to the api. Defaults to 'guest'\n #\n constructor: (options = {}) ->\n ",
"end": 1326,
"score": 0.7222076654434204,
"start": 1321,
"tag": "PASSWORD",
"value": "guest"
},
{
"context": "ltPublishOptions, options\n routing_key: queueName\n payload: JSON.stringify data\n ",
"end": 2281,
"score": 0.8241029977798462,
"start": 2272,
"tag": "KEY",
"value": "queueName"
}
] | src/RabbitHttpClient.coffee | topliceanu/rabbitmq-client | 1 | _ = require 'underscore'
request = require 'request'
Q = require 'q'
Client = require './Client'
util = require './util'
# Communicate with RabbitMQ server through the HTTP API which can be started
# by enabling the rabbitmq management plugin.
#
# @note All message consumed by the http client off a queue are immediately ACKed!
#
class RabbitHttpClient extends Client
# Default message publishing options.
defaultPublishOptions: {}
# Default message consumption options.
defaultReadOptions:
# How many messages to consume with one request. By default it's 1.
count: 1
# Whether to re-enqueue the messages after consumption. By default it's false.
requeue: false
# Default encoding to use for message payloads.
encoding: 'auto'
# Constructs a rabbitmq client using the http protocol
#
# @param {Object} options
# @option host {String} Ip of machine where rabbitmq server is installed. Defaults to 'localhost'.
# @option port {Number} Port where the rabbitmq server is listening. Defaults to 15672 for http.
# @option vhost {String} Rabbitmq virtual host. Defaults to '/'.
# @option login {String} Username to login to the api. Defaults to 'guest'
# @option password {String} Password to login to the api. Defaults to 'guest'
#
constructor: (options = {}) ->
options?.port = 15672
super options
# Publishes a message to a RabbitMQ queue on the default
# exchange (amq.default) using the REST API.
# @param {String} queueName
# @param {Object} queueOpts
# @return {Object} Q.Promise resolving to a Queue instance.
# @example
# curl -i -u <user>:<pass> \
# -H 'content-type:application/json' \
# -d '{
# "properties":<options>,
# "routing_key":<queueName>,
# "payload":<data>,
# "payload_encoding":"string"
# }' \
# -XPOST http://rabbitmq/api/exchanges/%2f/amq.default/publish
#
publish: (queueName, data, options = {}) ->
endpoint = '/api/exchanges/%2f/amq.default/publish'
body =
properties: _.extend @defaultPublishOptions, options
routing_key: queueName
payload: JSON.stringify data
payload_encoding: 'string'
(@call endpoint, body).then (result) ->
if result?.routed isnt true
Q.reject new Error 'Message was not published'
else
Q()
# Retrieves a message from a RabbitMQ endpoint and
# consume it at the same time (ie. send ACK).
#
# @example
# curl -i -u vibetrace:V2PBCZLa0dS2 \
# -H 'content-type:application/json' \
# -d '{
# "count":1,
# "requeue":false,
# "encoding":"auto"
# }' \
# -XPOST http://rabbitmq/api/queues/%2f/<queueName>/get
#
# @param {String} queueName - name of the queue to subscribe to.
# @param {Object} options - list of options to read
# @option count {Boolean} How many messages to consume with one request. By default it's 1.
# @option requeue {Boolean} Whether to re-enqueue the messages after consumption. By default it's false.
# @option encoding {String} Default encoding to use for message payloads.
# @return {Object} Q.Promise resolves to an Array<String> of messages.
#
consume: (queueName, options = {}) ->
endpoint = "/api/queues/%2f/#{queueName}/get"
body = _.extend {}, @defaultReadOptions, options
(@call endpoint, body).then (messages) ->
Q _(messages).chain().pluck('payload').map(JSON.parse).value()
# This method polls the queue endpoint and consumes data as soon as
# it appears.
#
# It implements a fibonacci polling mechanism to
# ensure efficient bandwidth consumption, ie. whenever a call to
# the queue returns empty results, it will wait that much longer
# before calling again. If the call returns data, it will fetch more
# data immediately after consumption.
#
# To implement the api of the native rabbitmq client, the callback
# executed for each message also receives the ack function which it
# will call whenever the message is consumed. This is fake as
# the message is already consumed by the time it reaches the callback.
#
# @param queueName {String} The queue will be created if it does not exist.
# @param callback {Function} whenever a new message is retrieved this callback is executed. Signature: function (error, message, ack) {..}
# @param options {Object} extra params
# @option count {Number} Number of messages to consume. Defaults to 10.
#
subscribe: (queueName, callback, options = {}) ->
options.count ?= 10
call = =>
@log 'info', 'polling the rabbitmq queue', queueName
(@consume queueName, count: options.count).then (messages) ->
unless messages?.length > 0
return Q.reject new Error 'Nothing to consume'
steps = _.map messages, (message) ->
return ->
deferred = Q.defer()
callback null, message, deferred.makeNodeResolver()
deferred.promise
util.pipe steps, null, ignoreErrors: true
util.backoff call,
strategy: 'fibonacci'
maxDelay: 1 * 60 * 1000
startImmediately: true
# Utility method to call an HTTP endpoint given
#
# @private
# @param endpoint {String} Http path&query string of the url to call.
# @param body {Object} Http request body.
# @return {Q.promise} Resolves when the call is completed.
#
call: (endpoint, body) ->
options =
method: 'POST'
url: "http://#{@options.host}:#{@options.port}#{endpoint}"
auth:
user: @options.login
pass: @options.password
sendImmediately: true
header:
'Content-type': 'application/json'
'Accept': 'application/json'
body: JSON.stringify body
deferred = Q.defer()
request options, (error, response, body) ->
if error? then return deferred.reject error
unless response.statusCode is 200
return deferred.reject new Error body
deferred.resolve JSON.parse body
deferred.promise
# Public API.
module.exports = RabbitHttpClient
| 26504 | _ = require 'underscore'
request = require 'request'
Q = require 'q'
Client = require './Client'
util = require './util'
# Communicate with RabbitMQ server through the HTTP API which can be started
# by enabling the rabbitmq management plugin.
#
# @note All message consumed by the http client off a queue are immediately ACKed!
#
class RabbitHttpClient extends Client
# Default message publishing options.
defaultPublishOptions: {}
# Default message consumption options.
defaultReadOptions:
# How many messages to consume with one request. By default it's 1.
count: 1
# Whether to re-enqueue the messages after consumption. By default it's false.
requeue: false
# Default encoding to use for message payloads.
encoding: 'auto'
# Constructs a rabbitmq client using the http protocol
#
# @param {Object} options
# @option host {String} Ip of machine where rabbitmq server is installed. Defaults to 'localhost'.
# @option port {Number} Port where the rabbitmq server is listening. Defaults to 15672 for http.
# @option vhost {String} Rabbitmq virtual host. Defaults to '/'.
# @option login {String} Username to login to the api. Defaults to 'guest'
# @option password {String} Password to login to the api. Defaults to '<PASSWORD>'
#
constructor: (options = {}) ->
options?.port = 15672
super options
# Publishes a message to a RabbitMQ queue on the default
# exchange (amq.default) using the REST API.
# @param {String} queueName
# @param {Object} queueOpts
# @return {Object} Q.Promise resolving to a Queue instance.
# @example
# curl -i -u <user>:<pass> \
# -H 'content-type:application/json' \
# -d '{
# "properties":<options>,
# "routing_key":<queueName>,
# "payload":<data>,
# "payload_encoding":"string"
# }' \
# -XPOST http://rabbitmq/api/exchanges/%2f/amq.default/publish
#
publish: (queueName, data, options = {}) ->
endpoint = '/api/exchanges/%2f/amq.default/publish'
body =
properties: _.extend @defaultPublishOptions, options
routing_key: <KEY>
payload: JSON.stringify data
payload_encoding: 'string'
(@call endpoint, body).then (result) ->
if result?.routed isnt true
Q.reject new Error 'Message was not published'
else
Q()
# Retrieves a message from a RabbitMQ endpoint and
# consume it at the same time (ie. send ACK).
#
# @example
# curl -i -u vibetrace:V2PBCZLa0dS2 \
# -H 'content-type:application/json' \
# -d '{
# "count":1,
# "requeue":false,
# "encoding":"auto"
# }' \
# -XPOST http://rabbitmq/api/queues/%2f/<queueName>/get
#
# @param {String} queueName - name of the queue to subscribe to.
# @param {Object} options - list of options to read
# @option count {Boolean} How many messages to consume with one request. By default it's 1.
# @option requeue {Boolean} Whether to re-enqueue the messages after consumption. By default it's false.
# @option encoding {String} Default encoding to use for message payloads.
# @return {Object} Q.Promise resolves to an Array<String> of messages.
#
consume: (queueName, options = {}) ->
endpoint = "/api/queues/%2f/#{queueName}/get"
body = _.extend {}, @defaultReadOptions, options
(@call endpoint, body).then (messages) ->
Q _(messages).chain().pluck('payload').map(JSON.parse).value()
# This method polls the queue endpoint and consumes data as soon as
# it appears.
#
# It implements a fibonacci polling mechanism to
# ensure efficient bandwidth consumption, ie. whenever a call to
# the queue returns empty results, it will wait that much longer
# before calling again. If the call returns data, it will fetch more
# data immediately after consumption.
#
# To implement the api of the native rabbitmq client, the callback
# executed for each message also receives the ack function which it
# will call whenever the message is consumed. This is fake as
# the message is already consumed by the time it reaches the callback.
#
# @param queueName {String} The queue will be created if it does not exist.
# @param callback {Function} whenever a new message is retrieved this callback is executed. Signature: function (error, message, ack) {..}
# @param options {Object} extra params
# @option count {Number} Number of messages to consume. Defaults to 10.
#
subscribe: (queueName, callback, options = {}) ->
options.count ?= 10
call = =>
@log 'info', 'polling the rabbitmq queue', queueName
(@consume queueName, count: options.count).then (messages) ->
unless messages?.length > 0
return Q.reject new Error 'Nothing to consume'
steps = _.map messages, (message) ->
return ->
deferred = Q.defer()
callback null, message, deferred.makeNodeResolver()
deferred.promise
util.pipe steps, null, ignoreErrors: true
util.backoff call,
strategy: 'fibonacci'
maxDelay: 1 * 60 * 1000
startImmediately: true
# Utility method to call an HTTP endpoint given
#
# @private
# @param endpoint {String} Http path&query string of the url to call.
# @param body {Object} Http request body.
# @return {Q.promise} Resolves when the call is completed.
#
call: (endpoint, body) ->
options =
method: 'POST'
url: "http://#{@options.host}:#{@options.port}#{endpoint}"
auth:
user: @options.login
pass: @options.password
sendImmediately: true
header:
'Content-type': 'application/json'
'Accept': 'application/json'
body: JSON.stringify body
deferred = Q.defer()
request options, (error, response, body) ->
if error? then return deferred.reject error
unless response.statusCode is 200
return deferred.reject new Error body
deferred.resolve JSON.parse body
deferred.promise
# Public API.
module.exports = RabbitHttpClient
| true | _ = require 'underscore'
request = require 'request'
Q = require 'q'
Client = require './Client'
util = require './util'
# Communicate with RabbitMQ server through the HTTP API which can be started
# by enabling the rabbitmq management plugin.
#
# @note All message consumed by the http client off a queue are immediately ACKed!
#
class RabbitHttpClient extends Client
# Default message publishing options.
defaultPublishOptions: {}
# Default message consumption options.
defaultReadOptions:
# How many messages to consume with one request. By default it's 1.
count: 1
# Whether to re-enqueue the messages after consumption. By default it's false.
requeue: false
# Default encoding to use for message payloads.
encoding: 'auto'
# Constructs a rabbitmq client using the http protocol
#
# @param {Object} options
# @option host {String} Ip of machine where rabbitmq server is installed. Defaults to 'localhost'.
# @option port {Number} Port where the rabbitmq server is listening. Defaults to 15672 for http.
# @option vhost {String} Rabbitmq virtual host. Defaults to '/'.
# @option login {String} Username to login to the api. Defaults to 'guest'
# @option password {String} Password to login to the api. Defaults to 'PI:PASSWORD:<PASSWORD>END_PI'
#
constructor: (options = {}) ->
options?.port = 15672
super options
# Publishes a message to a RabbitMQ queue on the default
# exchange (amq.default) using the REST API.
# @param {String} queueName
# @param {Object} queueOpts
# @return {Object} Q.Promise resolving to a Queue instance.
# @example
# curl -i -u <user>:<pass> \
# -H 'content-type:application/json' \
# -d '{
# "properties":<options>,
# "routing_key":<queueName>,
# "payload":<data>,
# "payload_encoding":"string"
# }' \
# -XPOST http://rabbitmq/api/exchanges/%2f/amq.default/publish
#
publish: (queueName, data, options = {}) ->
endpoint = '/api/exchanges/%2f/amq.default/publish'
body =
properties: _.extend @defaultPublishOptions, options
routing_key: PI:KEY:<KEY>END_PI
payload: JSON.stringify data
payload_encoding: 'string'
(@call endpoint, body).then (result) ->
if result?.routed isnt true
Q.reject new Error 'Message was not published'
else
Q()
# Retrieves a message from a RabbitMQ endpoint and
# consume it at the same time (ie. send ACK).
#
# @example
# curl -i -u vibetrace:V2PBCZLa0dS2 \
# -H 'content-type:application/json' \
# -d '{
# "count":1,
# "requeue":false,
# "encoding":"auto"
# }' \
# -XPOST http://rabbitmq/api/queues/%2f/<queueName>/get
#
# @param {String} queueName - name of the queue to subscribe to.
# @param {Object} options - list of options to read
# @option count {Boolean} How many messages to consume with one request. By default it's 1.
# @option requeue {Boolean} Whether to re-enqueue the messages after consumption. By default it's false.
# @option encoding {String} Default encoding to use for message payloads.
# @return {Object} Q.Promise resolves to an Array<String> of messages.
#
consume: (queueName, options = {}) ->
endpoint = "/api/queues/%2f/#{queueName}/get"
body = _.extend {}, @defaultReadOptions, options
(@call endpoint, body).then (messages) ->
Q _(messages).chain().pluck('payload').map(JSON.parse).value()
# This method polls the queue endpoint and consumes data as soon as
# it appears.
#
# It implements a fibonacci polling mechanism to
# ensure efficient bandwidth consumption, ie. whenever a call to
# the queue returns empty results, it will wait that much longer
# before calling again. If the call returns data, it will fetch more
# data immediately after consumption.
#
# To implement the api of the native rabbitmq client, the callback
# executed for each message also receives the ack function which it
# will call whenever the message is consumed. This is fake as
# the message is already consumed by the time it reaches the callback.
#
# @param queueName {String} The queue will be created if it does not exist.
# @param callback {Function} whenever a new message is retrieved this callback is executed. Signature: function (error, message, ack) {..}
# @param options {Object} extra params
# @option count {Number} Number of messages to consume. Defaults to 10.
#
subscribe: (queueName, callback, options = {}) ->
options.count ?= 10
call = =>
@log 'info', 'polling the rabbitmq queue', queueName
(@consume queueName, count: options.count).then (messages) ->
unless messages?.length > 0
return Q.reject new Error 'Nothing to consume'
steps = _.map messages, (message) ->
return ->
deferred = Q.defer()
callback null, message, deferred.makeNodeResolver()
deferred.promise
util.pipe steps, null, ignoreErrors: true
util.backoff call,
strategy: 'fibonacci'
maxDelay: 1 * 60 * 1000
startImmediately: true
# Utility method to call an HTTP endpoint given
#
# @private
# @param endpoint {String} Http path&query string of the url to call.
# @param body {Object} Http request body.
# @return {Q.promise} Resolves when the call is completed.
#
call: (endpoint, body) ->
options =
method: 'POST'
url: "http://#{@options.host}:#{@options.port}#{endpoint}"
auth:
user: @options.login
pass: @options.password
sendImmediately: true
header:
'Content-type': 'application/json'
'Accept': 'application/json'
body: JSON.stringify body
deferred = Q.defer()
request options, (error, response, body) ->
if error? then return deferred.reject error
unless response.statusCode is 200
return deferred.reject new Error body
deferred.resolve JSON.parse body
deferred.promise
# Public API.
module.exports = RabbitHttpClient
|
[
{
"context": "# Copyright (c) 2015 Jesse Grosjean. All rights reserved.\n\nFoldingTextService = requi",
"end": 35,
"score": 0.999733567237854,
"start": 21,
"tag": "NAME",
"value": "Jesse Grosjean"
}
] | atom/packages/foldingtext-for-atom/lib/extensions/text-formatting-popover.coffee | prookie/dotfiles-1 | 0 | # Copyright (c) 2015 Jesse Grosjean. All rights reserved.
FoldingTextService = require '../foldingtext-service'
{Disposable, CompositeDisposable} = require 'atom'
class TextFormattingPopover extends HTMLElement
constructor: ->
super()
createdCallback: ->
@classList.add 'btn-toolbar'
@formattingButtonGroup = document.createElement 'div'
@formattingButtonGroup.classList.add 'btn-group'
@appendChild @formattingButtonGroup
@boldButton = document.createElement 'button'
@boldButton.className = 'btn fa fa-bold fa-lg'
@boldButton.setAttribute 'data-command', 'outline-editor:toggle-bold'
@formattingButtonGroup.appendChild @boldButton
@italicButton = document.createElement 'button'
@italicButton.className = 'btn fa fa-italic fa-lg'
@italicButton.setAttribute 'data-command', 'outline-editor:toggle-italic'
@formattingButtonGroup.appendChild @italicButton
@underlineButton = document.createElement 'button'
@underlineButton.className = 'btn fa fa-underline fa-lg'
@underlineButton.setAttribute 'data-command', 'outline-editor:toggle-underline'
@formattingButtonGroup.appendChild @underlineButton
@linkButton = document.createElement 'button'
@linkButton.className = 'btn fa fa-link fa-lg'
@linkButton.setAttribute 'data-command', 'outline-editor:edit-link'
@formattingButtonGroup.appendChild @linkButton
@clearFormattingButton = document.createElement 'button'
@clearFormattingButton.className = 'btn fa fa-eraser fa-lg'
@clearFormattingButton.setAttribute 'data-command', 'outline-editor:clear-formatting'
@formattingButtonGroup.appendChild @clearFormattingButton
###
@headingButton = document.createElement 'button'
@headingButton.className = 'btn fa fa-header fa-lg'
@headingButton.setAttribute 'data-command', 'outline-editor:edit-link'
@formattingButtonGroup.appendChild @headingButton
@statusButton = document.createElement 'button'
@statusButton.className = 'btn fa fa-check fa-lg'
@statusButton.setAttribute 'data-command', 'outline-editor:toggle-status-complete'
@formattingButtonGroup.appendChild @statusButton
@tagsButton = document.createElement 'button'
@tagsButton.className = 'btn fa fa-tags fa-lg'
@tagsButton.setAttribute 'data-command', 'outline-editor:edit-tags'
@formattingButtonGroup.appendChild @tagsButton
###
attachedCallback: ->
@tooltipSubs = new CompositeDisposable
@tooltipSubs.add atom.tooltips.add @boldButton,
title: "Bold",
keyBindingCommand: 'outline-editor:toggle-bold'
@tooltipSubs.add atom.tooltips.add @italicButton,
title: "Italic",
keyBindingCommand: 'outline-editor:toggle-italic'
@tooltipSubs.add atom.tooltips.add @underlineButton,
title: "Underline",
keyBindingCommand: 'outline-editor:edit-underline'
@tooltipSubs.add atom.tooltips.add @linkButton,
title: "Edit Link",
keyBindingCommand: 'outline-editor:edit-link'
@tooltipSubs.add atom.tooltips.add @clearFormattingButton,
title: "Clear Formatting",
keyBindingCommand: 'outline-editor:clear-formatting'
detachedCallback: ->
@tooltipSubs.dispose()
validateButtons: ->
formattingTags = FoldingTextService.getActiveOutlineEditor()?.getTypingFormattingTags() or {}
unless @boldButton.classList.contains('selected') is formattingTags['B']?
@boldButton.classList.toggle('selected')
unless @italicButton.classList.contains('selected') is formattingTags['I']?
@italicButton.classList.toggle('selected')
unless @underlineButton.classList.contains('selected') is formattingTags['U']?
@underlineButton.classList.toggle('selected')
unless @linkButton.classList.contains('selected') is formattingTags['A']?
@linkButton.classList.toggle('selected')
FoldingTextService.eventRegistery.listen 'ft-text-formatting-popover button',
mousedown: (e) ->
outlineEditorElement = FoldingTextService.getActiveOutlineEditor()?.outlineEditorElement
if outlineEditorElement and command = e.target.getAttribute?('data-command')
if command is 'outline-editor:edit-link'
formattingBarPanel.hide()
atom.commands.dispatch outlineEditorElement, command
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
formattingBar = document.createElement 'ft-text-formatting-popover'
formattingBarPanel = atom.workspace.addPopoverPanel
item: formattingBar
target: ->
FoldingTextService.getActiveOutlineEditor()?.selection?.selectionClientRect
viewport: ->
FoldingTextService.getActiveOutlineEditor()?.outlineEditorElement.getBoundingClientRect()
FoldingTextService.observeActiveOutlineEditorSelection (selection) ->
if selection?.isTextMode and not selection.isCollapsed and not selection.editor.outlineEditorElement.isPerformingExtendSelectionInteraction()
formattingBarPanel.show()
formattingBar.validateButtons()
else
formattingBarPanel.hide()
module.exports = document.registerElement 'ft-text-formatting-popover', prototype: TextFormattingPopover.prototype | 223210 | # Copyright (c) 2015 <NAME>. All rights reserved.
FoldingTextService = require '../foldingtext-service'
{Disposable, CompositeDisposable} = require 'atom'
class TextFormattingPopover extends HTMLElement
constructor: ->
super()
createdCallback: ->
@classList.add 'btn-toolbar'
@formattingButtonGroup = document.createElement 'div'
@formattingButtonGroup.classList.add 'btn-group'
@appendChild @formattingButtonGroup
@boldButton = document.createElement 'button'
@boldButton.className = 'btn fa fa-bold fa-lg'
@boldButton.setAttribute 'data-command', 'outline-editor:toggle-bold'
@formattingButtonGroup.appendChild @boldButton
@italicButton = document.createElement 'button'
@italicButton.className = 'btn fa fa-italic fa-lg'
@italicButton.setAttribute 'data-command', 'outline-editor:toggle-italic'
@formattingButtonGroup.appendChild @italicButton
@underlineButton = document.createElement 'button'
@underlineButton.className = 'btn fa fa-underline fa-lg'
@underlineButton.setAttribute 'data-command', 'outline-editor:toggle-underline'
@formattingButtonGroup.appendChild @underlineButton
@linkButton = document.createElement 'button'
@linkButton.className = 'btn fa fa-link fa-lg'
@linkButton.setAttribute 'data-command', 'outline-editor:edit-link'
@formattingButtonGroup.appendChild @linkButton
@clearFormattingButton = document.createElement 'button'
@clearFormattingButton.className = 'btn fa fa-eraser fa-lg'
@clearFormattingButton.setAttribute 'data-command', 'outline-editor:clear-formatting'
@formattingButtonGroup.appendChild @clearFormattingButton
###
@headingButton = document.createElement 'button'
@headingButton.className = 'btn fa fa-header fa-lg'
@headingButton.setAttribute 'data-command', 'outline-editor:edit-link'
@formattingButtonGroup.appendChild @headingButton
@statusButton = document.createElement 'button'
@statusButton.className = 'btn fa fa-check fa-lg'
@statusButton.setAttribute 'data-command', 'outline-editor:toggle-status-complete'
@formattingButtonGroup.appendChild @statusButton
@tagsButton = document.createElement 'button'
@tagsButton.className = 'btn fa fa-tags fa-lg'
@tagsButton.setAttribute 'data-command', 'outline-editor:edit-tags'
@formattingButtonGroup.appendChild @tagsButton
###
attachedCallback: ->
@tooltipSubs = new CompositeDisposable
@tooltipSubs.add atom.tooltips.add @boldButton,
title: "Bold",
keyBindingCommand: 'outline-editor:toggle-bold'
@tooltipSubs.add atom.tooltips.add @italicButton,
title: "Italic",
keyBindingCommand: 'outline-editor:toggle-italic'
@tooltipSubs.add atom.tooltips.add @underlineButton,
title: "Underline",
keyBindingCommand: 'outline-editor:edit-underline'
@tooltipSubs.add atom.tooltips.add @linkButton,
title: "Edit Link",
keyBindingCommand: 'outline-editor:edit-link'
@tooltipSubs.add atom.tooltips.add @clearFormattingButton,
title: "Clear Formatting",
keyBindingCommand: 'outline-editor:clear-formatting'
detachedCallback: ->
@tooltipSubs.dispose()
validateButtons: ->
formattingTags = FoldingTextService.getActiveOutlineEditor()?.getTypingFormattingTags() or {}
unless @boldButton.classList.contains('selected') is formattingTags['B']?
@boldButton.classList.toggle('selected')
unless @italicButton.classList.contains('selected') is formattingTags['I']?
@italicButton.classList.toggle('selected')
unless @underlineButton.classList.contains('selected') is formattingTags['U']?
@underlineButton.classList.toggle('selected')
unless @linkButton.classList.contains('selected') is formattingTags['A']?
@linkButton.classList.toggle('selected')
FoldingTextService.eventRegistery.listen 'ft-text-formatting-popover button',
mousedown: (e) ->
outlineEditorElement = FoldingTextService.getActiveOutlineEditor()?.outlineEditorElement
if outlineEditorElement and command = e.target.getAttribute?('data-command')
if command is 'outline-editor:edit-link'
formattingBarPanel.hide()
atom.commands.dispatch outlineEditorElement, command
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
formattingBar = document.createElement 'ft-text-formatting-popover'
formattingBarPanel = atom.workspace.addPopoverPanel
item: formattingBar
target: ->
FoldingTextService.getActiveOutlineEditor()?.selection?.selectionClientRect
viewport: ->
FoldingTextService.getActiveOutlineEditor()?.outlineEditorElement.getBoundingClientRect()
FoldingTextService.observeActiveOutlineEditorSelection (selection) ->
if selection?.isTextMode and not selection.isCollapsed and not selection.editor.outlineEditorElement.isPerformingExtendSelectionInteraction()
formattingBarPanel.show()
formattingBar.validateButtons()
else
formattingBarPanel.hide()
module.exports = document.registerElement 'ft-text-formatting-popover', prototype: TextFormattingPopover.prototype | true | # Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved.
FoldingTextService = require '../foldingtext-service'
{Disposable, CompositeDisposable} = require 'atom'
class TextFormattingPopover extends HTMLElement
constructor: ->
super()
createdCallback: ->
@classList.add 'btn-toolbar'
@formattingButtonGroup = document.createElement 'div'
@formattingButtonGroup.classList.add 'btn-group'
@appendChild @formattingButtonGroup
@boldButton = document.createElement 'button'
@boldButton.className = 'btn fa fa-bold fa-lg'
@boldButton.setAttribute 'data-command', 'outline-editor:toggle-bold'
@formattingButtonGroup.appendChild @boldButton
@italicButton = document.createElement 'button'
@italicButton.className = 'btn fa fa-italic fa-lg'
@italicButton.setAttribute 'data-command', 'outline-editor:toggle-italic'
@formattingButtonGroup.appendChild @italicButton
@underlineButton = document.createElement 'button'
@underlineButton.className = 'btn fa fa-underline fa-lg'
@underlineButton.setAttribute 'data-command', 'outline-editor:toggle-underline'
@formattingButtonGroup.appendChild @underlineButton
@linkButton = document.createElement 'button'
@linkButton.className = 'btn fa fa-link fa-lg'
@linkButton.setAttribute 'data-command', 'outline-editor:edit-link'
@formattingButtonGroup.appendChild @linkButton
@clearFormattingButton = document.createElement 'button'
@clearFormattingButton.className = 'btn fa fa-eraser fa-lg'
@clearFormattingButton.setAttribute 'data-command', 'outline-editor:clear-formatting'
@formattingButtonGroup.appendChild @clearFormattingButton
###
@headingButton = document.createElement 'button'
@headingButton.className = 'btn fa fa-header fa-lg'
@headingButton.setAttribute 'data-command', 'outline-editor:edit-link'
@formattingButtonGroup.appendChild @headingButton
@statusButton = document.createElement 'button'
@statusButton.className = 'btn fa fa-check fa-lg'
@statusButton.setAttribute 'data-command', 'outline-editor:toggle-status-complete'
@formattingButtonGroup.appendChild @statusButton
@tagsButton = document.createElement 'button'
@tagsButton.className = 'btn fa fa-tags fa-lg'
@tagsButton.setAttribute 'data-command', 'outline-editor:edit-tags'
@formattingButtonGroup.appendChild @tagsButton
###
attachedCallback: ->
@tooltipSubs = new CompositeDisposable
@tooltipSubs.add atom.tooltips.add @boldButton,
title: "Bold",
keyBindingCommand: 'outline-editor:toggle-bold'
@tooltipSubs.add atom.tooltips.add @italicButton,
title: "Italic",
keyBindingCommand: 'outline-editor:toggle-italic'
@tooltipSubs.add atom.tooltips.add @underlineButton,
title: "Underline",
keyBindingCommand: 'outline-editor:edit-underline'
@tooltipSubs.add atom.tooltips.add @linkButton,
title: "Edit Link",
keyBindingCommand: 'outline-editor:edit-link'
@tooltipSubs.add atom.tooltips.add @clearFormattingButton,
title: "Clear Formatting",
keyBindingCommand: 'outline-editor:clear-formatting'
detachedCallback: ->
@tooltipSubs.dispose()
validateButtons: ->
formattingTags = FoldingTextService.getActiveOutlineEditor()?.getTypingFormattingTags() or {}
unless @boldButton.classList.contains('selected') is formattingTags['B']?
@boldButton.classList.toggle('selected')
unless @italicButton.classList.contains('selected') is formattingTags['I']?
@italicButton.classList.toggle('selected')
unless @underlineButton.classList.contains('selected') is formattingTags['U']?
@underlineButton.classList.toggle('selected')
unless @linkButton.classList.contains('selected') is formattingTags['A']?
@linkButton.classList.toggle('selected')
FoldingTextService.eventRegistery.listen 'ft-text-formatting-popover button',
mousedown: (e) ->
outlineEditorElement = FoldingTextService.getActiveOutlineEditor()?.outlineEditorElement
if outlineEditorElement and command = e.target.getAttribute?('data-command')
if command is 'outline-editor:edit-link'
formattingBarPanel.hide()
atom.commands.dispatch outlineEditorElement, command
e.stopImmediatePropagation()
e.stopPropagation()
e.preventDefault()
formattingBar = document.createElement 'ft-text-formatting-popover'
formattingBarPanel = atom.workspace.addPopoverPanel
item: formattingBar
target: ->
FoldingTextService.getActiveOutlineEditor()?.selection?.selectionClientRect
viewport: ->
FoldingTextService.getActiveOutlineEditor()?.outlineEditorElement.getBoundingClientRect()
FoldingTextService.observeActiveOutlineEditorSelection (selection) ->
if selection?.isTextMode and not selection.isCollapsed and not selection.editor.outlineEditorElement.isPerformingExtendSelectionInteraction()
formattingBarPanel.show()
formattingBar.validateButtons()
else
formattingBarPanel.hide()
module.exports = document.registerElement 'ft-text-formatting-popover', prototype: TextFormattingPopover.prototype |
[
{
"context": "mon')\n\ntest 'simple-test', [\n {\n Name: 'Bob'\n Location: 'Sweden'\n }\n {\n N",
"end": 74,
"score": 0.9998648762702942,
"start": 71,
"tag": "NAME",
"value": "Bob"
},
{
"context": " Location: 'Sweden'\n }\n {\n Name: 'Alice'\n Location: 'France'\n }\n]\n",
"end": 135,
"score": 0.999862551689148,
"start": 130,
"tag": "NAME",
"value": "Alice"
}
] | test/simple_test.coffee | SBeyeMHP/node-xlsx-writestream | 42 | test = require('./common')
test 'simple-test', [
{
Name: 'Bob'
Location: 'Sweden'
}
{
Name: 'Alice'
Location: 'France'
}
]
| 156224 | test = require('./common')
test 'simple-test', [
{
Name: '<NAME>'
Location: 'Sweden'
}
{
Name: '<NAME>'
Location: 'France'
}
]
| true | test = require('./common')
test 'simple-test', [
{
Name: 'PI:NAME:<NAME>END_PI'
Location: 'Sweden'
}
{
Name: 'PI:NAME:<NAME>END_PI'
Location: 'France'
}
]
|
[
{
"context": "w using `this`/`super` before `super()`.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------",
"end": 103,
"score": 0.9998693466186523,
"start": 89,
"tag": "NAME",
"value": "Toru Nagashima"
}
] | src/rules/no-this-before-super.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview A rule to disallow using `this`/`super` before `super()`.
# @author Toru Nagashima
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Checks whether or not a given node is a constructor.
# @param {ASTNode} node - A node to check. This node type is one of
# `Program`, `FunctionDeclaration`, `FunctionExpression`, and
# `ArrowFunctionExpression`.
# @returns {boolean} `true` if the node is a constructor.
###
isConstructorFunction = (node) ->
node.type is 'FunctionExpression' and
node.parent.type is 'MethodDefinition' and
node.parent.kind is 'constructor'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'disallow `this`/`super` before calling `super()` in constructors'
category: 'ECMAScript 6'
recommended: yes
url: 'https://eslint.org/docs/rules/no-this-before-super'
schema: []
create: (context) ->
###
# Information for each constructor.
# - upper: Information of the upper constructor.
# - hasExtends: A flag which shows whether the owner class has a valid
# `extends` part.
# - scope: The scope of the owner class.
# - codePath: The code path of this constructor.
###
funcInfo = null
###
# Information for each code path segment.
# Each key is the id of a code path segment.
# Each value is an object:
# - superCalled: The flag which shows `super()` called in all code paths.
# - invalidNodes: The array of invalid ThisExpression and Super nodes.
###
segInfoMap = Object.create null
###*
# Gets whether or not `super()` is called in a given code path segment.
# @param {CodePathSegment} segment - A code path segment to get.
# @returns {boolean} `true` if `super()` is called.
###
isCalled = (segment) ->
not segment.reachable or segInfoMap[segment.id].superCalled
###*
# Checks whether or not this is in a constructor.
# @returns {boolean} `true` if this is in a constructor.
###
isInConstructorOfDerivedClass = ->
Boolean funcInfo?.isConstructor and funcInfo.hasExtends
###*
# Checks whether or not this is before `super()` is called.
# @returns {boolean} `true` if this is before `super()` is called.
###
isBeforeCallOfSuper = ->
isInConstructorOfDerivedClass() and
not funcInfo.codePath.currentSegments.every isCalled
###*
# Sets a given node as invalid.
# @param {ASTNode} node - A node to set as invalid. This is one of
# a ThisExpression and a Super.
# @returns {void}
###
setInvalid = (node) ->
segments = funcInfo.codePath.currentSegments
for segment in segments when segment.reachable
segInfoMap[segment.id].invalidNodes.push node
###*
# Sets the current segment as `super` was called.
# @returns {void}
###
setSuperCalled = ->
segments = funcInfo.codePath.currentSegments
for segment in segments when segment.reachable
segInfoMap[segment.id].superCalled = yes
isThisParam = (node) ->
func = funcInfo.node
{params} = func
return no unless params.length
prevNode = node
currentNode = node.parent
while currentNode and currentNode isnt func
prevNode = currentNode
currentNode = currentNode.parent
prevNode in params
###*
# Adds information of a constructor into the stack.
# @param {CodePath} codePath - A code path which was started.
# @param {ASTNode} node - The current node.
# @returns {void}
###
onCodePathStart: (codePath, node) ->
if isConstructorFunction node
# Class > ClassBody > MethodDefinition > FunctionExpression
classNode = node.parent.parent.parent
funcInfo = {
upper: funcInfo
isConstructor: yes
hasExtends: Boolean(
classNode.superClass and
not astUtils.isNullOrUndefined classNode.superClass
)
codePath
node
thisParams: []
}
else
funcInfo ###:### = {
upper: funcInfo
isConstructor: no
hasExtends: no
codePath
node
thisParams: []
}
###*
# Removes the top of stack item.
#
# And this treverses all segments of this code path then reports every
# invalid node.
#
# @param {CodePath} codePath - A code path which was ended.
# @param {ASTNode} node - The current node.
# @returns {void}
###
onCodePathEnd: (codePath) ->
isDerivedClass = funcInfo.hasExtends
{thisParams} = funcInfo
funcInfo ###:### = funcInfo.upper
return unless isDerivedClass
hasSuperBeenCalled = no
codePath.traverseSegments (segment, controller) ->
info = segInfoMap[segment.id]
for invalidNode in info.invalidNodes
context.report
message: "'{{kind}}' is not allowed before 'super()'."
node: invalidNode
data:
kind: if invalidNode.type is 'Super' then 'super' else 'this'
if info.superCalled
hasSuperBeenCalled ###:### = yes
controller.skip()
unless hasSuperBeenCalled
for thisParam in thisParams
context.report
message: "'{{kind}}' is not allowed before 'super()'."
node: thisParam
data: kind: 'this'
###*
# Initialize information of a given code path segment.
# @param {CodePathSegment} segment - A code path segment to initialize.
# @returns {void}
###
onCodePathSegmentStart: (segment) ->
return unless isInConstructorOfDerivedClass()
# Initialize info.
segInfoMap[segment.id] =
superCalled:
segment.prevSegments.length > 0 and
segment.prevSegments.every isCalled
invalidNodes: []
###*
# Update information of the code path segment when a code path was
# looped.
# @param {CodePathSegment} fromSegment - The code path segment of the
# end of a loop.
# @param {CodePathSegment} toSegment - A code path segment of the head
# of a loop.
# @returns {void}
###
onCodePathSegmentLoop: (fromSegment, toSegment) ->
return unless isInConstructorOfDerivedClass()
# Update information inside of the loop.
funcInfo.codePath.traverseSegments first: toSegment, last: fromSegment, (
segment
controller
) ->
info = segInfoMap[segment.id]
if info.superCalled
info.invalidNodes = []
controller.skip()
else if (
segment.prevSegments.length > 0 and
segment.prevSegments.every isCalled
)
info.superCalled = yes
info.invalidNodes = []
###*
# Reports if this is before `super()`.
# @param {ASTNode} node - A target node.
# @returns {void}
###
ThisExpression: (node) ->
if isBeforeCallOfSuper()
if isThisParam node
funcInfo.thisParams.push node
else
setInvalid node
###*
# Reports if this is before `super()`.
# @param {ASTNode} node - A target node.
# @returns {void}
###
Super: (node) ->
if not astUtils.isCallee(node) and isBeforeCallOfSuper()
setInvalid node
###*
# Marks `super()` called.
# @param {ASTNode} node - A target node.
# @returns {void}
###
'CallExpression:exit': (node) ->
if node.callee.type is 'Super' and isBeforeCallOfSuper()
setSuperCalled()
###*
# Resets state.
# @returns {void}
###
'Program:exit': -> segInfoMap ###:### = Object.create null
| 36281 | ###*
# @fileoverview A rule to disallow using `this`/`super` before `super()`.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Checks whether or not a given node is a constructor.
# @param {ASTNode} node - A node to check. This node type is one of
# `Program`, `FunctionDeclaration`, `FunctionExpression`, and
# `ArrowFunctionExpression`.
# @returns {boolean} `true` if the node is a constructor.
###
isConstructorFunction = (node) ->
node.type is 'FunctionExpression' and
node.parent.type is 'MethodDefinition' and
node.parent.kind is 'constructor'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'disallow `this`/`super` before calling `super()` in constructors'
category: 'ECMAScript 6'
recommended: yes
url: 'https://eslint.org/docs/rules/no-this-before-super'
schema: []
create: (context) ->
###
# Information for each constructor.
# - upper: Information of the upper constructor.
# - hasExtends: A flag which shows whether the owner class has a valid
# `extends` part.
# - scope: The scope of the owner class.
# - codePath: The code path of this constructor.
###
funcInfo = null
###
# Information for each code path segment.
# Each key is the id of a code path segment.
# Each value is an object:
# - superCalled: The flag which shows `super()` called in all code paths.
# - invalidNodes: The array of invalid ThisExpression and Super nodes.
###
segInfoMap = Object.create null
###*
# Gets whether or not `super()` is called in a given code path segment.
# @param {CodePathSegment} segment - A code path segment to get.
# @returns {boolean} `true` if `super()` is called.
###
isCalled = (segment) ->
not segment.reachable or segInfoMap[segment.id].superCalled
###*
# Checks whether or not this is in a constructor.
# @returns {boolean} `true` if this is in a constructor.
###
isInConstructorOfDerivedClass = ->
Boolean funcInfo?.isConstructor and funcInfo.hasExtends
###*
# Checks whether or not this is before `super()` is called.
# @returns {boolean} `true` if this is before `super()` is called.
###
isBeforeCallOfSuper = ->
isInConstructorOfDerivedClass() and
not funcInfo.codePath.currentSegments.every isCalled
###*
# Sets a given node as invalid.
# @param {ASTNode} node - A node to set as invalid. This is one of
# a ThisExpression and a Super.
# @returns {void}
###
setInvalid = (node) ->
segments = funcInfo.codePath.currentSegments
for segment in segments when segment.reachable
segInfoMap[segment.id].invalidNodes.push node
###*
# Sets the current segment as `super` was called.
# @returns {void}
###
setSuperCalled = ->
segments = funcInfo.codePath.currentSegments
for segment in segments when segment.reachable
segInfoMap[segment.id].superCalled = yes
isThisParam = (node) ->
func = funcInfo.node
{params} = func
return no unless params.length
prevNode = node
currentNode = node.parent
while currentNode and currentNode isnt func
prevNode = currentNode
currentNode = currentNode.parent
prevNode in params
###*
# Adds information of a constructor into the stack.
# @param {CodePath} codePath - A code path which was started.
# @param {ASTNode} node - The current node.
# @returns {void}
###
onCodePathStart: (codePath, node) ->
if isConstructorFunction node
# Class > ClassBody > MethodDefinition > FunctionExpression
classNode = node.parent.parent.parent
funcInfo = {
upper: funcInfo
isConstructor: yes
hasExtends: Boolean(
classNode.superClass and
not astUtils.isNullOrUndefined classNode.superClass
)
codePath
node
thisParams: []
}
else
funcInfo ###:### = {
upper: funcInfo
isConstructor: no
hasExtends: no
codePath
node
thisParams: []
}
###*
# Removes the top of stack item.
#
# And this treverses all segments of this code path then reports every
# invalid node.
#
# @param {CodePath} codePath - A code path which was ended.
# @param {ASTNode} node - The current node.
# @returns {void}
###
onCodePathEnd: (codePath) ->
isDerivedClass = funcInfo.hasExtends
{thisParams} = funcInfo
funcInfo ###:### = funcInfo.upper
return unless isDerivedClass
hasSuperBeenCalled = no
codePath.traverseSegments (segment, controller) ->
info = segInfoMap[segment.id]
for invalidNode in info.invalidNodes
context.report
message: "'{{kind}}' is not allowed before 'super()'."
node: invalidNode
data:
kind: if invalidNode.type is 'Super' then 'super' else 'this'
if info.superCalled
hasSuperBeenCalled ###:### = yes
controller.skip()
unless hasSuperBeenCalled
for thisParam in thisParams
context.report
message: "'{{kind}}' is not allowed before 'super()'."
node: thisParam
data: kind: 'this'
###*
# Initialize information of a given code path segment.
# @param {CodePathSegment} segment - A code path segment to initialize.
# @returns {void}
###
onCodePathSegmentStart: (segment) ->
return unless isInConstructorOfDerivedClass()
# Initialize info.
segInfoMap[segment.id] =
superCalled:
segment.prevSegments.length > 0 and
segment.prevSegments.every isCalled
invalidNodes: []
###*
# Update information of the code path segment when a code path was
# looped.
# @param {CodePathSegment} fromSegment - The code path segment of the
# end of a loop.
# @param {CodePathSegment} toSegment - A code path segment of the head
# of a loop.
# @returns {void}
###
onCodePathSegmentLoop: (fromSegment, toSegment) ->
return unless isInConstructorOfDerivedClass()
# Update information inside of the loop.
funcInfo.codePath.traverseSegments first: toSegment, last: fromSegment, (
segment
controller
) ->
info = segInfoMap[segment.id]
if info.superCalled
info.invalidNodes = []
controller.skip()
else if (
segment.prevSegments.length > 0 and
segment.prevSegments.every isCalled
)
info.superCalled = yes
info.invalidNodes = []
###*
# Reports if this is before `super()`.
# @param {ASTNode} node - A target node.
# @returns {void}
###
ThisExpression: (node) ->
if isBeforeCallOfSuper()
if isThisParam node
funcInfo.thisParams.push node
else
setInvalid node
###*
# Reports if this is before `super()`.
# @param {ASTNode} node - A target node.
# @returns {void}
###
Super: (node) ->
if not astUtils.isCallee(node) and isBeforeCallOfSuper()
setInvalid node
###*
# Marks `super()` called.
# @param {ASTNode} node - A target node.
# @returns {void}
###
'CallExpression:exit': (node) ->
if node.callee.type is 'Super' and isBeforeCallOfSuper()
setSuperCalled()
###*
# Resets state.
# @returns {void}
###
'Program:exit': -> segInfoMap ###:### = Object.create null
| true | ###*
# @fileoverview A rule to disallow using `this`/`super` before `super()`.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
###*
# Checks whether or not a given node is a constructor.
# @param {ASTNode} node - A node to check. This node type is one of
# `Program`, `FunctionDeclaration`, `FunctionExpression`, and
# `ArrowFunctionExpression`.
# @returns {boolean} `true` if the node is a constructor.
###
isConstructorFunction = (node) ->
node.type is 'FunctionExpression' and
node.parent.type is 'MethodDefinition' and
node.parent.kind is 'constructor'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'disallow `this`/`super` before calling `super()` in constructors'
category: 'ECMAScript 6'
recommended: yes
url: 'https://eslint.org/docs/rules/no-this-before-super'
schema: []
create: (context) ->
###
# Information for each constructor.
# - upper: Information of the upper constructor.
# - hasExtends: A flag which shows whether the owner class has a valid
# `extends` part.
# - scope: The scope of the owner class.
# - codePath: The code path of this constructor.
###
funcInfo = null
###
# Information for each code path segment.
# Each key is the id of a code path segment.
# Each value is an object:
# - superCalled: The flag which shows `super()` called in all code paths.
# - invalidNodes: The array of invalid ThisExpression and Super nodes.
###
segInfoMap = Object.create null
###*
# Gets whether or not `super()` is called in a given code path segment.
# @param {CodePathSegment} segment - A code path segment to get.
# @returns {boolean} `true` if `super()` is called.
###
isCalled = (segment) ->
not segment.reachable or segInfoMap[segment.id].superCalled
###*
# Checks whether or not this is in a constructor.
# @returns {boolean} `true` if this is in a constructor.
###
isInConstructorOfDerivedClass = ->
Boolean funcInfo?.isConstructor and funcInfo.hasExtends
###*
# Checks whether or not this is before `super()` is called.
# @returns {boolean} `true` if this is before `super()` is called.
###
isBeforeCallOfSuper = ->
isInConstructorOfDerivedClass() and
not funcInfo.codePath.currentSegments.every isCalled
###*
# Sets a given node as invalid.
# @param {ASTNode} node - A node to set as invalid. This is one of
# a ThisExpression and a Super.
# @returns {void}
###
setInvalid = (node) ->
segments = funcInfo.codePath.currentSegments
for segment in segments when segment.reachable
segInfoMap[segment.id].invalidNodes.push node
###*
# Sets the current segment as `super` was called.
# @returns {void}
###
setSuperCalled = ->
segments = funcInfo.codePath.currentSegments
for segment in segments when segment.reachable
segInfoMap[segment.id].superCalled = yes
isThisParam = (node) ->
func = funcInfo.node
{params} = func
return no unless params.length
prevNode = node
currentNode = node.parent
while currentNode and currentNode isnt func
prevNode = currentNode
currentNode = currentNode.parent
prevNode in params
###*
# Adds information of a constructor into the stack.
# @param {CodePath} codePath - A code path which was started.
# @param {ASTNode} node - The current node.
# @returns {void}
###
onCodePathStart: (codePath, node) ->
if isConstructorFunction node
# Class > ClassBody > MethodDefinition > FunctionExpression
classNode = node.parent.parent.parent
funcInfo = {
upper: funcInfo
isConstructor: yes
hasExtends: Boolean(
classNode.superClass and
not astUtils.isNullOrUndefined classNode.superClass
)
codePath
node
thisParams: []
}
else
funcInfo ###:### = {
upper: funcInfo
isConstructor: no
hasExtends: no
codePath
node
thisParams: []
}
###*
# Removes the top of stack item.
#
# And this treverses all segments of this code path then reports every
# invalid node.
#
# @param {CodePath} codePath - A code path which was ended.
# @param {ASTNode} node - The current node.
# @returns {void}
###
onCodePathEnd: (codePath) ->
isDerivedClass = funcInfo.hasExtends
{thisParams} = funcInfo
funcInfo ###:### = funcInfo.upper
return unless isDerivedClass
hasSuperBeenCalled = no
codePath.traverseSegments (segment, controller) ->
info = segInfoMap[segment.id]
for invalidNode in info.invalidNodes
context.report
message: "'{{kind}}' is not allowed before 'super()'."
node: invalidNode
data:
kind: if invalidNode.type is 'Super' then 'super' else 'this'
if info.superCalled
hasSuperBeenCalled ###:### = yes
controller.skip()
unless hasSuperBeenCalled
for thisParam in thisParams
context.report
message: "'{{kind}}' is not allowed before 'super()'."
node: thisParam
data: kind: 'this'
###*
# Initialize information of a given code path segment.
# @param {CodePathSegment} segment - A code path segment to initialize.
# @returns {void}
###
onCodePathSegmentStart: (segment) ->
return unless isInConstructorOfDerivedClass()
# Initialize info.
segInfoMap[segment.id] =
superCalled:
segment.prevSegments.length > 0 and
segment.prevSegments.every isCalled
invalidNodes: []
###*
# Update information of the code path segment when a code path was
# looped.
# @param {CodePathSegment} fromSegment - The code path segment of the
# end of a loop.
# @param {CodePathSegment} toSegment - A code path segment of the head
# of a loop.
# @returns {void}
###
onCodePathSegmentLoop: (fromSegment, toSegment) ->
return unless isInConstructorOfDerivedClass()
# Update information inside of the loop.
funcInfo.codePath.traverseSegments first: toSegment, last: fromSegment, (
segment
controller
) ->
info = segInfoMap[segment.id]
if info.superCalled
info.invalidNodes = []
controller.skip()
else if (
segment.prevSegments.length > 0 and
segment.prevSegments.every isCalled
)
info.superCalled = yes
info.invalidNodes = []
###*
# Reports if this is before `super()`.
# @param {ASTNode} node - A target node.
# @returns {void}
###
ThisExpression: (node) ->
if isBeforeCallOfSuper()
if isThisParam node
funcInfo.thisParams.push node
else
setInvalid node
###*
# Reports if this is before `super()`.
# @param {ASTNode} node - A target node.
# @returns {void}
###
Super: (node) ->
if not astUtils.isCallee(node) and isBeforeCallOfSuper()
setInvalid node
###*
# Marks `super()` called.
# @param {ASTNode} node - A target node.
# @returns {void}
###
'CallExpression:exit': (node) ->
if node.callee.type is 'Super' and isBeforeCallOfSuper()
setSuperCalled()
###*
# Resets state.
# @returns {void}
###
'Program:exit': -> segInfoMap ###:### = Object.create null
|
[
{
"context": "rategy\n usernameField: 'email'\n passwordField: 'password'\n \n (email, password, done) ->\n errorMessage",
"end": 357,
"score": 0.9993054270744324,
"start": 349,
"tag": "PASSWORD",
"value": "password"
}
] | api/services/PassportService.coffee | MackieLoeffel/NachhaltigkeitsChallenge | 0 | passport = require('passport')
LocalStrategy = require('passport-local').Strategy
bcrypt = require('bcrypt')
passport.serializeUser (user, done) -> done null, user.id
passport.deserializeUser (id, done) ->
User.findOne({id}).exec (err, user) -> done err, user?.toJSON()
passport.use new LocalStrategy
usernameField: 'email'
passwordField: 'password'
(email, password, done) ->
errorMessage = "Wrong Credentials!"
User.findOne({email}).then (user) ->
return done(null, false, message: errorMessage) if !user
bcrypt.compare password, user.password, (err, res) ->
return done(null, false, message: errorMessage) if !res
done null, user.toJSON(), message: 'Logged In Successfully'
.catch (err) -> done err
| 72756 | passport = require('passport')
LocalStrategy = require('passport-local').Strategy
bcrypt = require('bcrypt')
passport.serializeUser (user, done) -> done null, user.id
passport.deserializeUser (id, done) ->
User.findOne({id}).exec (err, user) -> done err, user?.toJSON()
passport.use new LocalStrategy
usernameField: 'email'
passwordField: '<PASSWORD>'
(email, password, done) ->
errorMessage = "Wrong Credentials!"
User.findOne({email}).then (user) ->
return done(null, false, message: errorMessage) if !user
bcrypt.compare password, user.password, (err, res) ->
return done(null, false, message: errorMessage) if !res
done null, user.toJSON(), message: 'Logged In Successfully'
.catch (err) -> done err
| true | passport = require('passport')
LocalStrategy = require('passport-local').Strategy
bcrypt = require('bcrypt')
passport.serializeUser (user, done) -> done null, user.id
passport.deserializeUser (id, done) ->
User.findOne({id}).exec (err, user) -> done err, user?.toJSON()
passport.use new LocalStrategy
usernameField: 'email'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
(email, password, done) ->
errorMessage = "Wrong Credentials!"
User.findOne({email}).then (user) ->
return done(null, false, message: errorMessage) if !user
bcrypt.compare password, user.password, (err, res) ->
return done(null, false, message: errorMessage) if !res
done null, user.toJSON(), message: 'Logged In Successfully'
.catch (err) -> done err
|
[
{
"context": "###\n# MIT LICENSE\n# Copyright (c) 2011 Devon Govett\n#\n# Permission is hereby granted, free of charge,",
"end": 51,
"score": 0.9998499155044556,
"start": 39,
"tag": "NAME",
"value": "Devon Govett"
},
{
"context": "ALINGS IN THE SOFTWARE.\n###\n\n# https://github.com/niegowski/node-pngjs\n\nfs = require 'fs'\nzlib = require 'zli",
"end": 1138,
"score": 0.9541363716125488,
"start": 1129,
"tag": "USERNAME",
"value": "niegowski"
}
] | src/vendor/pngjs.coffee | EndangeredMassa/img-diff | 4 | ###
# MIT LICENSE
# Copyright (c) 2011 Devon Govett
#
# 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.
###
# https://github.com/niegowski/node-pngjs
fs = require 'fs'
zlib = require 'zlib'
zpipe = require 'zpipe'
module.exports = class PNG
@decode: (path, fn) ->
fs.readFile path, (err, file) ->
png = new PNG(file)
png.decode (pixels) ->
fn pixels
@load: (path) ->
file = fs.readFileSync path
return new PNG(file)
constructor: (@data) ->
@pos = 8 # Skip the default header
@palette = []
@imgData = []
@transparency = {}
@text = {}
loop
chunkSize = @readUInt32()
section = (String.fromCharCode @data[@pos++] for i in [0...4]).join('')
switch section
when 'IHDR'
# we can grab interesting values from here (like width, height, etc)
@width = @readUInt32()
@height = @readUInt32()
@bits = @data[@pos++]
@colorType = @data[@pos++]
@compressionMethod = @data[@pos++]
@filterMethod = @data[@pos++]
@interlaceMethod = @data[@pos++]
when 'PLTE'
@palette = @read(chunkSize)
when 'IDAT'
for i in [0...chunkSize] by 1
@imgData.push @data[@pos++]
when 'tRNS'
# This chunk can only occur once and it must occur after the
# PLTE chunk and before the IDAT chunk.
@transparency = {}
switch @colorType
when 3
# Indexed color, RGB. Each byte in this chunk is an alpha for
# the palette index in the PLTE ("palette") chunk up until the
# last non-opaque entry. Set up an array, stretching over all
# palette entries which will be 0 (opaque) or 1 (transparent).
@transparency.indexed = @read(chunkSize)
short = 255 - @transparency.indexed.length
if short > 0
@transparency.indexed.push 255 for i in [0...short]
when 0
# Greyscale. Corresponding to entries in the PLTE chunk.
# Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
@transparency.grayscale = @read(chunkSize)[0]
when 2
# True color with proper alpha channel.
@transparency.rgb = @read(chunkSize)
when 'tEXt'
text = @read(chunkSize)
index = text.indexOf(0)
key = String.fromCharCode text.slice(0, index)...
@text[key] = String.fromCharCode text.slice(index + 1)...
when 'IEND'
# we've got everything we need!
@colors = switch @colorType
when 0, 3, 4 then 1
when 2, 6 then 3
@hasAlphaChannel = @colorType in [4, 6]
colors = @colors + if @hasAlphaChannel then 1 else 0
@pixelBitlength = @bits * colors
@colorSpace = switch @colors
when 1 then 'DeviceGray'
when 3 then 'DeviceRGB'
@imgData = new Buffer @imgData
return
else
# unknown (or unimportant) section, skip it
@pos += chunkSize
@pos += 4 # Skip the CRC
if @pos > @data.length
throw new Error "Incomplete or corrupt PNG file"
return
read: (bytes) ->
(@data[@pos++] for i in [0...bytes])
readUInt32: ->
b1 = @data[@pos++] << 24
b2 = @data[@pos++] << 16
b3 = @data[@pos++] << 8
b4 = @data[@pos++]
b1 | b2 | b3 | b4
readUInt16: ->
b1 = @data[@pos++] << 8
b2 = @data[@pos++]
b1 | b2
decodePixels: (fn) ->
zlib.inflate @imgData, (err, data) =>
fn err if err?
try
pixels = @_decodePixels(data)
catch e
err = e
fn null, pixels
decodePixelsSync: ->
data = zpipe.inflate @imgData.toString('binary')
buffer = new Buffer data, 'binary'
@_decodePixels(buffer)
_decodePixels: (data) ->
pixelBytes = @pixelBitlength / 8
scanlineLength = pixelBytes * @width
pixels = new Buffer(scanlineLength * @height)
length = data.length
row = 0
pos = 0
c = 0
while pos < length
switch data[pos++]
when 0 # None
for i in [0...scanlineLength] by 1
pixels[c++] = data[pos++]
when 1 # Sub
for i in [0...scanlineLength] by 1
byte = data[pos++]
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
pixels[c++] = (byte + left) % 256
when 2 # Up
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (upper + byte) % 256
when 3 # Average
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256
when 4 # Paeth
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
if row is 0
upper = upperLeft = 0
else
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)]
p = left + upper - upperLeft
pa = Math.abs(p - left)
pb = Math.abs(p - upper)
pc = Math.abs(p - upperLeft)
if pa <= pb and pa <= pc
paeth = left
else if pb <= pc
paeth = upper
else
paeth = upperLeft
pixels[c++] = (byte + paeth) % 256
else
throw new Error "Invalid filter algorithm: " + data[pos - 1]
row++
return pixels
decodePalette: ->
palette = @palette
transparency = @transparency.indexed or []
ret = new Buffer(transparency.length + palette.length)
pos = 0
length = palette.length
c = 0
for i in [0...palette.length] by 3
ret[pos++] = palette[i]
ret[pos++] = palette[i + 1]
ret[pos++] = palette[i + 2]
ret[pos++] = transparency[c++] ? 255
return ret
copyToImageData: (imageData, pixels) ->
colors = @colors
palette = null
alpha = @hasAlphaChannel
if @palette.length
palette = @_decodedPalette ?= @decodePalette()
colors = 4
alpha = true
data = imageData?.data or imageData
length = data.length
input = palette or pixels
i = j = 0
if colors is 1
while i < length
k = if palette then pixels[i / 4] * 4 else j
v = input[k++]
data[i++] = v
data[i++] = v
data[i++] = v
data[i++] = if alpha then input[k++] else 255
j = k
else
while i < length
k = if palette then pixels[i / 4] * 4 else j
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = if alpha then input[k++] else 255
j = k
return
decode: (fn) ->
ret = new Buffer(@width * @height * 4)
@decodePixels (err, pixels) =>
return fn err if err?
@copyToImageData ret, pixels
fn null, ret
decodeSync: ->
ret = new Buffer(@width * @height * 4)
pixels = @decodePixelsSync()
@copyToImageData ret, pixels
return ret
| 27606 | ###
# MIT LICENSE
# Copyright (c) 2011 <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.
###
# https://github.com/niegowski/node-pngjs
fs = require 'fs'
zlib = require 'zlib'
zpipe = require 'zpipe'
module.exports = class PNG
@decode: (path, fn) ->
fs.readFile path, (err, file) ->
png = new PNG(file)
png.decode (pixels) ->
fn pixels
@load: (path) ->
file = fs.readFileSync path
return new PNG(file)
constructor: (@data) ->
@pos = 8 # Skip the default header
@palette = []
@imgData = []
@transparency = {}
@text = {}
loop
chunkSize = @readUInt32()
section = (String.fromCharCode @data[@pos++] for i in [0...4]).join('')
switch section
when 'IHDR'
# we can grab interesting values from here (like width, height, etc)
@width = @readUInt32()
@height = @readUInt32()
@bits = @data[@pos++]
@colorType = @data[@pos++]
@compressionMethod = @data[@pos++]
@filterMethod = @data[@pos++]
@interlaceMethod = @data[@pos++]
when 'PLTE'
@palette = @read(chunkSize)
when 'IDAT'
for i in [0...chunkSize] by 1
@imgData.push @data[@pos++]
when 'tRNS'
# This chunk can only occur once and it must occur after the
# PLTE chunk and before the IDAT chunk.
@transparency = {}
switch @colorType
when 3
# Indexed color, RGB. Each byte in this chunk is an alpha for
# the palette index in the PLTE ("palette") chunk up until the
# last non-opaque entry. Set up an array, stretching over all
# palette entries which will be 0 (opaque) or 1 (transparent).
@transparency.indexed = @read(chunkSize)
short = 255 - @transparency.indexed.length
if short > 0
@transparency.indexed.push 255 for i in [0...short]
when 0
# Greyscale. Corresponding to entries in the PLTE chunk.
# Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
@transparency.grayscale = @read(chunkSize)[0]
when 2
# True color with proper alpha channel.
@transparency.rgb = @read(chunkSize)
when 'tEXt'
text = @read(chunkSize)
index = text.indexOf(0)
key = String.fromCharCode text.slice(0, index)...
@text[key] = String.fromCharCode text.slice(index + 1)...
when 'IEND'
# we've got everything we need!
@colors = switch @colorType
when 0, 3, 4 then 1
when 2, 6 then 3
@hasAlphaChannel = @colorType in [4, 6]
colors = @colors + if @hasAlphaChannel then 1 else 0
@pixelBitlength = @bits * colors
@colorSpace = switch @colors
when 1 then 'DeviceGray'
when 3 then 'DeviceRGB'
@imgData = new Buffer @imgData
return
else
# unknown (or unimportant) section, skip it
@pos += chunkSize
@pos += 4 # Skip the CRC
if @pos > @data.length
throw new Error "Incomplete or corrupt PNG file"
return
read: (bytes) ->
(@data[@pos++] for i in [0...bytes])
readUInt32: ->
b1 = @data[@pos++] << 24
b2 = @data[@pos++] << 16
b3 = @data[@pos++] << 8
b4 = @data[@pos++]
b1 | b2 | b3 | b4
readUInt16: ->
b1 = @data[@pos++] << 8
b2 = @data[@pos++]
b1 | b2
decodePixels: (fn) ->
zlib.inflate @imgData, (err, data) =>
fn err if err?
try
pixels = @_decodePixels(data)
catch e
err = e
fn null, pixels
decodePixelsSync: ->
data = zpipe.inflate @imgData.toString('binary')
buffer = new Buffer data, 'binary'
@_decodePixels(buffer)
_decodePixels: (data) ->
pixelBytes = @pixelBitlength / 8
scanlineLength = pixelBytes * @width
pixels = new Buffer(scanlineLength * @height)
length = data.length
row = 0
pos = 0
c = 0
while pos < length
switch data[pos++]
when 0 # None
for i in [0...scanlineLength] by 1
pixels[c++] = data[pos++]
when 1 # Sub
for i in [0...scanlineLength] by 1
byte = data[pos++]
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
pixels[c++] = (byte + left) % 256
when 2 # Up
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (upper + byte) % 256
when 3 # Average
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256
when 4 # Paeth
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
if row is 0
upper = upperLeft = 0
else
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)]
p = left + upper - upperLeft
pa = Math.abs(p - left)
pb = Math.abs(p - upper)
pc = Math.abs(p - upperLeft)
if pa <= pb and pa <= pc
paeth = left
else if pb <= pc
paeth = upper
else
paeth = upperLeft
pixels[c++] = (byte + paeth) % 256
else
throw new Error "Invalid filter algorithm: " + data[pos - 1]
row++
return pixels
decodePalette: ->
palette = @palette
transparency = @transparency.indexed or []
ret = new Buffer(transparency.length + palette.length)
pos = 0
length = palette.length
c = 0
for i in [0...palette.length] by 3
ret[pos++] = palette[i]
ret[pos++] = palette[i + 1]
ret[pos++] = palette[i + 2]
ret[pos++] = transparency[c++] ? 255
return ret
copyToImageData: (imageData, pixels) ->
colors = @colors
palette = null
alpha = @hasAlphaChannel
if @palette.length
palette = @_decodedPalette ?= @decodePalette()
colors = 4
alpha = true
data = imageData?.data or imageData
length = data.length
input = palette or pixels
i = j = 0
if colors is 1
while i < length
k = if palette then pixels[i / 4] * 4 else j
v = input[k++]
data[i++] = v
data[i++] = v
data[i++] = v
data[i++] = if alpha then input[k++] else 255
j = k
else
while i < length
k = if palette then pixels[i / 4] * 4 else j
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = if alpha then input[k++] else 255
j = k
return
decode: (fn) ->
ret = new Buffer(@width * @height * 4)
@decodePixels (err, pixels) =>
return fn err if err?
@copyToImageData ret, pixels
fn null, ret
decodeSync: ->
ret = new Buffer(@width * @height * 4)
pixels = @decodePixelsSync()
@copyToImageData ret, pixels
return ret
| true | ###
# MIT LICENSE
# Copyright (c) 2011 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.
###
# https://github.com/niegowski/node-pngjs
fs = require 'fs'
zlib = require 'zlib'
zpipe = require 'zpipe'
module.exports = class PNG
@decode: (path, fn) ->
fs.readFile path, (err, file) ->
png = new PNG(file)
png.decode (pixels) ->
fn pixels
@load: (path) ->
file = fs.readFileSync path
return new PNG(file)
constructor: (@data) ->
@pos = 8 # Skip the default header
@palette = []
@imgData = []
@transparency = {}
@text = {}
loop
chunkSize = @readUInt32()
section = (String.fromCharCode @data[@pos++] for i in [0...4]).join('')
switch section
when 'IHDR'
# we can grab interesting values from here (like width, height, etc)
@width = @readUInt32()
@height = @readUInt32()
@bits = @data[@pos++]
@colorType = @data[@pos++]
@compressionMethod = @data[@pos++]
@filterMethod = @data[@pos++]
@interlaceMethod = @data[@pos++]
when 'PLTE'
@palette = @read(chunkSize)
when 'IDAT'
for i in [0...chunkSize] by 1
@imgData.push @data[@pos++]
when 'tRNS'
# This chunk can only occur once and it must occur after the
# PLTE chunk and before the IDAT chunk.
@transparency = {}
switch @colorType
when 3
# Indexed color, RGB. Each byte in this chunk is an alpha for
# the palette index in the PLTE ("palette") chunk up until the
# last non-opaque entry. Set up an array, stretching over all
# palette entries which will be 0 (opaque) or 1 (transparent).
@transparency.indexed = @read(chunkSize)
short = 255 - @transparency.indexed.length
if short > 0
@transparency.indexed.push 255 for i in [0...short]
when 0
# Greyscale. Corresponding to entries in the PLTE chunk.
# Grey is two bytes, range 0 .. (2 ^ bit-depth) - 1
@transparency.grayscale = @read(chunkSize)[0]
when 2
# True color with proper alpha channel.
@transparency.rgb = @read(chunkSize)
when 'tEXt'
text = @read(chunkSize)
index = text.indexOf(0)
key = String.fromCharCode text.slice(0, index)...
@text[key] = String.fromCharCode text.slice(index + 1)...
when 'IEND'
# we've got everything we need!
@colors = switch @colorType
when 0, 3, 4 then 1
when 2, 6 then 3
@hasAlphaChannel = @colorType in [4, 6]
colors = @colors + if @hasAlphaChannel then 1 else 0
@pixelBitlength = @bits * colors
@colorSpace = switch @colors
when 1 then 'DeviceGray'
when 3 then 'DeviceRGB'
@imgData = new Buffer @imgData
return
else
# unknown (or unimportant) section, skip it
@pos += chunkSize
@pos += 4 # Skip the CRC
if @pos > @data.length
throw new Error "Incomplete or corrupt PNG file"
return
read: (bytes) ->
(@data[@pos++] for i in [0...bytes])
readUInt32: ->
b1 = @data[@pos++] << 24
b2 = @data[@pos++] << 16
b3 = @data[@pos++] << 8
b4 = @data[@pos++]
b1 | b2 | b3 | b4
readUInt16: ->
b1 = @data[@pos++] << 8
b2 = @data[@pos++]
b1 | b2
decodePixels: (fn) ->
zlib.inflate @imgData, (err, data) =>
fn err if err?
try
pixels = @_decodePixels(data)
catch e
err = e
fn null, pixels
decodePixelsSync: ->
data = zpipe.inflate @imgData.toString('binary')
buffer = new Buffer data, 'binary'
@_decodePixels(buffer)
_decodePixels: (data) ->
pixelBytes = @pixelBitlength / 8
scanlineLength = pixelBytes * @width
pixels = new Buffer(scanlineLength * @height)
length = data.length
row = 0
pos = 0
c = 0
while pos < length
switch data[pos++]
when 0 # None
for i in [0...scanlineLength] by 1
pixels[c++] = data[pos++]
when 1 # Sub
for i in [0...scanlineLength] by 1
byte = data[pos++]
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
pixels[c++] = (byte + left) % 256
when 2 # Up
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (upper + byte) % 256
when 3 # Average
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
upper = row && pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
pixels[c++] = (byte + Math.floor((left + upper) / 2)) % 256
when 4 # Paeth
for i in [0...scanlineLength] by 1
byte = data[pos++]
col = (i - (i % pixelBytes)) / pixelBytes
left = if i < pixelBytes then 0 else pixels[c - pixelBytes]
if row is 0
upper = upperLeft = 0
else
upper = pixels[(row - 1) * scanlineLength + col * pixelBytes + (i % pixelBytes)]
upperLeft = col && pixels[(row - 1) * scanlineLength + (col - 1) * pixelBytes + (i % pixelBytes)]
p = left + upper - upperLeft
pa = Math.abs(p - left)
pb = Math.abs(p - upper)
pc = Math.abs(p - upperLeft)
if pa <= pb and pa <= pc
paeth = left
else if pb <= pc
paeth = upper
else
paeth = upperLeft
pixels[c++] = (byte + paeth) % 256
else
throw new Error "Invalid filter algorithm: " + data[pos - 1]
row++
return pixels
decodePalette: ->
palette = @palette
transparency = @transparency.indexed or []
ret = new Buffer(transparency.length + palette.length)
pos = 0
length = palette.length
c = 0
for i in [0...palette.length] by 3
ret[pos++] = palette[i]
ret[pos++] = palette[i + 1]
ret[pos++] = palette[i + 2]
ret[pos++] = transparency[c++] ? 255
return ret
copyToImageData: (imageData, pixels) ->
colors = @colors
palette = null
alpha = @hasAlphaChannel
if @palette.length
palette = @_decodedPalette ?= @decodePalette()
colors = 4
alpha = true
data = imageData?.data or imageData
length = data.length
input = palette or pixels
i = j = 0
if colors is 1
while i < length
k = if palette then pixels[i / 4] * 4 else j
v = input[k++]
data[i++] = v
data[i++] = v
data[i++] = v
data[i++] = if alpha then input[k++] else 255
j = k
else
while i < length
k = if palette then pixels[i / 4] * 4 else j
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = input[k++]
data[i++] = if alpha then input[k++] else 255
j = k
return
decode: (fn) ->
ret = new Buffer(@width * @height * 4)
@decodePixels (err, pixels) =>
return fn err if err?
@copyToImageData ret, pixels
fn null, ret
decodeSync: ->
ret = new Buffer(@width * @height * 4)
pixels = @decodePixelsSync()
@copyToImageData ret, pixels
return ret
|
[
{
"context": "77}}>\n <a href=\"mailto:team@pagedraw.io\" style={{\"display\": \"flex\"}}>\n ",
"end": 5211,
"score": 0.9999163746833801,
"start": 5195,
"tag": "EMAIL",
"value": "team@pagedraw.io"
}
] | src/pagedraw/companycard.cjsx | caffed/pagedraw | 3,213 | # Generated by https://pagedraw.io/pages/5249
React = require 'react'
render = ->
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1"}}>
<style dangerouslySetInnerHTML={__html: """
@import url('https://fonts.googleapis.com/css?family=Lato:');
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: inherit;
}
.pd-onhover-parent >.pd-onhover {
display: none;
}
.pd-onhover-parent:hover > * {
display: none;
}
.pd-onhover-parent:hover > .pd-onhover {
display: flex;
}
.pd-onactive-parent > .pd-onactive {
display: none;
}
.pd-onactive-parent:active > * {
display: none;
}
.pd-onactive-parent:active > .pd-onactive {
display: flex;
}
.pd-onactive-parent.pd-onhover-parent:active > .pd-onhover {
display: none;
}
"""} />
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 20, "paddingBottom": 36, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(37, 37, 59)"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.4977973568281938", "flexBasis": 0}} />
<div style={{"width": 121, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 22, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Company
</div>
<div style={{"height": 0, "flexGrow": "0.5022026431718062", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 16}}>
<div style={{"height": 2, "flexGrow": "1", "flexBasis": 0, "background": "rgba(255, 255, 255, 0.2)"}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 33}}>
<div style={{"height": 0, "flexGrow": "0.4864864864864865", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 27, "paddingRight": 27}}>
<div style={{"width": 257, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Pricing based on team size
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 41, "paddingLeft": 124, "paddingRight": 125}}>
<div style={{"width": 62, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(255, 255, 255, 0.6)", "fontSize": 12, "lineHeight": "normal", "letterSpacing": 0.46, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
INCLUDES
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 12}}>
<div style={{"width": 311, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>Generated code supports older browsers</div>
<div>Onboarding training</div>
<div>Dedicated support</div>
<div>Team collaboration features</div>
<div>On-prem deployment</div>
<div>Private Slack channel</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 21, "paddingLeft": 77, "paddingRight": 77}}>
<a href="mailto:team@pagedraw.io" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 4, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 7, "paddingRight": 8}}>
<div style={{"width": 142, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 15, "lineHeight": "40px", "letterSpacing": 0.3308823, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Request a quote
</div>
</div>
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.5135135135135135", "flexBasis": 0}} />
</div>
</div>
</div>
</div>
module.exports = (props) -> render.apply({props})
| 83206 | # Generated by https://pagedraw.io/pages/5249
React = require 'react'
render = ->
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1"}}>
<style dangerouslySetInnerHTML={__html: """
@import url('https://fonts.googleapis.com/css?family=Lato:');
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: inherit;
}
.pd-onhover-parent >.pd-onhover {
display: none;
}
.pd-onhover-parent:hover > * {
display: none;
}
.pd-onhover-parent:hover > .pd-onhover {
display: flex;
}
.pd-onactive-parent > .pd-onactive {
display: none;
}
.pd-onactive-parent:active > * {
display: none;
}
.pd-onactive-parent:active > .pd-onactive {
display: flex;
}
.pd-onactive-parent.pd-onhover-parent:active > .pd-onhover {
display: none;
}
"""} />
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 20, "paddingBottom": 36, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(37, 37, 59)"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.4977973568281938", "flexBasis": 0}} />
<div style={{"width": 121, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 22, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Company
</div>
<div style={{"height": 0, "flexGrow": "0.5022026431718062", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 16}}>
<div style={{"height": 2, "flexGrow": "1", "flexBasis": 0, "background": "rgba(255, 255, 255, 0.2)"}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 33}}>
<div style={{"height": 0, "flexGrow": "0.4864864864864865", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 27, "paddingRight": 27}}>
<div style={{"width": 257, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Pricing based on team size
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 41, "paddingLeft": 124, "paddingRight": 125}}>
<div style={{"width": 62, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(255, 255, 255, 0.6)", "fontSize": 12, "lineHeight": "normal", "letterSpacing": 0.46, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
INCLUDES
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 12}}>
<div style={{"width": 311, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>Generated code supports older browsers</div>
<div>Onboarding training</div>
<div>Dedicated support</div>
<div>Team collaboration features</div>
<div>On-prem deployment</div>
<div>Private Slack channel</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 21, "paddingLeft": 77, "paddingRight": 77}}>
<a href="mailto:<EMAIL>" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 4, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 7, "paddingRight": 8}}>
<div style={{"width": 142, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 15, "lineHeight": "40px", "letterSpacing": 0.3308823, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Request a quote
</div>
</div>
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.5135135135135135", "flexBasis": 0}} />
</div>
</div>
</div>
</div>
module.exports = (props) -> render.apply({props})
| true | # Generated by https://pagedraw.io/pages/5249
React = require 'react'
render = ->
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1"}}>
<style dangerouslySetInnerHTML={__html: """
@import url('https://fonts.googleapis.com/css?family=Lato:');
* {
box-sizing: border-box;
}
body {
margin: 0;
}
button:hover {
cursor: pointer;
}
a {
text-decoration: none;
color: inherit;
}
.pd-onhover-parent >.pd-onhover {
display: none;
}
.pd-onhover-parent:hover > * {
display: none;
}
.pd-onhover-parent:hover > .pd-onhover {
display: flex;
}
.pd-onactive-parent > .pd-onactive {
display: none;
}
.pd-onactive-parent:active > * {
display: none;
}
.pd-onactive-parent:active > .pd-onactive {
display: flex;
}
.pd-onactive-parent.pd-onhover-parent:active > .pd-onhover {
display: none;
}
"""} />
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"display": "flex", "flexDirection": "column", "flexGrow": "1", "flexBasis": 0, "minHeight": "fit-content", "paddingTop": 20, "paddingBottom": 36, "borderRadius": 10, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(37, 37, 59)"}}>
<div style={{"display": "flex", "flexShrink": "0"}}>
<div style={{"height": 0, "flexGrow": "0.4977973568281938", "flexBasis": 0}} />
<div style={{"width": 121, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 22, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Company
</div>
<div style={{"height": 0, "flexGrow": "0.5022026431718062", "flexBasis": 0}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 16}}>
<div style={{"height": 2, "flexGrow": "1", "flexBasis": 0, "background": "rgba(255, 255, 255, 0.2)"}} />
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 33}}>
<div style={{"height": 0, "flexGrow": "0.4864864864864865", "flexBasis": 0}} />
<div style={{"display": "flex", "flexDirection": "column"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 27, "paddingRight": 27}}>
<div style={{"width": 257, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Pricing based on team size
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 41, "paddingLeft": 124, "paddingRight": 125}}>
<div style={{"width": 62, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgba(255, 255, 255, 0.6)", "fontSize": 12, "lineHeight": "normal", "letterSpacing": 0.46, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
INCLUDES
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 12}}>
<div style={{"width": 311, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(255, 255, 255)", "fontSize": 17, "lineHeight": "26px", "letterSpacing": 0, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
<div>Generated code supports older browsers</div>
<div>Onboarding training</div>
<div>Dedicated support</div>
<div>Team collaboration features</div>
<div>On-prem deployment</div>
<div>Private Slack channel</div>
</div>
</div>
<div style={{"display": "flex", "flexShrink": "0", "marginTop": 21, "paddingLeft": 77, "paddingRight": 77}}>
<a href="mailto:PI:EMAIL:<EMAIL>END_PI" style={{"display": "flex"}}>
<div style={{"display": "flex", "flexDirection": "column", "borderRadius": 4, "boxShadow": "0px 5px 15px 0px rgba(0,0,0,0.07), 0px 15px 35px 0px rgba(50,50,93,0.10)", "background": "rgb(255, 255, 255)", "flexGrow": "1"}}>
<div style={{"display": "flex", "flexShrink": "0", "paddingLeft": 7, "paddingRight": 8}}>
<div style={{"width": 142, "flexShrink": "0", "fontFamily": "\"Lato\", sans-serif", "color": "rgb(0, 0, 31)", "fontSize": 15, "lineHeight": "40px", "letterSpacing": 0.3308823, "fontWeight": "normal", "fontStyle": "normal", "textDecoration": "none", "textAlign": "center", "wordWrap": "break-word"}}>
Request a quote
</div>
</div>
</div>
</a>
</div>
</div>
<div style={{"height": 0, "flexGrow": "0.5135135135135135", "flexBasis": 0}} />
</div>
</div>
</div>
</div>
module.exports = (props) -> render.apply({props})
|
[
{
"context": "###\nCopyright (c) 2014 Ramesh Nair (hiddentao.com)\n\nPermission is hereby granted, fr",
"end": 34,
"score": 0.9998847246170044,
"start": 23,
"tag": "NAME",
"value": "Ramesh Nair"
}
] | test/testbase.coffee | martianboy/squel | 0 | ###
Copyright (c) 2014 Ramesh Nair (hiddentao.com)
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.
###
sinon = require('sinon')
chai = require("chai")
sinonChai = require("sinon-chai")
assert = chai.assert
expect = chai.expect
should = chai.should()
chai.use(sinonChai)
###
Assert that two items are the same.
@param actual
@param expected
@param {String} [message] failure message
###
assert.same = (actual, expected, message) ->
assert.deepEqual actual, expected, message
testCreator = ->
test =
mocker: null
beforeEach: ->
test.mocker = sinon.createSandbox()
afterEach: ->
test.mocker.restore()
test
module?.exports =
_: require('lodash')
testCreator: testCreator
assert: assert
expect: expect
should: should
| 71387 | ###
Copyright (c) 2014 <NAME> (hiddentao.com)
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.
###
sinon = require('sinon')
chai = require("chai")
sinonChai = require("sinon-chai")
assert = chai.assert
expect = chai.expect
should = chai.should()
chai.use(sinonChai)
###
Assert that two items are the same.
@param actual
@param expected
@param {String} [message] failure message
###
assert.same = (actual, expected, message) ->
assert.deepEqual actual, expected, message
testCreator = ->
test =
mocker: null
beforeEach: ->
test.mocker = sinon.createSandbox()
afterEach: ->
test.mocker.restore()
test
module?.exports =
_: require('lodash')
testCreator: testCreator
assert: assert
expect: expect
should: should
| true | ###
Copyright (c) 2014 PI:NAME:<NAME>END_PI (hiddentao.com)
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.
###
sinon = require('sinon')
chai = require("chai")
sinonChai = require("sinon-chai")
assert = chai.assert
expect = chai.expect
should = chai.should()
chai.use(sinonChai)
###
Assert that two items are the same.
@param actual
@param expected
@param {String} [message] failure message
###
assert.same = (actual, expected, message) ->
assert.deepEqual actual, expected, message
testCreator = ->
test =
mocker: null
beforeEach: ->
test.mocker = sinon.createSandbox()
afterEach: ->
test.mocker.restore()
test
module?.exports =
_: require('lodash')
testCreator: testCreator
assert: assert
expect: expect
should: should
|
[
{
"context": "# copyright 2015 by mike lodato (zvxryb@gmail.com)\n# this work is subject to the ",
"end": 31,
"score": 0.9998553395271301,
"start": 20,
"tag": "NAME",
"value": "mike lodato"
},
{
"context": "# copyright 2015 by mike lodato (zvxryb@gmail.com)\n# this work is subject to the terms of the MIT l",
"end": 49,
"score": 0.9999286532402039,
"start": 33,
"tag": "EMAIL",
"value": "zvxryb@gmail.com"
}
] | src/main.coffee | zvxryb/openjscad-solve | 1 | # copyright 2015 by mike lodato (zvxryb@gmail.com)
# this work is subject to the terms of the MIT license
define ['math/expr', 'geometry/scalar', 'geometry/vector', 'geometry/line', 'math/system', 'coffeequate'], (Expr, Scalar, Vector, Line, System, CQ) ->
Expr: Expr
Scalar: Scalar
Vector: Vector
Line: Line
System: System
CQ: CQ
| 212908 | # copyright 2015 by <NAME> (<EMAIL>)
# this work is subject to the terms of the MIT license
define ['math/expr', 'geometry/scalar', 'geometry/vector', 'geometry/line', 'math/system', 'coffeequate'], (Expr, Scalar, Vector, Line, System, CQ) ->
Expr: Expr
Scalar: Scalar
Vector: Vector
Line: Line
System: System
CQ: CQ
| true | # copyright 2015 by PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# this work is subject to the terms of the MIT license
define ['math/expr', 'geometry/scalar', 'geometry/vector', 'geometry/line', 'math/system', 'coffeequate'], (Expr, Scalar, Vector, Line, System, CQ) ->
Expr: Expr
Scalar: Scalar
Vector: Vector
Line: Line
System: System
CQ: CQ
|
[
{
"context": " \n target_view_key = $(e.target).attr('id').replace('goto-', '')\n @tab_views[@shown_id].root_el.",
"end": 2249,
"score": 0.60579514503479,
"start": 2242,
"tag": "KEY",
"value": "replace"
},
{
"context": "et_view_key = $(e.target).attr('id').replace('goto-', '')\n @tab_views[@shown_id].root_el.hide()\n ",
"end": 2255,
"score": 0.7871523499488831,
"start": 2255,
"tag": "KEY",
"value": ""
}
] | app/assets/javascripts/backbone/goal_getter/views/body_portfolio_view.js.coffee | UrbanStrategies/goalgetterapp | 0 | GoalGetter.Views.PortfolioView = GoalGetter.Views.ScreenBase.extend
className: 'portfolio'
initialize: ->
_.bindAll @, 'render'
@tab_views =
'public': {}
'portfolio-friends': null
'portfolio-likes': null
'milestones': null
@shown_id = 'public'
manage_bubbles: () ->
view_self = @
@$el.find('.goto').each (i, e) ->
folder = $(e).find('.bubble').data('folder-name')
if view_self.model.get('inbox').hasOwnProperty(folder) and (ml = view_self.model.get('inbox')[folder]).length > 0
b = $(e).find('.bubble')
b.text ml.length
b.addClass('visible')
set_friend_action: () ->
status = @model.get 'is_friend'
return if status == 'self'
button_text = switch status
when 'friend'
'unfriend'
when 'not-friend'
'add friend'
# Change this later if we change the text above.
action = button_text.replace(' ', '-')
b = @$el.find('#change-friend-status')
b.show()
b.text button_text
b.data 'action', action
delayed_render: (key) ->
if key != 'public' and @tab_views[key] == null
el = @construct_screen key, @tab_views
@tab_views[key].root_el = el
else
if @tab_views[key].hasOwnProperty('view_obj') and @tab_views[key].view_obj.hasOwnProperty('fetcher')
@tab_views[key].view_obj.fetcher.resume()
@tab_views[key].root_el.show()
events:
# Name editing
'click .username': (e) ->
@$('.username').attr 'contentEditable', true
'blur .username': (e) ->
@model.data_change 'user_name', $(e.target).text(), target_div: $(e.target)
# Tab switching
'click .goto': (e) ->
@previous_tab.removeClass('selected')
@previous_tab = $(e.target)
@previous_tab.addClass('selected')
d = @previous_tab.find('.bubble')
if d.hasClass('visible')
folder = d.data('folder-name')
d.removeClass 'visible'
@update_alert folder
vo = @tab_views[@shown_id].view_obj
if typeof vo != 'undefined' and vo.hasOwnProperty('fetcher') # pause fetching
@tab_views[@shown_id].view_obj.fetcher.pause()
target_view_key = $(e.target).attr('id').replace('goto-', '')
@tab_views[@shown_id].root_el.hide()
@shown_id = target_view_key
@delayed_render @shown_id
# Generic handler for all portfolio additions
'click .add-card': (e) ->
if $(e.target).data('card-type')
click_on_node = $(e.target)
else
click_on_node = $(e.target).closest('.card-entry')
click_on = click_on_node.data('card-type')
if click_on == 'an-achievement'
achievement_type = click_on_node.data('achievement-type')
@model.card_type = click_on
@model.achievement_type = achievement_type
# Want to show a wave
@wave_wait = setInterval(
(ctx) ->
clearInterval ctx.wave_wait
ctx.trigger 'navigation:change', {to: ('add-' + click_on)}
400,
@
)
'click #change-friend-status': (e) ->
# is this orphaned code?
f = $('form#make-friend-form')
data =
payload:
code: $('#change-friend-status').data('action')
friend_id: @model.get 'id'
view_self = @
$.ajax(
method: 'PUT'
url: '/profile.json'
data: data
success: (d, s, x) ->
if d.data.status
view_self.model.set 'is_friend', d.data.is_friend
view_self.set_friend_action()
)
'click #sign-out': ->
view_self = @
$.ajax(
method: 'DELETE'
url: '/users/sign_out'
success: (d, s, x) ->
# assume correctness of response
view_self.model.destroy_user_data()
document.location.href = '/'
)
render: ->
t_func = _.template $('#body_portfolio_template').html()
@$el.html t_func({username: @model.get('user_name')})
@set_friend_action()
@manage_bubbles()
@previous_tab = @$el.find('.goto.selected')
@$el.find('#portfolio-img').attr 'src', @model.get('profile_pic_url')
view_self = @
# Create drop zone
$.ajaxSetup(
headers:
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
)
if @model.current_screen == '3'
dz = $("#portfolio-img").dropzone(
url: "/profile/photo"
headers:
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
init: ->
@on('success', (file, resp) ->
if resp.hasOwnProperty('redirect')
view_self.trigger 'navigation:change', {redirect: resp.redirect}
)
)
dz.on('dragenter', (e) ->
$(e.target).addClass('dragged')
)
dz.on('dragleave', (e) ->
$(e.target).removeClass('dragged')
)
dz.on('drop', (e) ->
$(e.target).removeClass('dragged')
$(e.target).hide()
$('.portfolio-img.loading').show()
)
# Add work experience
wex_card = @$el.find('.portfolio-card#workex')
@model.get('work_experience').forEach (item) ->
t_func = _.template $('#body_portfolio_work_experience').html()
el = $(t_func(
title: item.work_title
workplace: item.work_workplace,
startdate: item.work_startdate
enddate: item.work_enddate
))
wex_card.last().append el
# Add the remaining categories beneath work experience; these next two templates are in _portfolio_category.html.haml
t_func = _.template $('#portfolio_category').html()
@model.get('portfolio_categories').forEach (cat_name) ->
add_bar = $(t_func({card_name: cat_name}))
view_self.$el.find('.workex-row').after add_bar
t_func_1 = _.template $('#body_portfolio_achievement').html()
avlbl_ach = view_self.model.get('achievements').filter( (e) ->
e.type == cat_name
)
if avlbl_ach.length > 0
avlbl_ach[0]['texts'].forEach( (txt) ->
add_bar.append $(t_func_1({text: txt}))
)
null
@tab_views.public.root_el = @$el.find('#public')
@$el
| 182908 | GoalGetter.Views.PortfolioView = GoalGetter.Views.ScreenBase.extend
className: 'portfolio'
initialize: ->
_.bindAll @, 'render'
@tab_views =
'public': {}
'portfolio-friends': null
'portfolio-likes': null
'milestones': null
@shown_id = 'public'
manage_bubbles: () ->
view_self = @
@$el.find('.goto').each (i, e) ->
folder = $(e).find('.bubble').data('folder-name')
if view_self.model.get('inbox').hasOwnProperty(folder) and (ml = view_self.model.get('inbox')[folder]).length > 0
b = $(e).find('.bubble')
b.text ml.length
b.addClass('visible')
set_friend_action: () ->
status = @model.get 'is_friend'
return if status == 'self'
button_text = switch status
when 'friend'
'unfriend'
when 'not-friend'
'add friend'
# Change this later if we change the text above.
action = button_text.replace(' ', '-')
b = @$el.find('#change-friend-status')
b.show()
b.text button_text
b.data 'action', action
delayed_render: (key) ->
if key != 'public' and @tab_views[key] == null
el = @construct_screen key, @tab_views
@tab_views[key].root_el = el
else
if @tab_views[key].hasOwnProperty('view_obj') and @tab_views[key].view_obj.hasOwnProperty('fetcher')
@tab_views[key].view_obj.fetcher.resume()
@tab_views[key].root_el.show()
events:
# Name editing
'click .username': (e) ->
@$('.username').attr 'contentEditable', true
'blur .username': (e) ->
@model.data_change 'user_name', $(e.target).text(), target_div: $(e.target)
# Tab switching
'click .goto': (e) ->
@previous_tab.removeClass('selected')
@previous_tab = $(e.target)
@previous_tab.addClass('selected')
d = @previous_tab.find('.bubble')
if d.hasClass('visible')
folder = d.data('folder-name')
d.removeClass 'visible'
@update_alert folder
vo = @tab_views[@shown_id].view_obj
if typeof vo != 'undefined' and vo.hasOwnProperty('fetcher') # pause fetching
@tab_views[@shown_id].view_obj.fetcher.pause()
target_view_key = $(e.target).attr('id').<KEY>('goto<KEY>-', '')
@tab_views[@shown_id].root_el.hide()
@shown_id = target_view_key
@delayed_render @shown_id
# Generic handler for all portfolio additions
'click .add-card': (e) ->
if $(e.target).data('card-type')
click_on_node = $(e.target)
else
click_on_node = $(e.target).closest('.card-entry')
click_on = click_on_node.data('card-type')
if click_on == 'an-achievement'
achievement_type = click_on_node.data('achievement-type')
@model.card_type = click_on
@model.achievement_type = achievement_type
# Want to show a wave
@wave_wait = setInterval(
(ctx) ->
clearInterval ctx.wave_wait
ctx.trigger 'navigation:change', {to: ('add-' + click_on)}
400,
@
)
'click #change-friend-status': (e) ->
# is this orphaned code?
f = $('form#make-friend-form')
data =
payload:
code: $('#change-friend-status').data('action')
friend_id: @model.get 'id'
view_self = @
$.ajax(
method: 'PUT'
url: '/profile.json'
data: data
success: (d, s, x) ->
if d.data.status
view_self.model.set 'is_friend', d.data.is_friend
view_self.set_friend_action()
)
'click #sign-out': ->
view_self = @
$.ajax(
method: 'DELETE'
url: '/users/sign_out'
success: (d, s, x) ->
# assume correctness of response
view_self.model.destroy_user_data()
document.location.href = '/'
)
render: ->
t_func = _.template $('#body_portfolio_template').html()
@$el.html t_func({username: @model.get('user_name')})
@set_friend_action()
@manage_bubbles()
@previous_tab = @$el.find('.goto.selected')
@$el.find('#portfolio-img').attr 'src', @model.get('profile_pic_url')
view_self = @
# Create drop zone
$.ajaxSetup(
headers:
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
)
if @model.current_screen == '3'
dz = $("#portfolio-img").dropzone(
url: "/profile/photo"
headers:
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
init: ->
@on('success', (file, resp) ->
if resp.hasOwnProperty('redirect')
view_self.trigger 'navigation:change', {redirect: resp.redirect}
)
)
dz.on('dragenter', (e) ->
$(e.target).addClass('dragged')
)
dz.on('dragleave', (e) ->
$(e.target).removeClass('dragged')
)
dz.on('drop', (e) ->
$(e.target).removeClass('dragged')
$(e.target).hide()
$('.portfolio-img.loading').show()
)
# Add work experience
wex_card = @$el.find('.portfolio-card#workex')
@model.get('work_experience').forEach (item) ->
t_func = _.template $('#body_portfolio_work_experience').html()
el = $(t_func(
title: item.work_title
workplace: item.work_workplace,
startdate: item.work_startdate
enddate: item.work_enddate
))
wex_card.last().append el
# Add the remaining categories beneath work experience; these next two templates are in _portfolio_category.html.haml
t_func = _.template $('#portfolio_category').html()
@model.get('portfolio_categories').forEach (cat_name) ->
add_bar = $(t_func({card_name: cat_name}))
view_self.$el.find('.workex-row').after add_bar
t_func_1 = _.template $('#body_portfolio_achievement').html()
avlbl_ach = view_self.model.get('achievements').filter( (e) ->
e.type == cat_name
)
if avlbl_ach.length > 0
avlbl_ach[0]['texts'].forEach( (txt) ->
add_bar.append $(t_func_1({text: txt}))
)
null
@tab_views.public.root_el = @$el.find('#public')
@$el
| true | GoalGetter.Views.PortfolioView = GoalGetter.Views.ScreenBase.extend
className: 'portfolio'
initialize: ->
_.bindAll @, 'render'
@tab_views =
'public': {}
'portfolio-friends': null
'portfolio-likes': null
'milestones': null
@shown_id = 'public'
manage_bubbles: () ->
view_self = @
@$el.find('.goto').each (i, e) ->
folder = $(e).find('.bubble').data('folder-name')
if view_self.model.get('inbox').hasOwnProperty(folder) and (ml = view_self.model.get('inbox')[folder]).length > 0
b = $(e).find('.bubble')
b.text ml.length
b.addClass('visible')
set_friend_action: () ->
status = @model.get 'is_friend'
return if status == 'self'
button_text = switch status
when 'friend'
'unfriend'
when 'not-friend'
'add friend'
# Change this later if we change the text above.
action = button_text.replace(' ', '-')
b = @$el.find('#change-friend-status')
b.show()
b.text button_text
b.data 'action', action
delayed_render: (key) ->
if key != 'public' and @tab_views[key] == null
el = @construct_screen key, @tab_views
@tab_views[key].root_el = el
else
if @tab_views[key].hasOwnProperty('view_obj') and @tab_views[key].view_obj.hasOwnProperty('fetcher')
@tab_views[key].view_obj.fetcher.resume()
@tab_views[key].root_el.show()
events:
# Name editing
'click .username': (e) ->
@$('.username').attr 'contentEditable', true
'blur .username': (e) ->
@model.data_change 'user_name', $(e.target).text(), target_div: $(e.target)
# Tab switching
'click .goto': (e) ->
@previous_tab.removeClass('selected')
@previous_tab = $(e.target)
@previous_tab.addClass('selected')
d = @previous_tab.find('.bubble')
if d.hasClass('visible')
folder = d.data('folder-name')
d.removeClass 'visible'
@update_alert folder
vo = @tab_views[@shown_id].view_obj
if typeof vo != 'undefined' and vo.hasOwnProperty('fetcher') # pause fetching
@tab_views[@shown_id].view_obj.fetcher.pause()
target_view_key = $(e.target).attr('id').PI:KEY:<KEY>END_PI('gotoPI:KEY:<KEY>END_PI-', '')
@tab_views[@shown_id].root_el.hide()
@shown_id = target_view_key
@delayed_render @shown_id
# Generic handler for all portfolio additions
'click .add-card': (e) ->
if $(e.target).data('card-type')
click_on_node = $(e.target)
else
click_on_node = $(e.target).closest('.card-entry')
click_on = click_on_node.data('card-type')
if click_on == 'an-achievement'
achievement_type = click_on_node.data('achievement-type')
@model.card_type = click_on
@model.achievement_type = achievement_type
# Want to show a wave
@wave_wait = setInterval(
(ctx) ->
clearInterval ctx.wave_wait
ctx.trigger 'navigation:change', {to: ('add-' + click_on)}
400,
@
)
'click #change-friend-status': (e) ->
# is this orphaned code?
f = $('form#make-friend-form')
data =
payload:
code: $('#change-friend-status').data('action')
friend_id: @model.get 'id'
view_self = @
$.ajax(
method: 'PUT'
url: '/profile.json'
data: data
success: (d, s, x) ->
if d.data.status
view_self.model.set 'is_friend', d.data.is_friend
view_self.set_friend_action()
)
'click #sign-out': ->
view_self = @
$.ajax(
method: 'DELETE'
url: '/users/sign_out'
success: (d, s, x) ->
# assume correctness of response
view_self.model.destroy_user_data()
document.location.href = '/'
)
render: ->
t_func = _.template $('#body_portfolio_template').html()
@$el.html t_func({username: @model.get('user_name')})
@set_friend_action()
@manage_bubbles()
@previous_tab = @$el.find('.goto.selected')
@$el.find('#portfolio-img').attr 'src', @model.get('profile_pic_url')
view_self = @
# Create drop zone
$.ajaxSetup(
headers:
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
)
if @model.current_screen == '3'
dz = $("#portfolio-img").dropzone(
url: "/profile/photo"
headers:
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
init: ->
@on('success', (file, resp) ->
if resp.hasOwnProperty('redirect')
view_self.trigger 'navigation:change', {redirect: resp.redirect}
)
)
dz.on('dragenter', (e) ->
$(e.target).addClass('dragged')
)
dz.on('dragleave', (e) ->
$(e.target).removeClass('dragged')
)
dz.on('drop', (e) ->
$(e.target).removeClass('dragged')
$(e.target).hide()
$('.portfolio-img.loading').show()
)
# Add work experience
wex_card = @$el.find('.portfolio-card#workex')
@model.get('work_experience').forEach (item) ->
t_func = _.template $('#body_portfolio_work_experience').html()
el = $(t_func(
title: item.work_title
workplace: item.work_workplace,
startdate: item.work_startdate
enddate: item.work_enddate
))
wex_card.last().append el
# Add the remaining categories beneath work experience; these next two templates are in _portfolio_category.html.haml
t_func = _.template $('#portfolio_category').html()
@model.get('portfolio_categories').forEach (cat_name) ->
add_bar = $(t_func({card_name: cat_name}))
view_self.$el.find('.workex-row').after add_bar
t_func_1 = _.template $('#body_portfolio_achievement').html()
avlbl_ach = view_self.model.get('achievements').filter( (e) ->
e.type == cat_name
)
if avlbl_ach.length > 0
avlbl_ach[0]['texts'].forEach( (txt) ->
add_bar.append $(t_func_1({text: txt}))
)
null
@tab_views.public.root_el = @$el.find('#public')
@$el
|
[
{
"context": "reen readers\n return unless me.get('name') is 'zersiax' #in ['zersiax', 'Nick']\n ascii = $('#ascii-s",
"end": 7276,
"score": 0.9977903366088867,
"start": 7269,
"tag": "USERNAME",
"value": "zersiax"
},
{
"context": " return unless me.get('name') is 'zersiax' #in ['zersiax', 'Nick']\n ascii = $('#ascii-surface')\n tha",
"end": 7292,
"score": 0.9857901930809021,
"start": 7285,
"tag": "USERNAME",
"value": "zersiax"
},
{
"context": "ess me.get('name') is 'zersiax' #in ['zersiax', 'Nick']\n ascii = $('#ascii-surface')\n thangs = (l",
"end": 7300,
"score": 0.984811544418335,
"start": 7296,
"tag": "NAME",
"value": "Nick"
}
] | app/lib/surface/LankBoss.coffee | adamcsillag/codecombat | 2 | CocoClass = require 'core/CocoClass'
{me} = require 'core/auth'
LayerAdapter = require './LayerAdapter'
FlagLank = require 'lib/surface/FlagLank'
Lank = require 'lib/surface/Lank'
Mark = require './Mark'
Grid = require 'lib/world/Grid'
utils = require 'core/utils'
module.exports = class LankBoss extends CocoClass
subscriptions:
'level:set-debug': 'onSetDebug'
'sprite:highlight-sprites': 'onHighlightSprites'
'surface:stage-mouse-down': 'onStageMouseDown'
'level:select-sprite': 'onSelectSprite'
'level:suppress-selection-sounds': 'onSuppressSelectionSounds'
'level:lock-select': 'onSetLockSelect'
'level:restarted': 'onLevelRestarted'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'camera:dragged': 'onCameraDragged'
'sprite:loaded': -> @update(true)
'level:flag-color-selected': 'onFlagColorSelected'
'level:flag-updated': 'onFlagUpdated'
'surface:flag-appeared': 'onFlagAppeared'
'surface:remove-selected-flag': 'onRemoveSelectedFlag'
constructor: (@options={}) ->
super()
@handleEvents = @options.handleEvents
@gameUIState = @options.gameUIState
@dragged = 0
@camera = @options.camera
@webGLStage = @options.webGLStage
@surfaceTextLayer = @options.surfaceTextLayer
@world = @options.world
@options.thangTypes ?= []
@lanks = {}
@lankArray = [] # Mirror @lanks, but faster for when we just need to iterate
@createLayers()
@pendingFlags = []
if not @handleEvents
@listenTo @gameUIState, 'change:selected', @onChangeSelected
destroy: ->
@removeLank lank for thangID, lank of @lanks
@targetMark?.destroy()
@selectionMark?.destroy()
lankLayer.destroy() for lankLayer in _.values @layerAdapters
super()
toString: -> "<LankBoss: #{@lankArray.length} lanks>"
thangTypeFor: (type) ->
_.find @options.thangTypes, (m) -> m.get('original') is type or m.get('name') is type
createLayers: ->
@layerAdapters = {}
for [name, priority] in [
['Land', -40]
['Ground', -30]
['Obstacle', -20]
['Path', -10]
['Default', 0]
['Floating', 10]
]
@layerAdapters[name] = new LayerAdapter name: name, webGL: true, layerPriority: priority, transform: LayerAdapter.TRANSFORM_SURFACE, camera: @camera
@webGLStage.addChild (lankLayer.container for lankLayer in _.values(@layerAdapters))...
layerForChild: (child, lank) ->
unless child.layerPriority?
if thang = lank?.thang
child.layerPriority = thang.layerPriority
child.layerPriority ?= 0 if thang.isSelectable
child.layerPriority ?= -40 if thang.isLand
child.layerPriority ?= 0
return @layerAdapters['Default'] unless child.layerPriority
layer = _.findLast @layerAdapters, (layer, name) ->
layer.layerPriority <= child.layerPriority
layer ?= @layerAdapters['Land'] if child.layerPriority < -40
layer ? @layerAdapters['Default']
addLank: (lank, id=null, layer=null) ->
id ?= lank.thang.id
console.error 'Lank collision! Already have:', id if @lanks[id]
@lanks[id] = lank
@lankArray.push lank
layer ?= @layerAdapters['Obstacle'] if lank.thang?.spriteName.search(/(dungeon|indoor|ice|classroom|vr).wall/i) isnt -1
layer ?= @layerForChild lank.sprite, lank
layer.addLank lank
layer.updateLayerOrder()
lank
createMarks: ->
@targetMark = new Mark name: 'target', camera: @camera, layer: @layerAdapters['Ground'], thangType: 'target'
@selectionMark = new Mark name: 'selection', camera: @camera, layer: @layerAdapters['Ground'], thangType: 'selection'
createLankOptions: (options) ->
_.extend options, {
@camera
resolutionFactor: SPRITE_RESOLUTION_FACTOR
groundLayer: @layerAdapters['Ground']
textLayer: @surfaceTextLayer
floatingLayer: @layerAdapters['Floating']
showInvisible: @options.showInvisible
@gameUIState
@handleEvents
}
onSetDebug: (e) ->
return if e.debug is @debug
@debug = e.debug
lank.setDebug @debug for lank in @lankArray
onHighlightSprites: (e) ->
highlightedIDs = e.thangIDs or []
for thangID, lank of @lanks
lank.setHighlight? thangID in highlightedIDs, e.delay
addThangToLanks: (thang, layer=null) ->
return console.warn 'Tried to add Thang to the surface it already has:', thang.id if @lanks[thang.id]
thangType = _.find @options.thangTypes, (m) ->
return false unless m.get('actions') or m.get('raster')
return m.get('name') is thang.spriteName
thangType ?= _.find @options.thangTypes, (m) -> return m.get('name') is thang.spriteName
return console.error "Couldn't find ThangType for", thang unless thangType
options = @createLankOptions thang: thang
options.resolutionFactor = if thangType.get('kind') is 'Floor' then 2 else SPRITE_RESOLUTION_FACTOR
if @options.playerNames and /Hero Placeholder/.test thang.id
options.playerName = @options.playerNames[thang.team]
lank = new Lank thangType, options
@listenTo lank, 'sprite:mouse-up', @onLankMouseUp
@addLank lank, null, layer
lank.setDebug @debug
lank
removeLank: (lank) ->
lank.layer.removeLank(lank)
thang = lank.thang
delete @lanks[lank.thang.id]
@lankArray.splice @lankArray.indexOf(lank), 1
@stopListening lank
lank.destroy()
lank.thang = thang # Keep around so that we know which thang the destroyed thang was for
updateSounds: ->
lank.playSounds() for lank in @lankArray # hmm; doesn't work for lanks which we didn't add yet in adjustLankExistence
update: (frameChanged) ->
@adjustLankExistence() if frameChanged
lank.update frameChanged for lank in @lankArray
@updateSelection()
@layerAdapters['Default'].updateLayerOrder()
@cacheObstacles()
adjustLankExistence: ->
# Add anything new, remove anything old, update everything current
updatedObstacles = []
itemsJustEquipped = []
for thang in @world.thangs when thang.exists and thang.pos
itemsJustEquipped = itemsJustEquipped.concat @equipNewItems thang if thang.equip
if lank = @lanks[thang.id]
lank.setThang thang # make sure Lank has latest Thang
else
lank = @addThangToLanks(thang)
Backbone.Mediator.publish 'surface:new-thang-added', thang: thang, sprite: lank
updatedObstacles.push lank if lank.sprite.parent is @layerAdapters['Obstacle']
lank.playSounds()
item.modifyStats() for item in itemsJustEquipped
for thangID, lank of @lanks
missing = not (lank.notOfThisWorld or @world.thangMap[thangID]?.exists)
isObstacle = lank.sprite.parent is @layerAdapters['Obstacle']
updatedObstacles.push lank if isObstacle and (missing or lank.hasMoved)
lank.hasMoved = false
@removeLank lank if missing
@cacheObstacles updatedObstacles if updatedObstacles.length and @cachedObstacles
# mainly for handling selecting thangs from session when the thang is not always in existence
if @willSelectThang and @lanks[@willSelectThang[0]]
@selectThang @willSelectThang...
@updateScreenReader()
updateScreenReader: ->
# Testing ASCII map for screen readers
return unless me.get('name') is 'zersiax' #in ['zersiax', 'Nick']
ascii = $('#ascii-surface')
thangs = (lank.thang for lank in @lankArray)
grid = new Grid thangs, @world.width, @world.height, 0, 0, 0, true
utils.replaceText ascii, grid.toString true
ascii.css 'transform', 'initial'
fullWidth = ascii.innerWidth()
fullHeight = ascii.innerHeight()
availableWidth = ascii.parent().innerWidth()
availableHeight = ascii.parent().innerHeight()
scale = availableWidth / fullWidth
scale = Math.min scale, availableHeight / fullHeight
ascii.css 'transform', "scale(#{scale})"
equipNewItems: (thang) ->
itemsJustEquipped = []
if thang.equip and not thang.equipped
thang.equip() # Pretty hacky, but needed since initialize may not be called if we're not running Systems.
itemsJustEquipped.push thang
if thang.inventoryIDs
# Even hackier: these items were only created/equipped during simulation, so we reequip here.
for slot, itemID of thang.inventoryIDs
item = @world.getThangByID itemID
unless item.equipped
console.log thang.id, 'equipping', item, 'in', thang.slot, 'Surface-side, but it cannot equip?' unless item.equip
item.equip?()
itemsJustEquipped.push item if item.equip
return itemsJustEquipped
cacheObstacles: (updatedObstacles=null) ->
return if @cachedObstacles and not updatedObstacles
lankArray = @lankArray
wallLanks = (lank for lank in lankArray when lank.thangType?.get('name').search(/(dungeon|indoor|ice|classroom|vr).wall/i) isnt -1)
return if _.any (s.stillLoading for s in wallLanks)
walls = (lank.thang for lank in wallLanks)
@world.calculateBounds()
wallGrid = new Grid walls, @world.width, @world.height
if updatedObstacles
possiblyUpdatedWallLanks = (lank for lank in wallLanks when _.find updatedObstacles, (w2) -> lank is w2 or (Math.abs(lank.thang.pos.x - w2.thang.pos.x) + Math.abs(lank.thang.pos.y - w2.thang.pos.y)) <= 16)
else
possiblyUpdatedWallLanks = wallLanks
# console.log 'updating up to', possiblyUpdatedWallLanks.length, 'of', wallLanks.length, 'wall lanks from updatedObstacles', updatedObstacles
for wallLank in possiblyUpdatedWallLanks
wallLank.queueAction 'idle' if not wallLank.currentRootAction
wallLank.lockAction(false)
wallLank.updateActionDirection wallGrid
wallLank.lockAction(true)
wallLank.updateScale()
wallLank.updatePosition()
# console.log wallGrid.toString()
@cachedObstacles = true
lankFor: (thangID) -> @lanks[thangID]
onNewWorld: (e) ->
@world = @options.world = e.world
# Clear obstacle cache for this level, since we are spawning walls dynamically
@cachedObstacles = false if e.finished and /kithgard-mastery/.test window.location.href
play: ->
lank.play() for lank in @lankArray
@selectionMark?.play()
@targetMark?.play()
stop: ->
lank.stop() for lank in @lankArray
@selectionMark?.stop()
@targetMark?.stop()
# Selection
onSuppressSelectionSounds: (e) -> @suppressSelectionSounds = e.suppress
onSetLockSelect: (e) -> @selectLocked = e.lock
onLevelRestarted: (e) ->
@selectLocked = false
@selectLank e, null
onSelectSprite: (e) ->
@selectThang e.thangID, e.spellName
onCameraDragged: ->
@dragged += 1
onLankMouseUp: (e) ->
return unless @handleEvents
return if key.shift #and @options.choosing
return @dragged = 0 if @dragged > 3
@dragged = 0
lank = if e.sprite?.thang?.isSelectable then e.sprite else null
return if @flagCursorLank and lank?.thangType.get('name') is 'Flag'
@selectLank e, lank
onStageMouseDown: (e) ->
return unless @handleEvents
return if key.shift #and @options.choosing
@selectLank e if e.onBackground
onChangeSelected: (gameUIState, selected) ->
oldLanks = (s.sprite for s in gameUIState.previousAttributes().selected or [])
newLanks = (s.sprite for s in selected or [])
addedLanks = _.difference(newLanks, oldLanks)
removedLanks = _.difference(oldLanks, newLanks)
for lank in addedLanks
layer = if lank.sprite.parent isnt @layerAdapters.Default.container then @layerAdapters.Default else @layerAdapters.Ground
mark = new Mark name: 'selection', camera: @camera, layer: layer, thangType: 'selection'
mark.toggle true
mark.setLank(lank)
mark.update()
lank.marks.selection = mark # TODO: Figure out how to non-hackily assign lank this mark
for lank in removedLanks
lank.removeMark?('selection')
selectThang: (thangID, spellName=null, treemaThangSelected = null) ->
return @willSelectThang = [thangID, spellName] unless @lanks[thangID]
@selectLank null, @lanks[thangID], spellName, treemaThangSelected
selectLank: (e, lank=null, spellName=null, treemaThangSelected = null) ->
return if e and (@disabled or @selectLocked) # Ignore clicks for selection/panning/wizard movement while disabled or select is locked
worldPos = lank?.thang?.pos
worldPos ?= @camera.screenToWorld {x: e.originalEvent.rawX, y: e.originalEvent.rawY} if e?.originalEvent
if @handleEvents
if (not @reallyStopMoving) and worldPos and (@options.navigateToSelection or not lank or treemaThangSelected) and e?.originalEvent?.nativeEvent?.which isnt 3
@camera.zoomTo(lank?.sprite or @camera.worldToSurface(worldPos), @camera.zoom, 1000, true)
lank = null if @options.choosing # Don't select lanks while choosing
if lank isnt @selectedLank
@selectedLank?.selected = false
lank?.selected = true
@selectedLank = lank
alive = lank and not (lank.thang.health < 0)
Backbone.Mediator.publish 'surface:sprite-selected',
thang: if lank then lank.thang else null
sprite: lank
spellName: spellName ? e?.spellName
originalEvent: e
worldPos: worldPos
@willSelectThang = null if lank # Now that we've done a real selection, don't reselect some other Thang later.
if alive and not @suppressSelectionSounds
instance = lank.playSound 'selected'
if instance?.playState is 'playSucceeded'
Backbone.Mediator.publish 'sprite:thang-began-talking', thang: lank?.thang
instance.addEventListener 'complete', ->
Backbone.Mediator.publish 'sprite:thang-finished-talking', thang: lank?.thang
onFlagColorSelected: (e) ->
@removeLank @flagCursorLank if @flagCursorLank
@flagCursorLank = null
for flagLank in @lankArray when flagLank.thangType.get('name') is 'Flag'
flagLank.sprite.cursor = if e.color then 'crosshair' else 'pointer'
return unless e.color
@flagCursorLank = new FlagLank @thangTypeFor('Flag'), @createLankOptions(thangID: 'Flag Cursor', color: e.color, team: me.team, isCursor: true, pos: e.pos)
@addLank @flagCursorLank, @flagCursorLank.thang.id, @layerAdapters['Floating']
onFlagUpdated: (e) ->
return unless e.active
pendingFlag = new FlagLank @thangTypeFor('Flag'), @createLankOptions(thangID: 'Pending Flag ' + Math.random(), color: e.color, team: e.team, isCursor: false, pos: e.pos)
@addLank pendingFlag, pendingFlag.thang.id, @layerAdapters['Floating']
@pendingFlags.push pendingFlag
onFlagAppeared: (e) ->
# Remove the pending flag that matches this one's color/team/position, and any color/team matches placed earlier.
t1 = e.sprite.thang
pending = (@pendingFlags ? []).slice()
foundExactMatch = false
for i in [pending.length - 1 .. 0] by -1
pendingFlag = pending[i]
t2 = pendingFlag.thang
matchedType = t1.color is t2.color and t1.team is t2.team
matched = matchedType and (foundExactMatch or Math.abs(t1.pos.x - t2.pos.x) < 0.00001 and Math.abs(t1.pos.y - t2.pos.y) < 0.00001)
if matched
foundExactMatch = true
@pendingFlags.splice(i, 1)
@removeLank pendingFlag
e.sprite.sprite?.cursor = if @flagCursorLank then 'crosshair' else 'pointer'
null
onRemoveSelectedFlag: (e) ->
# Remove the selected lank if it's a flag, or any flag of the given color if a color is given.
flagLank = _.find [@selectedLank].concat(@lankArray), (lank) ->
lank and lank.thangType.get('name') is 'Flag' and lank.thang.team is me.team and (lank.thang.color is e.color or not e.color) and not lank.notOfThisWorld
return unless flagLank
Backbone.Mediator.publish 'surface:remove-flag', color: flagLank.thang.color
# Marks
updateSelection: ->
if @selectedLank?.thang and (not @selectedLank.thang.exists or not @world.getThangByID @selectedLank.thang.id)
thangID = @selectedLank.thang.id
@selectedLank = null # Don't actually trigger deselection, but remove the selected lank.
@selectionMark?.toggle false
@willSelectThang = [thangID, null]
@updateTarget()
return unless @selectionMark
@selectedLank = null if @selectedLank and (@selectedLank.destroyed or not @selectedLank.thang)
# The selection mark should be on the ground layer, unless we're not a normal lank (like a wall), in which case we'll place it higher so we can see it.
if @selectedLank and @selectedLank.sprite.parent isnt @layerAdapters.Default.container
@selectionMark.setLayer @layerAdapters.Default
else if @selectedLank
@selectionMark.setLayer @layerAdapters.Ground
@selectionMark.toggle @selectedLank?
@selectionMark.setLank @selectedLank
@selectionMark.update()
updateTarget: ->
return unless @targetMark
thang = @selectedLank?.thang
target = thang?.target
targetPos = thang?.targetPos
targetPos = null if targetPos?.isZero?() # Null targetPos get serialized as (0, 0, 0)
@targetMark.setLank if target then @lanks[target.id] else null
@targetMark.toggle @targetMark.lank or targetPos
@targetMark.update if targetPos then @camera.worldToSurface targetPos else null
| 132016 | CocoClass = require 'core/CocoClass'
{me} = require 'core/auth'
LayerAdapter = require './LayerAdapter'
FlagLank = require 'lib/surface/FlagLank'
Lank = require 'lib/surface/Lank'
Mark = require './Mark'
Grid = require 'lib/world/Grid'
utils = require 'core/utils'
module.exports = class LankBoss extends CocoClass
subscriptions:
'level:set-debug': 'onSetDebug'
'sprite:highlight-sprites': 'onHighlightSprites'
'surface:stage-mouse-down': 'onStageMouseDown'
'level:select-sprite': 'onSelectSprite'
'level:suppress-selection-sounds': 'onSuppressSelectionSounds'
'level:lock-select': 'onSetLockSelect'
'level:restarted': 'onLevelRestarted'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'camera:dragged': 'onCameraDragged'
'sprite:loaded': -> @update(true)
'level:flag-color-selected': 'onFlagColorSelected'
'level:flag-updated': 'onFlagUpdated'
'surface:flag-appeared': 'onFlagAppeared'
'surface:remove-selected-flag': 'onRemoveSelectedFlag'
constructor: (@options={}) ->
super()
@handleEvents = @options.handleEvents
@gameUIState = @options.gameUIState
@dragged = 0
@camera = @options.camera
@webGLStage = @options.webGLStage
@surfaceTextLayer = @options.surfaceTextLayer
@world = @options.world
@options.thangTypes ?= []
@lanks = {}
@lankArray = [] # Mirror @lanks, but faster for when we just need to iterate
@createLayers()
@pendingFlags = []
if not @handleEvents
@listenTo @gameUIState, 'change:selected', @onChangeSelected
destroy: ->
@removeLank lank for thangID, lank of @lanks
@targetMark?.destroy()
@selectionMark?.destroy()
lankLayer.destroy() for lankLayer in _.values @layerAdapters
super()
toString: -> "<LankBoss: #{@lankArray.length} lanks>"
thangTypeFor: (type) ->
_.find @options.thangTypes, (m) -> m.get('original') is type or m.get('name') is type
createLayers: ->
@layerAdapters = {}
for [name, priority] in [
['Land', -40]
['Ground', -30]
['Obstacle', -20]
['Path', -10]
['Default', 0]
['Floating', 10]
]
@layerAdapters[name] = new LayerAdapter name: name, webGL: true, layerPriority: priority, transform: LayerAdapter.TRANSFORM_SURFACE, camera: @camera
@webGLStage.addChild (lankLayer.container for lankLayer in _.values(@layerAdapters))...
layerForChild: (child, lank) ->
unless child.layerPriority?
if thang = lank?.thang
child.layerPriority = thang.layerPriority
child.layerPriority ?= 0 if thang.isSelectable
child.layerPriority ?= -40 if thang.isLand
child.layerPriority ?= 0
return @layerAdapters['Default'] unless child.layerPriority
layer = _.findLast @layerAdapters, (layer, name) ->
layer.layerPriority <= child.layerPriority
layer ?= @layerAdapters['Land'] if child.layerPriority < -40
layer ? @layerAdapters['Default']
addLank: (lank, id=null, layer=null) ->
id ?= lank.thang.id
console.error 'Lank collision! Already have:', id if @lanks[id]
@lanks[id] = lank
@lankArray.push lank
layer ?= @layerAdapters['Obstacle'] if lank.thang?.spriteName.search(/(dungeon|indoor|ice|classroom|vr).wall/i) isnt -1
layer ?= @layerForChild lank.sprite, lank
layer.addLank lank
layer.updateLayerOrder()
lank
createMarks: ->
@targetMark = new Mark name: 'target', camera: @camera, layer: @layerAdapters['Ground'], thangType: 'target'
@selectionMark = new Mark name: 'selection', camera: @camera, layer: @layerAdapters['Ground'], thangType: 'selection'
createLankOptions: (options) ->
_.extend options, {
@camera
resolutionFactor: SPRITE_RESOLUTION_FACTOR
groundLayer: @layerAdapters['Ground']
textLayer: @surfaceTextLayer
floatingLayer: @layerAdapters['Floating']
showInvisible: @options.showInvisible
@gameUIState
@handleEvents
}
onSetDebug: (e) ->
return if e.debug is @debug
@debug = e.debug
lank.setDebug @debug for lank in @lankArray
onHighlightSprites: (e) ->
highlightedIDs = e.thangIDs or []
for thangID, lank of @lanks
lank.setHighlight? thangID in highlightedIDs, e.delay
addThangToLanks: (thang, layer=null) ->
return console.warn 'Tried to add Thang to the surface it already has:', thang.id if @lanks[thang.id]
thangType = _.find @options.thangTypes, (m) ->
return false unless m.get('actions') or m.get('raster')
return m.get('name') is thang.spriteName
thangType ?= _.find @options.thangTypes, (m) -> return m.get('name') is thang.spriteName
return console.error "Couldn't find ThangType for", thang unless thangType
options = @createLankOptions thang: thang
options.resolutionFactor = if thangType.get('kind') is 'Floor' then 2 else SPRITE_RESOLUTION_FACTOR
if @options.playerNames and /Hero Placeholder/.test thang.id
options.playerName = @options.playerNames[thang.team]
lank = new Lank thangType, options
@listenTo lank, 'sprite:mouse-up', @onLankMouseUp
@addLank lank, null, layer
lank.setDebug @debug
lank
removeLank: (lank) ->
lank.layer.removeLank(lank)
thang = lank.thang
delete @lanks[lank.thang.id]
@lankArray.splice @lankArray.indexOf(lank), 1
@stopListening lank
lank.destroy()
lank.thang = thang # Keep around so that we know which thang the destroyed thang was for
updateSounds: ->
lank.playSounds() for lank in @lankArray # hmm; doesn't work for lanks which we didn't add yet in adjustLankExistence
update: (frameChanged) ->
@adjustLankExistence() if frameChanged
lank.update frameChanged for lank in @lankArray
@updateSelection()
@layerAdapters['Default'].updateLayerOrder()
@cacheObstacles()
adjustLankExistence: ->
# Add anything new, remove anything old, update everything current
updatedObstacles = []
itemsJustEquipped = []
for thang in @world.thangs when thang.exists and thang.pos
itemsJustEquipped = itemsJustEquipped.concat @equipNewItems thang if thang.equip
if lank = @lanks[thang.id]
lank.setThang thang # make sure Lank has latest Thang
else
lank = @addThangToLanks(thang)
Backbone.Mediator.publish 'surface:new-thang-added', thang: thang, sprite: lank
updatedObstacles.push lank if lank.sprite.parent is @layerAdapters['Obstacle']
lank.playSounds()
item.modifyStats() for item in itemsJustEquipped
for thangID, lank of @lanks
missing = not (lank.notOfThisWorld or @world.thangMap[thangID]?.exists)
isObstacle = lank.sprite.parent is @layerAdapters['Obstacle']
updatedObstacles.push lank if isObstacle and (missing or lank.hasMoved)
lank.hasMoved = false
@removeLank lank if missing
@cacheObstacles updatedObstacles if updatedObstacles.length and @cachedObstacles
# mainly for handling selecting thangs from session when the thang is not always in existence
if @willSelectThang and @lanks[@willSelectThang[0]]
@selectThang @willSelectThang...
@updateScreenReader()
updateScreenReader: ->
# Testing ASCII map for screen readers
return unless me.get('name') is 'zersiax' #in ['zersiax', '<NAME>']
ascii = $('#ascii-surface')
thangs = (lank.thang for lank in @lankArray)
grid = new Grid thangs, @world.width, @world.height, 0, 0, 0, true
utils.replaceText ascii, grid.toString true
ascii.css 'transform', 'initial'
fullWidth = ascii.innerWidth()
fullHeight = ascii.innerHeight()
availableWidth = ascii.parent().innerWidth()
availableHeight = ascii.parent().innerHeight()
scale = availableWidth / fullWidth
scale = Math.min scale, availableHeight / fullHeight
ascii.css 'transform', "scale(#{scale})"
equipNewItems: (thang) ->
itemsJustEquipped = []
if thang.equip and not thang.equipped
thang.equip() # Pretty hacky, but needed since initialize may not be called if we're not running Systems.
itemsJustEquipped.push thang
if thang.inventoryIDs
# Even hackier: these items were only created/equipped during simulation, so we reequip here.
for slot, itemID of thang.inventoryIDs
item = @world.getThangByID itemID
unless item.equipped
console.log thang.id, 'equipping', item, 'in', thang.slot, 'Surface-side, but it cannot equip?' unless item.equip
item.equip?()
itemsJustEquipped.push item if item.equip
return itemsJustEquipped
cacheObstacles: (updatedObstacles=null) ->
return if @cachedObstacles and not updatedObstacles
lankArray = @lankArray
wallLanks = (lank for lank in lankArray when lank.thangType?.get('name').search(/(dungeon|indoor|ice|classroom|vr).wall/i) isnt -1)
return if _.any (s.stillLoading for s in wallLanks)
walls = (lank.thang for lank in wallLanks)
@world.calculateBounds()
wallGrid = new Grid walls, @world.width, @world.height
if updatedObstacles
possiblyUpdatedWallLanks = (lank for lank in wallLanks when _.find updatedObstacles, (w2) -> lank is w2 or (Math.abs(lank.thang.pos.x - w2.thang.pos.x) + Math.abs(lank.thang.pos.y - w2.thang.pos.y)) <= 16)
else
possiblyUpdatedWallLanks = wallLanks
# console.log 'updating up to', possiblyUpdatedWallLanks.length, 'of', wallLanks.length, 'wall lanks from updatedObstacles', updatedObstacles
for wallLank in possiblyUpdatedWallLanks
wallLank.queueAction 'idle' if not wallLank.currentRootAction
wallLank.lockAction(false)
wallLank.updateActionDirection wallGrid
wallLank.lockAction(true)
wallLank.updateScale()
wallLank.updatePosition()
# console.log wallGrid.toString()
@cachedObstacles = true
lankFor: (thangID) -> @lanks[thangID]
onNewWorld: (e) ->
@world = @options.world = e.world
# Clear obstacle cache for this level, since we are spawning walls dynamically
@cachedObstacles = false if e.finished and /kithgard-mastery/.test window.location.href
play: ->
lank.play() for lank in @lankArray
@selectionMark?.play()
@targetMark?.play()
stop: ->
lank.stop() for lank in @lankArray
@selectionMark?.stop()
@targetMark?.stop()
# Selection
onSuppressSelectionSounds: (e) -> @suppressSelectionSounds = e.suppress
onSetLockSelect: (e) -> @selectLocked = e.lock
onLevelRestarted: (e) ->
@selectLocked = false
@selectLank e, null
onSelectSprite: (e) ->
@selectThang e.thangID, e.spellName
onCameraDragged: ->
@dragged += 1
onLankMouseUp: (e) ->
return unless @handleEvents
return if key.shift #and @options.choosing
return @dragged = 0 if @dragged > 3
@dragged = 0
lank = if e.sprite?.thang?.isSelectable then e.sprite else null
return if @flagCursorLank and lank?.thangType.get('name') is 'Flag'
@selectLank e, lank
onStageMouseDown: (e) ->
return unless @handleEvents
return if key.shift #and @options.choosing
@selectLank e if e.onBackground
onChangeSelected: (gameUIState, selected) ->
oldLanks = (s.sprite for s in gameUIState.previousAttributes().selected or [])
newLanks = (s.sprite for s in selected or [])
addedLanks = _.difference(newLanks, oldLanks)
removedLanks = _.difference(oldLanks, newLanks)
for lank in addedLanks
layer = if lank.sprite.parent isnt @layerAdapters.Default.container then @layerAdapters.Default else @layerAdapters.Ground
mark = new Mark name: 'selection', camera: @camera, layer: layer, thangType: 'selection'
mark.toggle true
mark.setLank(lank)
mark.update()
lank.marks.selection = mark # TODO: Figure out how to non-hackily assign lank this mark
for lank in removedLanks
lank.removeMark?('selection')
selectThang: (thangID, spellName=null, treemaThangSelected = null) ->
return @willSelectThang = [thangID, spellName] unless @lanks[thangID]
@selectLank null, @lanks[thangID], spellName, treemaThangSelected
selectLank: (e, lank=null, spellName=null, treemaThangSelected = null) ->
return if e and (@disabled or @selectLocked) # Ignore clicks for selection/panning/wizard movement while disabled or select is locked
worldPos = lank?.thang?.pos
worldPos ?= @camera.screenToWorld {x: e.originalEvent.rawX, y: e.originalEvent.rawY} if e?.originalEvent
if @handleEvents
if (not @reallyStopMoving) and worldPos and (@options.navigateToSelection or not lank or treemaThangSelected) and e?.originalEvent?.nativeEvent?.which isnt 3
@camera.zoomTo(lank?.sprite or @camera.worldToSurface(worldPos), @camera.zoom, 1000, true)
lank = null if @options.choosing # Don't select lanks while choosing
if lank isnt @selectedLank
@selectedLank?.selected = false
lank?.selected = true
@selectedLank = lank
alive = lank and not (lank.thang.health < 0)
Backbone.Mediator.publish 'surface:sprite-selected',
thang: if lank then lank.thang else null
sprite: lank
spellName: spellName ? e?.spellName
originalEvent: e
worldPos: worldPos
@willSelectThang = null if lank # Now that we've done a real selection, don't reselect some other Thang later.
if alive and not @suppressSelectionSounds
instance = lank.playSound 'selected'
if instance?.playState is 'playSucceeded'
Backbone.Mediator.publish 'sprite:thang-began-talking', thang: lank?.thang
instance.addEventListener 'complete', ->
Backbone.Mediator.publish 'sprite:thang-finished-talking', thang: lank?.thang
onFlagColorSelected: (e) ->
@removeLank @flagCursorLank if @flagCursorLank
@flagCursorLank = null
for flagLank in @lankArray when flagLank.thangType.get('name') is 'Flag'
flagLank.sprite.cursor = if e.color then 'crosshair' else 'pointer'
return unless e.color
@flagCursorLank = new FlagLank @thangTypeFor('Flag'), @createLankOptions(thangID: 'Flag Cursor', color: e.color, team: me.team, isCursor: true, pos: e.pos)
@addLank @flagCursorLank, @flagCursorLank.thang.id, @layerAdapters['Floating']
onFlagUpdated: (e) ->
return unless e.active
pendingFlag = new FlagLank @thangTypeFor('Flag'), @createLankOptions(thangID: 'Pending Flag ' + Math.random(), color: e.color, team: e.team, isCursor: false, pos: e.pos)
@addLank pendingFlag, pendingFlag.thang.id, @layerAdapters['Floating']
@pendingFlags.push pendingFlag
onFlagAppeared: (e) ->
# Remove the pending flag that matches this one's color/team/position, and any color/team matches placed earlier.
t1 = e.sprite.thang
pending = (@pendingFlags ? []).slice()
foundExactMatch = false
for i in [pending.length - 1 .. 0] by -1
pendingFlag = pending[i]
t2 = pendingFlag.thang
matchedType = t1.color is t2.color and t1.team is t2.team
matched = matchedType and (foundExactMatch or Math.abs(t1.pos.x - t2.pos.x) < 0.00001 and Math.abs(t1.pos.y - t2.pos.y) < 0.00001)
if matched
foundExactMatch = true
@pendingFlags.splice(i, 1)
@removeLank pendingFlag
e.sprite.sprite?.cursor = if @flagCursorLank then 'crosshair' else 'pointer'
null
onRemoveSelectedFlag: (e) ->
# Remove the selected lank if it's a flag, or any flag of the given color if a color is given.
flagLank = _.find [@selectedLank].concat(@lankArray), (lank) ->
lank and lank.thangType.get('name') is 'Flag' and lank.thang.team is me.team and (lank.thang.color is e.color or not e.color) and not lank.notOfThisWorld
return unless flagLank
Backbone.Mediator.publish 'surface:remove-flag', color: flagLank.thang.color
# Marks
updateSelection: ->
if @selectedLank?.thang and (not @selectedLank.thang.exists or not @world.getThangByID @selectedLank.thang.id)
thangID = @selectedLank.thang.id
@selectedLank = null # Don't actually trigger deselection, but remove the selected lank.
@selectionMark?.toggle false
@willSelectThang = [thangID, null]
@updateTarget()
return unless @selectionMark
@selectedLank = null if @selectedLank and (@selectedLank.destroyed or not @selectedLank.thang)
# The selection mark should be on the ground layer, unless we're not a normal lank (like a wall), in which case we'll place it higher so we can see it.
if @selectedLank and @selectedLank.sprite.parent isnt @layerAdapters.Default.container
@selectionMark.setLayer @layerAdapters.Default
else if @selectedLank
@selectionMark.setLayer @layerAdapters.Ground
@selectionMark.toggle @selectedLank?
@selectionMark.setLank @selectedLank
@selectionMark.update()
updateTarget: ->
return unless @targetMark
thang = @selectedLank?.thang
target = thang?.target
targetPos = thang?.targetPos
targetPos = null if targetPos?.isZero?() # Null targetPos get serialized as (0, 0, 0)
@targetMark.setLank if target then @lanks[target.id] else null
@targetMark.toggle @targetMark.lank or targetPos
@targetMark.update if targetPos then @camera.worldToSurface targetPos else null
| true | CocoClass = require 'core/CocoClass'
{me} = require 'core/auth'
LayerAdapter = require './LayerAdapter'
FlagLank = require 'lib/surface/FlagLank'
Lank = require 'lib/surface/Lank'
Mark = require './Mark'
Grid = require 'lib/world/Grid'
utils = require 'core/utils'
module.exports = class LankBoss extends CocoClass
subscriptions:
'level:set-debug': 'onSetDebug'
'sprite:highlight-sprites': 'onHighlightSprites'
'surface:stage-mouse-down': 'onStageMouseDown'
'level:select-sprite': 'onSelectSprite'
'level:suppress-selection-sounds': 'onSuppressSelectionSounds'
'level:lock-select': 'onSetLockSelect'
'level:restarted': 'onLevelRestarted'
'god:new-world-created': 'onNewWorld'
'god:streaming-world-updated': 'onNewWorld'
'camera:dragged': 'onCameraDragged'
'sprite:loaded': -> @update(true)
'level:flag-color-selected': 'onFlagColorSelected'
'level:flag-updated': 'onFlagUpdated'
'surface:flag-appeared': 'onFlagAppeared'
'surface:remove-selected-flag': 'onRemoveSelectedFlag'
constructor: (@options={}) ->
super()
@handleEvents = @options.handleEvents
@gameUIState = @options.gameUIState
@dragged = 0
@camera = @options.camera
@webGLStage = @options.webGLStage
@surfaceTextLayer = @options.surfaceTextLayer
@world = @options.world
@options.thangTypes ?= []
@lanks = {}
@lankArray = [] # Mirror @lanks, but faster for when we just need to iterate
@createLayers()
@pendingFlags = []
if not @handleEvents
@listenTo @gameUIState, 'change:selected', @onChangeSelected
destroy: ->
@removeLank lank for thangID, lank of @lanks
@targetMark?.destroy()
@selectionMark?.destroy()
lankLayer.destroy() for lankLayer in _.values @layerAdapters
super()
toString: -> "<LankBoss: #{@lankArray.length} lanks>"
thangTypeFor: (type) ->
_.find @options.thangTypes, (m) -> m.get('original') is type or m.get('name') is type
createLayers: ->
@layerAdapters = {}
for [name, priority] in [
['Land', -40]
['Ground', -30]
['Obstacle', -20]
['Path', -10]
['Default', 0]
['Floating', 10]
]
@layerAdapters[name] = new LayerAdapter name: name, webGL: true, layerPriority: priority, transform: LayerAdapter.TRANSFORM_SURFACE, camera: @camera
@webGLStage.addChild (lankLayer.container for lankLayer in _.values(@layerAdapters))...
layerForChild: (child, lank) ->
unless child.layerPriority?
if thang = lank?.thang
child.layerPriority = thang.layerPriority
child.layerPriority ?= 0 if thang.isSelectable
child.layerPriority ?= -40 if thang.isLand
child.layerPriority ?= 0
return @layerAdapters['Default'] unless child.layerPriority
layer = _.findLast @layerAdapters, (layer, name) ->
layer.layerPriority <= child.layerPriority
layer ?= @layerAdapters['Land'] if child.layerPriority < -40
layer ? @layerAdapters['Default']
addLank: (lank, id=null, layer=null) ->
id ?= lank.thang.id
console.error 'Lank collision! Already have:', id if @lanks[id]
@lanks[id] = lank
@lankArray.push lank
layer ?= @layerAdapters['Obstacle'] if lank.thang?.spriteName.search(/(dungeon|indoor|ice|classroom|vr).wall/i) isnt -1
layer ?= @layerForChild lank.sprite, lank
layer.addLank lank
layer.updateLayerOrder()
lank
createMarks: ->
@targetMark = new Mark name: 'target', camera: @camera, layer: @layerAdapters['Ground'], thangType: 'target'
@selectionMark = new Mark name: 'selection', camera: @camera, layer: @layerAdapters['Ground'], thangType: 'selection'
createLankOptions: (options) ->
_.extend options, {
@camera
resolutionFactor: SPRITE_RESOLUTION_FACTOR
groundLayer: @layerAdapters['Ground']
textLayer: @surfaceTextLayer
floatingLayer: @layerAdapters['Floating']
showInvisible: @options.showInvisible
@gameUIState
@handleEvents
}
onSetDebug: (e) ->
return if e.debug is @debug
@debug = e.debug
lank.setDebug @debug for lank in @lankArray
onHighlightSprites: (e) ->
highlightedIDs = e.thangIDs or []
for thangID, lank of @lanks
lank.setHighlight? thangID in highlightedIDs, e.delay
addThangToLanks: (thang, layer=null) ->
return console.warn 'Tried to add Thang to the surface it already has:', thang.id if @lanks[thang.id]
thangType = _.find @options.thangTypes, (m) ->
return false unless m.get('actions') or m.get('raster')
return m.get('name') is thang.spriteName
thangType ?= _.find @options.thangTypes, (m) -> return m.get('name') is thang.spriteName
return console.error "Couldn't find ThangType for", thang unless thangType
options = @createLankOptions thang: thang
options.resolutionFactor = if thangType.get('kind') is 'Floor' then 2 else SPRITE_RESOLUTION_FACTOR
if @options.playerNames and /Hero Placeholder/.test thang.id
options.playerName = @options.playerNames[thang.team]
lank = new Lank thangType, options
@listenTo lank, 'sprite:mouse-up', @onLankMouseUp
@addLank lank, null, layer
lank.setDebug @debug
lank
removeLank: (lank) ->
lank.layer.removeLank(lank)
thang = lank.thang
delete @lanks[lank.thang.id]
@lankArray.splice @lankArray.indexOf(lank), 1
@stopListening lank
lank.destroy()
lank.thang = thang # Keep around so that we know which thang the destroyed thang was for
updateSounds: ->
lank.playSounds() for lank in @lankArray # hmm; doesn't work for lanks which we didn't add yet in adjustLankExistence
update: (frameChanged) ->
@adjustLankExistence() if frameChanged
lank.update frameChanged for lank in @lankArray
@updateSelection()
@layerAdapters['Default'].updateLayerOrder()
@cacheObstacles()
adjustLankExistence: ->
# Add anything new, remove anything old, update everything current
updatedObstacles = []
itemsJustEquipped = []
for thang in @world.thangs when thang.exists and thang.pos
itemsJustEquipped = itemsJustEquipped.concat @equipNewItems thang if thang.equip
if lank = @lanks[thang.id]
lank.setThang thang # make sure Lank has latest Thang
else
lank = @addThangToLanks(thang)
Backbone.Mediator.publish 'surface:new-thang-added', thang: thang, sprite: lank
updatedObstacles.push lank if lank.sprite.parent is @layerAdapters['Obstacle']
lank.playSounds()
item.modifyStats() for item in itemsJustEquipped
for thangID, lank of @lanks
missing = not (lank.notOfThisWorld or @world.thangMap[thangID]?.exists)
isObstacle = lank.sprite.parent is @layerAdapters['Obstacle']
updatedObstacles.push lank if isObstacle and (missing or lank.hasMoved)
lank.hasMoved = false
@removeLank lank if missing
@cacheObstacles updatedObstacles if updatedObstacles.length and @cachedObstacles
# mainly for handling selecting thangs from session when the thang is not always in existence
if @willSelectThang and @lanks[@willSelectThang[0]]
@selectThang @willSelectThang...
@updateScreenReader()
updateScreenReader: ->
# Testing ASCII map for screen readers
return unless me.get('name') is 'zersiax' #in ['zersiax', 'PI:NAME:<NAME>END_PI']
ascii = $('#ascii-surface')
thangs = (lank.thang for lank in @lankArray)
grid = new Grid thangs, @world.width, @world.height, 0, 0, 0, true
utils.replaceText ascii, grid.toString true
ascii.css 'transform', 'initial'
fullWidth = ascii.innerWidth()
fullHeight = ascii.innerHeight()
availableWidth = ascii.parent().innerWidth()
availableHeight = ascii.parent().innerHeight()
scale = availableWidth / fullWidth
scale = Math.min scale, availableHeight / fullHeight
ascii.css 'transform', "scale(#{scale})"
equipNewItems: (thang) ->
itemsJustEquipped = []
if thang.equip and not thang.equipped
thang.equip() # Pretty hacky, but needed since initialize may not be called if we're not running Systems.
itemsJustEquipped.push thang
if thang.inventoryIDs
# Even hackier: these items were only created/equipped during simulation, so we reequip here.
for slot, itemID of thang.inventoryIDs
item = @world.getThangByID itemID
unless item.equipped
console.log thang.id, 'equipping', item, 'in', thang.slot, 'Surface-side, but it cannot equip?' unless item.equip
item.equip?()
itemsJustEquipped.push item if item.equip
return itemsJustEquipped
cacheObstacles: (updatedObstacles=null) ->
return if @cachedObstacles and not updatedObstacles
lankArray = @lankArray
wallLanks = (lank for lank in lankArray when lank.thangType?.get('name').search(/(dungeon|indoor|ice|classroom|vr).wall/i) isnt -1)
return if _.any (s.stillLoading for s in wallLanks)
walls = (lank.thang for lank in wallLanks)
@world.calculateBounds()
wallGrid = new Grid walls, @world.width, @world.height
if updatedObstacles
possiblyUpdatedWallLanks = (lank for lank in wallLanks when _.find updatedObstacles, (w2) -> lank is w2 or (Math.abs(lank.thang.pos.x - w2.thang.pos.x) + Math.abs(lank.thang.pos.y - w2.thang.pos.y)) <= 16)
else
possiblyUpdatedWallLanks = wallLanks
# console.log 'updating up to', possiblyUpdatedWallLanks.length, 'of', wallLanks.length, 'wall lanks from updatedObstacles', updatedObstacles
for wallLank in possiblyUpdatedWallLanks
wallLank.queueAction 'idle' if not wallLank.currentRootAction
wallLank.lockAction(false)
wallLank.updateActionDirection wallGrid
wallLank.lockAction(true)
wallLank.updateScale()
wallLank.updatePosition()
# console.log wallGrid.toString()
@cachedObstacles = true
lankFor: (thangID) -> @lanks[thangID]
onNewWorld: (e) ->
@world = @options.world = e.world
# Clear obstacle cache for this level, since we are spawning walls dynamically
@cachedObstacles = false if e.finished and /kithgard-mastery/.test window.location.href
play: ->
lank.play() for lank in @lankArray
@selectionMark?.play()
@targetMark?.play()
stop: ->
lank.stop() for lank in @lankArray
@selectionMark?.stop()
@targetMark?.stop()
# Selection
onSuppressSelectionSounds: (e) -> @suppressSelectionSounds = e.suppress
onSetLockSelect: (e) -> @selectLocked = e.lock
onLevelRestarted: (e) ->
@selectLocked = false
@selectLank e, null
onSelectSprite: (e) ->
@selectThang e.thangID, e.spellName
onCameraDragged: ->
@dragged += 1
onLankMouseUp: (e) ->
return unless @handleEvents
return if key.shift #and @options.choosing
return @dragged = 0 if @dragged > 3
@dragged = 0
lank = if e.sprite?.thang?.isSelectable then e.sprite else null
return if @flagCursorLank and lank?.thangType.get('name') is 'Flag'
@selectLank e, lank
onStageMouseDown: (e) ->
return unless @handleEvents
return if key.shift #and @options.choosing
@selectLank e if e.onBackground
onChangeSelected: (gameUIState, selected) ->
oldLanks = (s.sprite for s in gameUIState.previousAttributes().selected or [])
newLanks = (s.sprite for s in selected or [])
addedLanks = _.difference(newLanks, oldLanks)
removedLanks = _.difference(oldLanks, newLanks)
for lank in addedLanks
layer = if lank.sprite.parent isnt @layerAdapters.Default.container then @layerAdapters.Default else @layerAdapters.Ground
mark = new Mark name: 'selection', camera: @camera, layer: layer, thangType: 'selection'
mark.toggle true
mark.setLank(lank)
mark.update()
lank.marks.selection = mark # TODO: Figure out how to non-hackily assign lank this mark
for lank in removedLanks
lank.removeMark?('selection')
selectThang: (thangID, spellName=null, treemaThangSelected = null) ->
return @willSelectThang = [thangID, spellName] unless @lanks[thangID]
@selectLank null, @lanks[thangID], spellName, treemaThangSelected
selectLank: (e, lank=null, spellName=null, treemaThangSelected = null) ->
return if e and (@disabled or @selectLocked) # Ignore clicks for selection/panning/wizard movement while disabled or select is locked
worldPos = lank?.thang?.pos
worldPos ?= @camera.screenToWorld {x: e.originalEvent.rawX, y: e.originalEvent.rawY} if e?.originalEvent
if @handleEvents
if (not @reallyStopMoving) and worldPos and (@options.navigateToSelection or not lank or treemaThangSelected) and e?.originalEvent?.nativeEvent?.which isnt 3
@camera.zoomTo(lank?.sprite or @camera.worldToSurface(worldPos), @camera.zoom, 1000, true)
lank = null if @options.choosing # Don't select lanks while choosing
if lank isnt @selectedLank
@selectedLank?.selected = false
lank?.selected = true
@selectedLank = lank
alive = lank and not (lank.thang.health < 0)
Backbone.Mediator.publish 'surface:sprite-selected',
thang: if lank then lank.thang else null
sprite: lank
spellName: spellName ? e?.spellName
originalEvent: e
worldPos: worldPos
@willSelectThang = null if lank # Now that we've done a real selection, don't reselect some other Thang later.
if alive and not @suppressSelectionSounds
instance = lank.playSound 'selected'
if instance?.playState is 'playSucceeded'
Backbone.Mediator.publish 'sprite:thang-began-talking', thang: lank?.thang
instance.addEventListener 'complete', ->
Backbone.Mediator.publish 'sprite:thang-finished-talking', thang: lank?.thang
onFlagColorSelected: (e) ->
@removeLank @flagCursorLank if @flagCursorLank
@flagCursorLank = null
for flagLank in @lankArray when flagLank.thangType.get('name') is 'Flag'
flagLank.sprite.cursor = if e.color then 'crosshair' else 'pointer'
return unless e.color
@flagCursorLank = new FlagLank @thangTypeFor('Flag'), @createLankOptions(thangID: 'Flag Cursor', color: e.color, team: me.team, isCursor: true, pos: e.pos)
@addLank @flagCursorLank, @flagCursorLank.thang.id, @layerAdapters['Floating']
onFlagUpdated: (e) ->
return unless e.active
pendingFlag = new FlagLank @thangTypeFor('Flag'), @createLankOptions(thangID: 'Pending Flag ' + Math.random(), color: e.color, team: e.team, isCursor: false, pos: e.pos)
@addLank pendingFlag, pendingFlag.thang.id, @layerAdapters['Floating']
@pendingFlags.push pendingFlag
onFlagAppeared: (e) ->
# Remove the pending flag that matches this one's color/team/position, and any color/team matches placed earlier.
t1 = e.sprite.thang
pending = (@pendingFlags ? []).slice()
foundExactMatch = false
for i in [pending.length - 1 .. 0] by -1
pendingFlag = pending[i]
t2 = pendingFlag.thang
matchedType = t1.color is t2.color and t1.team is t2.team
matched = matchedType and (foundExactMatch or Math.abs(t1.pos.x - t2.pos.x) < 0.00001 and Math.abs(t1.pos.y - t2.pos.y) < 0.00001)
if matched
foundExactMatch = true
@pendingFlags.splice(i, 1)
@removeLank pendingFlag
e.sprite.sprite?.cursor = if @flagCursorLank then 'crosshair' else 'pointer'
null
onRemoveSelectedFlag: (e) ->
# Remove the selected lank if it's a flag, or any flag of the given color if a color is given.
flagLank = _.find [@selectedLank].concat(@lankArray), (lank) ->
lank and lank.thangType.get('name') is 'Flag' and lank.thang.team is me.team and (lank.thang.color is e.color or not e.color) and not lank.notOfThisWorld
return unless flagLank
Backbone.Mediator.publish 'surface:remove-flag', color: flagLank.thang.color
# Marks
updateSelection: ->
if @selectedLank?.thang and (not @selectedLank.thang.exists or not @world.getThangByID @selectedLank.thang.id)
thangID = @selectedLank.thang.id
@selectedLank = null # Don't actually trigger deselection, but remove the selected lank.
@selectionMark?.toggle false
@willSelectThang = [thangID, null]
@updateTarget()
return unless @selectionMark
@selectedLank = null if @selectedLank and (@selectedLank.destroyed or not @selectedLank.thang)
# The selection mark should be on the ground layer, unless we're not a normal lank (like a wall), in which case we'll place it higher so we can see it.
if @selectedLank and @selectedLank.sprite.parent isnt @layerAdapters.Default.container
@selectionMark.setLayer @layerAdapters.Default
else if @selectedLank
@selectionMark.setLayer @layerAdapters.Ground
@selectionMark.toggle @selectedLank?
@selectionMark.setLank @selectedLank
@selectionMark.update()
updateTarget: ->
return unless @targetMark
thang = @selectedLank?.thang
target = thang?.target
targetPos = thang?.targetPos
targetPos = null if targetPos?.isZero?() # Null targetPos get serialized as (0, 0, 0)
@targetMark.setLank if target then @lanks[target.id] else null
@targetMark.toggle @targetMark.lank or targetPos
@targetMark.update if targetPos then @camera.worldToSurface targetPos else null
|
[
{
"context": "omma styles of two types: last and first\n# @author Vignesh Anand aka vegetableman\n###\n\n'use strict'\n\nastUtils = re",
"end": 109,
"score": 0.9998873472213745,
"start": 96,
"tag": "NAME",
"value": "Vignesh Anand"
},
{
"context": " types: last and first\n# @author Vignesh Anand aka vegetableman\n###\n\n'use strict'\n\nastUtils = require '../eslint-",
"end": 126,
"score": 0.9995954632759094,
"start": 114,
"tag": "USERNAME",
"value": "vegetableman"
}
] | src/rules/comma-style.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Comma style - enforces comma styles of two types: last and first
# @author Vignesh Anand aka vegetableman
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce consistent comma style'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/comma-style'
# fixable: 'code'
schema: [
enum: ['first', 'last']
,
type: 'object'
properties:
exceptions:
type: 'object'
additionalProperties:
type: 'boolean'
additionalProperties: no
]
messages:
unexpectedLineBeforeAndAfterComma:
"Bad line breaking before and after ','."
expectedCommaFirst: "',' should be placed first."
expectedCommaLast: "',' should be placed last."
create: (context) ->
style = context.options[0] or 'last'
sourceCode = context.getSourceCode()
exceptions =
ArrayPattern: yes
ArrowFunctionExpression: yes
CallExpression: yes
FunctionDeclaration: yes
FunctionExpression: yes
ImportDeclaration: yes
ObjectPattern: yes
NewExpression: yes
if (
context.options.length is 2 and
Object::hasOwnProperty.call context.options[1], 'exceptions'
)
for own key, exception of context.options[1].exceptions
exceptions[key] = exception
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
# ###*
# # Modified text based on the style
# # @param {string} styleType Style type
# # @param {string} text Source code text
# # @returns {string} modified text
# # @private
# ###
# getReplacedText = (styleType, text) ->
# switch styleType
# when 'between'
# return ",#{text.replace '\n', ''}"
# when 'first'
# return "#{text},"
# when 'last'
# return ",#{text}"
# else
# return ''
# ###*
# # Determines the fixer function for a given style.
# # @param {string} styleType comma style
# # @param {ASTNode} previousItemToken The token to check.
# # @param {ASTNode} commaToken The token to check.
# # @param {ASTNode} currentItemToken The token to check.
# # @returns {Function} Fixer function
# # @private
# ###
# getFixerFunction = (
# styleType
# previousItemToken
# commaToken
# currentItemToken
# ) ->
# text =
# sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
# sourceCode.text.slice commaToken.range[1], currentItemToken.range[0]
# range = [previousItemToken.range[1], currentItemToken.range[0]]
# (fixer) -> fixer.replaceTextRange range, getReplacedText styleType, text
###*
# Validates the spacing around single items in lists.
# @param {Token} previousItemToken The last token from the previous item.
# @param {Token} commaToken The token representing the comma.
# @param {Token} currentItemToken The first token of the current item.
# @param {Token} reportItem The item to use when reporting an error.
# @returns {void}
# @private
###
validateCommaItemSpacing = (
previousItemToken
commaToken
currentItemToken
reportItem
) ->
# if single line
if (
astUtils.isTokenOnSameLine(commaToken, currentItemToken) and
astUtils.isTokenOnSameLine previousItemToken, commaToken
)
# do nothing.
else if (
not astUtils.isTokenOnSameLine(commaToken, currentItemToken) and
not astUtils.isTokenOnSameLine previousItemToken, commaToken
)
# lone comma
context.report
node: reportItem
loc:
line: commaToken.loc.end.line
column: commaToken.loc.start.column
messageId: 'unexpectedLineBeforeAndAfterComma'
# fix: getFixerFunction(
# 'between'
# previousItemToken
# commaToken
# currentItemToken
# )
else if (
style is 'first' and
not astUtils.isTokenOnSameLine commaToken, currentItemToken
)
context.report
node: reportItem
messageId: 'expectedCommaFirst'
# fix: getFixerFunction(
# style
# previousItemToken
# commaToken
# currentItemToken
# )
else if (
style is 'last' and
astUtils.isTokenOnSameLine commaToken, currentItemToken
)
context.report
node: reportItem
loc:
line: commaToken.loc.end.line
column: commaToken.loc.end.column
messageId: 'expectedCommaLast'
# fix: getFixerFunction(
# style
# previousItemToken
# commaToken
# currentItemToken
# )
###*
# Checks the comma placement with regards to a declaration/property/element
# @param {ASTNode} node The binary expression node to check
# @param {string} property The property of the node containing child nodes.
# @private
# @returns {void}
###
validateComma = (node, property) ->
items = node[property]
arrayLiteral = node.type in ['ArrayExpression', 'ArrayPattern']
if items.length > 1 or arrayLiteral
# seed as opening [
previousItemToken = sourceCode.getFirstToken node
items.forEach (item, index) ->
commaToken =
if item and index > 0
sourceCode.getTokenBefore item
else
previousItemToken
currentItemToken =
if item
sourceCode.getFirstToken item
else
sourceCode.getTokenAfter commaToken
reportItem = item or currentItemToken
###
# This works by comparing three token locations:
# - previousItemToken is the last token of the previous item
# - commaToken is the location of the comma before the current item
# - currentItemToken is the first token of the current item
#
# These values get switched around if item is undefined.
# previousItemToken will refer to the last token not belonging
# to the current item, which could be a comma or an opening
# square bracket. currentItemToken could be a comma.
#
# All comparisons are done based on these tokens directly, so
# they are always valid regardless of an undefined item.
###
if commaToken? and astUtils.isCommaToken commaToken
validateCommaItemSpacing(
previousItemToken
commaToken
currentItemToken
reportItem
)
if item
tokenAfterItem = sourceCode.getTokenAfter(
item
astUtils.isNotClosingParenToken
)
previousItemToken ###:### =
if tokenAfterItem
sourceCode.getTokenBefore tokenAfterItem
else
sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1]
###
# Special case for array literals that have empty last items, such
# as [ 1, 2, ]. These arrays only have two items show up in the
# AST, so we need to look at the token to verify that there's no
# dangling comma.
###
if arrayLiteral
lastToken = sourceCode.getLastToken node
nextToLastToken = sourceCode.getTokenBefore lastToken
if astUtils.isCommaToken nextToLastToken
validateCommaItemSpacing(
sourceCode.getTokenBefore nextToLastToken
nextToLastToken
lastToken
lastToken
)
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
nodes = {}
unless exceptions.VariableDeclaration
nodes.VariableDeclaration = (node) -> validateComma node, 'declarations'
unless exceptions.ObjectExpression
nodes.ObjectExpression = (node) -> validateComma node, 'properties'
unless exceptions.ObjectPattern
nodes.ObjectPattern = (node) -> validateComma node, 'properties'
unless exceptions.ArrayExpression
nodes.ArrayExpression = (node) -> validateComma node, 'elements'
unless exceptions.ArrayPattern
nodes.ArrayPattern = (node) -> validateComma node, 'elements'
unless exceptions.FunctionDeclaration
nodes.FunctionDeclaration = (node) -> validateComma node, 'params'
unless exceptions.FunctionExpression
nodes.FunctionExpression = (node) -> validateComma node, 'params'
unless exceptions.ArrowFunctionExpression
nodes.ArrowFunctionExpression = (node) -> validateComma node, 'params'
unless exceptions.CallExpression
nodes.CallExpression = (node) -> validateComma node, 'arguments'
unless exceptions.ImportDeclaration
nodes.ImportDeclaration = (node) -> validateComma node, 'specifiers'
unless exceptions.NewExpression
nodes.NewExpression = (node) -> validateComma node, 'arguments'
nodes
| 85746 | ###*
# @fileoverview Comma style - enforces comma styles of two types: last and first
# @author <NAME> aka vegetableman
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce consistent comma style'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/comma-style'
# fixable: 'code'
schema: [
enum: ['first', 'last']
,
type: 'object'
properties:
exceptions:
type: 'object'
additionalProperties:
type: 'boolean'
additionalProperties: no
]
messages:
unexpectedLineBeforeAndAfterComma:
"Bad line breaking before and after ','."
expectedCommaFirst: "',' should be placed first."
expectedCommaLast: "',' should be placed last."
create: (context) ->
style = context.options[0] or 'last'
sourceCode = context.getSourceCode()
exceptions =
ArrayPattern: yes
ArrowFunctionExpression: yes
CallExpression: yes
FunctionDeclaration: yes
FunctionExpression: yes
ImportDeclaration: yes
ObjectPattern: yes
NewExpression: yes
if (
context.options.length is 2 and
Object::hasOwnProperty.call context.options[1], 'exceptions'
)
for own key, exception of context.options[1].exceptions
exceptions[key] = exception
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
# ###*
# # Modified text based on the style
# # @param {string} styleType Style type
# # @param {string} text Source code text
# # @returns {string} modified text
# # @private
# ###
# getReplacedText = (styleType, text) ->
# switch styleType
# when 'between'
# return ",#{text.replace '\n', ''}"
# when 'first'
# return "#{text},"
# when 'last'
# return ",#{text}"
# else
# return ''
# ###*
# # Determines the fixer function for a given style.
# # @param {string} styleType comma style
# # @param {ASTNode} previousItemToken The token to check.
# # @param {ASTNode} commaToken The token to check.
# # @param {ASTNode} currentItemToken The token to check.
# # @returns {Function} Fixer function
# # @private
# ###
# getFixerFunction = (
# styleType
# previousItemToken
# commaToken
# currentItemToken
# ) ->
# text =
# sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
# sourceCode.text.slice commaToken.range[1], currentItemToken.range[0]
# range = [previousItemToken.range[1], currentItemToken.range[0]]
# (fixer) -> fixer.replaceTextRange range, getReplacedText styleType, text
###*
# Validates the spacing around single items in lists.
# @param {Token} previousItemToken The last token from the previous item.
# @param {Token} commaToken The token representing the comma.
# @param {Token} currentItemToken The first token of the current item.
# @param {Token} reportItem The item to use when reporting an error.
# @returns {void}
# @private
###
validateCommaItemSpacing = (
previousItemToken
commaToken
currentItemToken
reportItem
) ->
# if single line
if (
astUtils.isTokenOnSameLine(commaToken, currentItemToken) and
astUtils.isTokenOnSameLine previousItemToken, commaToken
)
# do nothing.
else if (
not astUtils.isTokenOnSameLine(commaToken, currentItemToken) and
not astUtils.isTokenOnSameLine previousItemToken, commaToken
)
# lone comma
context.report
node: reportItem
loc:
line: commaToken.loc.end.line
column: commaToken.loc.start.column
messageId: 'unexpectedLineBeforeAndAfterComma'
# fix: getFixerFunction(
# 'between'
# previousItemToken
# commaToken
# currentItemToken
# )
else if (
style is 'first' and
not astUtils.isTokenOnSameLine commaToken, currentItemToken
)
context.report
node: reportItem
messageId: 'expectedCommaFirst'
# fix: getFixerFunction(
# style
# previousItemToken
# commaToken
# currentItemToken
# )
else if (
style is 'last' and
astUtils.isTokenOnSameLine commaToken, currentItemToken
)
context.report
node: reportItem
loc:
line: commaToken.loc.end.line
column: commaToken.loc.end.column
messageId: 'expectedCommaLast'
# fix: getFixerFunction(
# style
# previousItemToken
# commaToken
# currentItemToken
# )
###*
# Checks the comma placement with regards to a declaration/property/element
# @param {ASTNode} node The binary expression node to check
# @param {string} property The property of the node containing child nodes.
# @private
# @returns {void}
###
validateComma = (node, property) ->
items = node[property]
arrayLiteral = node.type in ['ArrayExpression', 'ArrayPattern']
if items.length > 1 or arrayLiteral
# seed as opening [
previousItemToken = sourceCode.getFirstToken node
items.forEach (item, index) ->
commaToken =
if item and index > 0
sourceCode.getTokenBefore item
else
previousItemToken
currentItemToken =
if item
sourceCode.getFirstToken item
else
sourceCode.getTokenAfter commaToken
reportItem = item or currentItemToken
###
# This works by comparing three token locations:
# - previousItemToken is the last token of the previous item
# - commaToken is the location of the comma before the current item
# - currentItemToken is the first token of the current item
#
# These values get switched around if item is undefined.
# previousItemToken will refer to the last token not belonging
# to the current item, which could be a comma or an opening
# square bracket. currentItemToken could be a comma.
#
# All comparisons are done based on these tokens directly, so
# they are always valid regardless of an undefined item.
###
if commaToken? and astUtils.isCommaToken commaToken
validateCommaItemSpacing(
previousItemToken
commaToken
currentItemToken
reportItem
)
if item
tokenAfterItem = sourceCode.getTokenAfter(
item
astUtils.isNotClosingParenToken
)
previousItemToken ###:### =
if tokenAfterItem
sourceCode.getTokenBefore tokenAfterItem
else
sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1]
###
# Special case for array literals that have empty last items, such
# as [ 1, 2, ]. These arrays only have two items show up in the
# AST, so we need to look at the token to verify that there's no
# dangling comma.
###
if arrayLiteral
lastToken = sourceCode.getLastToken node
nextToLastToken = sourceCode.getTokenBefore lastToken
if astUtils.isCommaToken nextToLastToken
validateCommaItemSpacing(
sourceCode.getTokenBefore nextToLastToken
nextToLastToken
lastToken
lastToken
)
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
nodes = {}
unless exceptions.VariableDeclaration
nodes.VariableDeclaration = (node) -> validateComma node, 'declarations'
unless exceptions.ObjectExpression
nodes.ObjectExpression = (node) -> validateComma node, 'properties'
unless exceptions.ObjectPattern
nodes.ObjectPattern = (node) -> validateComma node, 'properties'
unless exceptions.ArrayExpression
nodes.ArrayExpression = (node) -> validateComma node, 'elements'
unless exceptions.ArrayPattern
nodes.ArrayPattern = (node) -> validateComma node, 'elements'
unless exceptions.FunctionDeclaration
nodes.FunctionDeclaration = (node) -> validateComma node, 'params'
unless exceptions.FunctionExpression
nodes.FunctionExpression = (node) -> validateComma node, 'params'
unless exceptions.ArrowFunctionExpression
nodes.ArrowFunctionExpression = (node) -> validateComma node, 'params'
unless exceptions.CallExpression
nodes.CallExpression = (node) -> validateComma node, 'arguments'
unless exceptions.ImportDeclaration
nodes.ImportDeclaration = (node) -> validateComma node, 'specifiers'
unless exceptions.NewExpression
nodes.NewExpression = (node) -> validateComma node, 'arguments'
nodes
| true | ###*
# @fileoverview Comma style - enforces comma styles of two types: last and first
# @author PI:NAME:<NAME>END_PI aka vegetableman
###
'use strict'
astUtils = require '../eslint-ast-utils'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'enforce consistent comma style'
category: 'Stylistic Issues'
recommended: no
url: 'https://eslint.org/docs/rules/comma-style'
# fixable: 'code'
schema: [
enum: ['first', 'last']
,
type: 'object'
properties:
exceptions:
type: 'object'
additionalProperties:
type: 'boolean'
additionalProperties: no
]
messages:
unexpectedLineBeforeAndAfterComma:
"Bad line breaking before and after ','."
expectedCommaFirst: "',' should be placed first."
expectedCommaLast: "',' should be placed last."
create: (context) ->
style = context.options[0] or 'last'
sourceCode = context.getSourceCode()
exceptions =
ArrayPattern: yes
ArrowFunctionExpression: yes
CallExpression: yes
FunctionDeclaration: yes
FunctionExpression: yes
ImportDeclaration: yes
ObjectPattern: yes
NewExpression: yes
if (
context.options.length is 2 and
Object::hasOwnProperty.call context.options[1], 'exceptions'
)
for own key, exception of context.options[1].exceptions
exceptions[key] = exception
#--------------------------------------------------------------------------
# Helpers
#--------------------------------------------------------------------------
# ###*
# # Modified text based on the style
# # @param {string} styleType Style type
# # @param {string} text Source code text
# # @returns {string} modified text
# # @private
# ###
# getReplacedText = (styleType, text) ->
# switch styleType
# when 'between'
# return ",#{text.replace '\n', ''}"
# when 'first'
# return "#{text},"
# when 'last'
# return ",#{text}"
# else
# return ''
# ###*
# # Determines the fixer function for a given style.
# # @param {string} styleType comma style
# # @param {ASTNode} previousItemToken The token to check.
# # @param {ASTNode} commaToken The token to check.
# # @param {ASTNode} currentItemToken The token to check.
# # @returns {Function} Fixer function
# # @private
# ###
# getFixerFunction = (
# styleType
# previousItemToken
# commaToken
# currentItemToken
# ) ->
# text =
# sourceCode.text.slice(previousItemToken.range[1], commaToken.range[0]) +
# sourceCode.text.slice commaToken.range[1], currentItemToken.range[0]
# range = [previousItemToken.range[1], currentItemToken.range[0]]
# (fixer) -> fixer.replaceTextRange range, getReplacedText styleType, text
###*
# Validates the spacing around single items in lists.
# @param {Token} previousItemToken The last token from the previous item.
# @param {Token} commaToken The token representing the comma.
# @param {Token} currentItemToken The first token of the current item.
# @param {Token} reportItem The item to use when reporting an error.
# @returns {void}
# @private
###
validateCommaItemSpacing = (
previousItemToken
commaToken
currentItemToken
reportItem
) ->
# if single line
if (
astUtils.isTokenOnSameLine(commaToken, currentItemToken) and
astUtils.isTokenOnSameLine previousItemToken, commaToken
)
# do nothing.
else if (
not astUtils.isTokenOnSameLine(commaToken, currentItemToken) and
not astUtils.isTokenOnSameLine previousItemToken, commaToken
)
# lone comma
context.report
node: reportItem
loc:
line: commaToken.loc.end.line
column: commaToken.loc.start.column
messageId: 'unexpectedLineBeforeAndAfterComma'
# fix: getFixerFunction(
# 'between'
# previousItemToken
# commaToken
# currentItemToken
# )
else if (
style is 'first' and
not astUtils.isTokenOnSameLine commaToken, currentItemToken
)
context.report
node: reportItem
messageId: 'expectedCommaFirst'
# fix: getFixerFunction(
# style
# previousItemToken
# commaToken
# currentItemToken
# )
else if (
style is 'last' and
astUtils.isTokenOnSameLine commaToken, currentItemToken
)
context.report
node: reportItem
loc:
line: commaToken.loc.end.line
column: commaToken.loc.end.column
messageId: 'expectedCommaLast'
# fix: getFixerFunction(
# style
# previousItemToken
# commaToken
# currentItemToken
# )
###*
# Checks the comma placement with regards to a declaration/property/element
# @param {ASTNode} node The binary expression node to check
# @param {string} property The property of the node containing child nodes.
# @private
# @returns {void}
###
validateComma = (node, property) ->
items = node[property]
arrayLiteral = node.type in ['ArrayExpression', 'ArrayPattern']
if items.length > 1 or arrayLiteral
# seed as opening [
previousItemToken = sourceCode.getFirstToken node
items.forEach (item, index) ->
commaToken =
if item and index > 0
sourceCode.getTokenBefore item
else
previousItemToken
currentItemToken =
if item
sourceCode.getFirstToken item
else
sourceCode.getTokenAfter commaToken
reportItem = item or currentItemToken
###
# This works by comparing three token locations:
# - previousItemToken is the last token of the previous item
# - commaToken is the location of the comma before the current item
# - currentItemToken is the first token of the current item
#
# These values get switched around if item is undefined.
# previousItemToken will refer to the last token not belonging
# to the current item, which could be a comma or an opening
# square bracket. currentItemToken could be a comma.
#
# All comparisons are done based on these tokens directly, so
# they are always valid regardless of an undefined item.
###
if commaToken? and astUtils.isCommaToken commaToken
validateCommaItemSpacing(
previousItemToken
commaToken
currentItemToken
reportItem
)
if item
tokenAfterItem = sourceCode.getTokenAfter(
item
astUtils.isNotClosingParenToken
)
previousItemToken ###:### =
if tokenAfterItem
sourceCode.getTokenBefore tokenAfterItem
else
sourceCode.ast.tokens[sourceCode.ast.tokens.length - 1]
###
# Special case for array literals that have empty last items, such
# as [ 1, 2, ]. These arrays only have two items show up in the
# AST, so we need to look at the token to verify that there's no
# dangling comma.
###
if arrayLiteral
lastToken = sourceCode.getLastToken node
nextToLastToken = sourceCode.getTokenBefore lastToken
if astUtils.isCommaToken nextToLastToken
validateCommaItemSpacing(
sourceCode.getTokenBefore nextToLastToken
nextToLastToken
lastToken
lastToken
)
#--------------------------------------------------------------------------
# Public
#--------------------------------------------------------------------------
nodes = {}
unless exceptions.VariableDeclaration
nodes.VariableDeclaration = (node) -> validateComma node, 'declarations'
unless exceptions.ObjectExpression
nodes.ObjectExpression = (node) -> validateComma node, 'properties'
unless exceptions.ObjectPattern
nodes.ObjectPattern = (node) -> validateComma node, 'properties'
unless exceptions.ArrayExpression
nodes.ArrayExpression = (node) -> validateComma node, 'elements'
unless exceptions.ArrayPattern
nodes.ArrayPattern = (node) -> validateComma node, 'elements'
unless exceptions.FunctionDeclaration
nodes.FunctionDeclaration = (node) -> validateComma node, 'params'
unless exceptions.FunctionExpression
nodes.FunctionExpression = (node) -> validateComma node, 'params'
unless exceptions.ArrowFunctionExpression
nodes.ArrowFunctionExpression = (node) -> validateComma node, 'params'
unless exceptions.CallExpression
nodes.CallExpression = (node) -> validateComma node, 'arguments'
unless exceptions.ImportDeclaration
nodes.ImportDeclaration = (node) -> validateComma node, 'specifiers'
unless exceptions.NewExpression
nodes.NewExpression = (node) -> validateComma node, 'arguments'
nodes
|
[
{
"context": " Product'\n @client.products.save(newProduct(@productType))\n .then (result) =>\n expect(resu",
"end": 2504,
"score": 0.5296551585197449,
"start": 2497,
"tag": "USERNAME",
"value": "product"
},
{
"context": " (done) ->\n @client.productProjections.byId(@testProduct.id).staged(true).fetch()\n .then ({ body: upd",
"end": 2860,
"score": 0.6953631639480591,
"start": 2849,
"tag": "USERNAME",
"value": "testProduct"
},
{
"context": "datedProduct }) =>\n @client.products.byId(@testProduct.id).delete(updatedProduct.version)\n .then ()",
"end": 2970,
"score": 0.6600263118743896,
"start": 2959,
"tag": "USERNAME",
"value": "testProduct"
},
{
"context": "s\n @client.states.create({\n key: 'SdkIntegrationTestInitialState',\n type: 'ProductState',\n }).then",
"end": 9812,
"score": 0.9986887574195862,
"start": 9782,
"tag": "KEY",
"value": "SdkIntegrationTestInitialState"
},
{
"context": ">\n @client.states.create({\n key: 'SdkIntegrationTestSecondState',\n type: 'ProductState',\n }).then",
"end": 10022,
"score": 0.9990697503089905,
"start": 9993,
"tag": "KEY",
"value": "SdkIntegrationTestSecondState"
},
{
"context": "ustomTypePayloads = [\n {\n \"key\": \"price-withKilosPrice\",\n \"name\": {\n \"en\": \"addition",
"end": 12958,
"score": 0.9550204277038574,
"start": 12938,
"tag": "KEY",
"value": "price-withKilosPrice"
},
{
"context": " ]\n },\n {\n \"key\": \"price-withKilosPrice-two\",\n \"name\": {\n \"en\": \"addition",
"end": 13513,
"score": 0.9430056810379028,
"start": 13489,
"tag": "KEY",
"value": "price-withKilosPrice-two"
},
{
"context": "custom fields', (done) ->\n pName = uniqueId('Foo')\n pSlug = uniqueId('foo')\n OLD_PROD =\n",
"end": 17078,
"score": 0.948162853717804,
"start": 17075,
"tag": "NAME",
"value": "Foo"
},
{
"context": " typeId: 'product-type'\n name: {de: pName}\n slug: {de: pSlug}\n descriptio",
"end": 17232,
"score": 0.6617819666862488,
"start": 17231,
"tag": "NAME",
"value": "p"
},
{
"context": " typeId: 'product-type'\n name: {de: pName}\n slug: {de: pSlug}\n descriptio",
"end": 17988,
"score": 0.6683840155601501,
"start": 17987,
"tag": "NAME",
"value": "p"
}
] | src/spec/integration/products-sync.spec.coffee | commercetools/sphere-node-sdk | 13 | debug = require('debug')('spec-integration:products')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient, ProductSync} = require '../../lib/main'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newProductType = ->
name: 'Clothing'
description: 'A sample product type'
newProduct = (pType) ->
name:
en: uniqueId 'product'
slug:
en: uniqueId 'slug'
productType:
id: pType.id
typeId: 'product-type'
masterVariant:
images: [
url: 'http://my.image.url'
dimensions:
w: 100
h: 100
label: 'label'
]
updateUnpublish = (version) ->
version: version
actions: [
{action: "unpublish"}
]
describe 'Integration Products Sync', ->
beforeEach (done) ->
@client = new SphereClient config: Config
@sync = new ProductSync
debug 'Creating a ProductType'
@client.productTypes.save(newProductType())
.then (result) =>
expect(result.statusCode).toBe 201
@productType = result.body
done()
.catch (error) -> done(_.prettify(error))
afterEach (done) ->
debug 'Unpublishing all products'
@client.products.sort('id').where('masterData(published = "true")')
.process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id)
.update(updateUnpublish(product.version))
.then (results) =>
debug "Unpublished #{results.length} products"
debug 'About to delete all products'
@client.products.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} products"
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).delete(product.version)
.then (results) =>
debug "Deleted #{results.length} products"
debug 'About to delete all product types'
@client.productTypes.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} product types"
Promise.all _.map payload.body.results, (productType) =>
@client.productTypes.byId(productType.id).delete(productType.version)
.then () ->
debug "Deleted #{results.length} product types"
done()
.catch (error) -> done(_.prettify(error.body))
, 60000 # 1min
describe 'Image update actions', ->
beforeEach (done) ->
debug 'Creating a Product'
@client.products.save(newProduct(@productType))
.then (result) =>
expect(result.statusCode).toBe 201
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
@testProduct = result.body
done()
.catch (error) ->
done(_.prettify(error))
afterEach (done) ->
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) =>
@client.products.byId(@testProduct.id).delete(updatedProduct.version)
.then () ->
done()
.catch (error) -> done(_.prettify(error))
it 'should update the label of an image', (done) ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].label = 'newLabel'
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) ->
actual = updatedProduct.masterVariant.images[0].label
expected = NEW_PROD.masterVariant.images[0].label
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should update the url of an image', (done) ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].url = 'http://my.new.image.url'
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) ->
actual = updatedProduct.masterVariant.images[0].url
expected = NEW_PROD.masterVariant.images[0].url
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should not update the dimensions of an image', ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].dimensions =
w: 200
h: 200
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
update = ->
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
expect(update).toThrow()
it 'should create and sync product', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {en: pName}
slug: {en: pSlug}
description: {en: 'A foo product'}
metaTitle: {en: 'The Foo'}
metaDescription: {en: 'The Foo product'}
masterVariant:
sku: 'v0'
prices: [
{value: {centAmount: 1000, currencyCode: 'EUR'}, country: 'DE'}
]
variants: [
{
sku: 'v1'
prices: [
{value: {centAmount: 2000, currencyCode: 'USD'}}
]
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
metaTitle: {de: 'The Foo'}
metaDescription: {de: 'The Foo product'}
searchKeywords: {
en: [{text: 'new'}, {text: 'search'}, {text: 'keywords'}]
"fr-BE": [{text: 'bruxelles'}, {text:'liege'}, {text: 'brugge'}]
}
masterVariant:
id: 1
sku: 'v0'
prices: [
{value: {centAmount: 1500, currencyCode: 'EUR'}, country: 'DE'}
{value: {centAmount: 1500, currencyCode: 'EUR'}, country: 'IT'}
]
variants: [
{
id: 2
sku: 'v1'
prices: [
{value: {centAmount: 2000, currencyCode: 'USD'}}
]
},
{
sku: 'v2'
prices: [
{value: {centAmount: 3000, currencyCode: 'EUR'}, country: 'FR'}
]
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.name).toEqual {de: pName}
expect(updated.slug).toEqual {de: pSlug}
expect(updated.description).toEqual {de: 'A foo product'}
expect(updated.metaTitle).toEqual {de: 'The Foo'}
expect(updated.metaDescription).toEqual {de: 'The Foo product'}
expect(updated.masterVariant.prices[0].value.centAmount).toBe 1500
expect(updated.masterVariant.prices[1].value.centAmount).toBe 1500
expect(updated.masterVariant.prices[1].country).toBe 'IT'
expect(updated.searchKeywords.en[0].text).toBe 'new'
expect(updated.searchKeywords['fr-BE'][1].text).toBe 'liege'
expect(updated.variants[0].sku).toBe 'v1'
expect(updated.variants[0].prices[0].value.centAmount).toBe 2000
expect(updated.variants[1].sku).toBe 'v2'
expect(updated.variants[1].prices[0].value.centAmount).toBe 3000
expect(updated.variants[1].prices[0].country).toBe 'FR'
done()
.catch (error) -> done(_.prettify(error))
, 30000 # 30sec
describe 'State update actions', ->
initialStateId = null
secondStateId = null
testProduct = null
cleanupState = (client) ->
# remove states if they exist
states = [
'SdkIntegrationTestInitialState',
'SdkIntegrationTestSecondState'
]
Promise.all(states.map((state) ->
client.states
.where("key=\"#{state}\"")
.fetch()
.then(({ body: { results: [stateToDelete] } }) ->
if stateToDelete
client.states.byId(stateToDelete.id).delete(stateToDelete.version)
)
))
cleanupProduct = (client) ->
if testProduct
return client.productProjections
.byId(testProduct.id)
.staged(true)
.fetch()
.then ({ body: updatedProduct }) ->
testProduct = null
client.products
.byId(updatedProduct.id)
.delete(updatedProduct.version)
Promise.resolve()
beforeEach (done) ->
cleanupProduct(@client)
.then => cleanupState(@client)
.then =>
# setup states
@client.states.create({
key: 'SdkIntegrationTestInitialState',
type: 'ProductState',
}).then(({ body: state }) ->
initialStateId = state.id
)
.then =>
@client.states.create({
key: 'SdkIntegrationTestSecondState',
type: 'ProductState',
}).then(({ body: state }) ->
secondStateId = state.id
)
.then =>
# setup product
@client.products.save(newProduct(@productType))
.then ({ body: { id } }) =>
@client.productProjections.byId(id).staged(true).fetch()
.then ({ body }) ->
testProduct = body
.then -> done()
.catch (error) ->
done(_.prettify(error))
afterEach (done) ->
cleanupProduct(@client)
.then => cleanupState(@client)
.then -> done()
.catch (error) -> done(_.prettify(error))
it 'should add a the initial state to a product', (done) ->
updatedTestProd = _.extend({}, testProduct, {
state: {
typeId: 'state',
id: initialStateId
}
})
diff = @sync.buildActions(updatedTestProd, testProduct)
expect(diff.shouldUpdate()).toEqual(true)
@client.products.byId(updatedTestProd.id).update(diff.getUpdatePayload())
.then(({ body: { state } }) ->
expect(state).toEqual({
typeId: 'state',
id: initialStateId
})
done()
)
.catch (error) -> done(_.prettify(error))
, 10000 # 10sec
it 'should transition the state', (done) ->
# set the initial state
@client.products.byId(testProduct.id).update({
actions: [{
action: 'transitionState',
state: { typeId: 'state', id: initialStateId }
}]
version: testProduct.version
})
.then =>
@client.productProjections.byId(testProduct.id).staged(true).fetch()
.then(({ body: prodWithInitialState }) =>
updatedTestProd = _.extend({}, prodWithInitialState, {
state: {
typeId: 'state',
id: secondStateId
}
})
diff = @sync.buildActions(updatedTestProd, prodWithInitialState)
expect(diff.shouldUpdate()).toEqual(true)
@client.products
.byId(updatedTestProd.id)
.update(diff.getUpdatePayload())
)
.then(({ body: { state } }) ->
expect(state).toEqual({
typeId: 'state',
id: secondStateId
})
done()
)
.catch (error) ->
done(_.prettify(error))
, 10000 # 10sec
describe 'price custom type and field handling', (done) ->
customTypes = []
typesCleanup = (client) ->
customTypes = []
client.types.all().fetch()
.then (result) ->
Promise.all _.map result.body.results, (e) ->
client.types.byId(e.id).delete(e.version)
.then (results) ->
debug('Cleaned up all custom types.')
Promise.resolve()
.catch (error) ->
Promise.resolve(error)
beforeEach (done) ->
@client = new SphereClient config: Config
customTypePayloads = [
{
"key": "price-withKilosPrice",
"name": {
"en": "additional custom field kiloPrice"
},
"resourceTypeIds": [
"product-price"
],
"fieldDefinitions": [
{
"type": {
"name": "Money"
},
"name": "kiloPrice",
"label": {
"en": "kilo price"
},
"required": false,
"inputHint": "SingleLine"
}
]
},
{
"key": "price-withKilosPrice-two",
"name": {
"en": "additional custom field kiloPrice"
},
"resourceTypeIds": [
"product-price"
],
"fieldDefinitions": [
{
"type": {
"name": "Money"
},
"name": "kiloPrice",
"label": {
"en": "kilo price"
},
"required": false,
"inputHint": "SingleLine"
}
]
}
]
typesCleanup(@client).then =>
@client.types.create(customTypePayloads[0])
.then (result) =>
customTypes.push(result.body)
@client.types.create(customTypePayloads[1])
.then (result) ->
customTypes.push(result.body)
done()
.catch (error) ->
debug error
done()
it 'should update price custom type id', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[1].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.type.id).toBe customTypes[1].id
done()
.catch (error) -> done(_.prettify(error))
it 'should update custom fields', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'JPY',
centAmount: 9000
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.currencyCode).toBe 'JPY'
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.centAmount).toBe 9000
done()
.catch (error) -> done(_.prettify(error))
it 'should add price custom type and fields', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 4948
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.type.id).toBe customTypes[0].id
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.currencyCode).toBe 'EUR'
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.centAmount).toBe 4948
done()
.catch (error) -> done(_.prettify(error))
, 60000
| 118420 | debug = require('debug')('spec-integration:products')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient, ProductSync} = require '../../lib/main'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newProductType = ->
name: 'Clothing'
description: 'A sample product type'
newProduct = (pType) ->
name:
en: uniqueId 'product'
slug:
en: uniqueId 'slug'
productType:
id: pType.id
typeId: 'product-type'
masterVariant:
images: [
url: 'http://my.image.url'
dimensions:
w: 100
h: 100
label: 'label'
]
updateUnpublish = (version) ->
version: version
actions: [
{action: "unpublish"}
]
describe 'Integration Products Sync', ->
beforeEach (done) ->
@client = new SphereClient config: Config
@sync = new ProductSync
debug 'Creating a ProductType'
@client.productTypes.save(newProductType())
.then (result) =>
expect(result.statusCode).toBe 201
@productType = result.body
done()
.catch (error) -> done(_.prettify(error))
afterEach (done) ->
debug 'Unpublishing all products'
@client.products.sort('id').where('masterData(published = "true")')
.process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id)
.update(updateUnpublish(product.version))
.then (results) =>
debug "Unpublished #{results.length} products"
debug 'About to delete all products'
@client.products.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} products"
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).delete(product.version)
.then (results) =>
debug "Deleted #{results.length} products"
debug 'About to delete all product types'
@client.productTypes.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} product types"
Promise.all _.map payload.body.results, (productType) =>
@client.productTypes.byId(productType.id).delete(productType.version)
.then () ->
debug "Deleted #{results.length} product types"
done()
.catch (error) -> done(_.prettify(error.body))
, 60000 # 1min
describe 'Image update actions', ->
beforeEach (done) ->
debug 'Creating a Product'
@client.products.save(newProduct(@productType))
.then (result) =>
expect(result.statusCode).toBe 201
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
@testProduct = result.body
done()
.catch (error) ->
done(_.prettify(error))
afterEach (done) ->
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) =>
@client.products.byId(@testProduct.id).delete(updatedProduct.version)
.then () ->
done()
.catch (error) -> done(_.prettify(error))
it 'should update the label of an image', (done) ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].label = 'newLabel'
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) ->
actual = updatedProduct.masterVariant.images[0].label
expected = NEW_PROD.masterVariant.images[0].label
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should update the url of an image', (done) ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].url = 'http://my.new.image.url'
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) ->
actual = updatedProduct.masterVariant.images[0].url
expected = NEW_PROD.masterVariant.images[0].url
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should not update the dimensions of an image', ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].dimensions =
w: 200
h: 200
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
update = ->
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
expect(update).toThrow()
it 'should create and sync product', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {en: pName}
slug: {en: pSlug}
description: {en: 'A foo product'}
metaTitle: {en: 'The Foo'}
metaDescription: {en: 'The Foo product'}
masterVariant:
sku: 'v0'
prices: [
{value: {centAmount: 1000, currencyCode: 'EUR'}, country: 'DE'}
]
variants: [
{
sku: 'v1'
prices: [
{value: {centAmount: 2000, currencyCode: 'USD'}}
]
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
metaTitle: {de: 'The Foo'}
metaDescription: {de: 'The Foo product'}
searchKeywords: {
en: [{text: 'new'}, {text: 'search'}, {text: 'keywords'}]
"fr-BE": [{text: 'bruxelles'}, {text:'liege'}, {text: 'brugge'}]
}
masterVariant:
id: 1
sku: 'v0'
prices: [
{value: {centAmount: 1500, currencyCode: 'EUR'}, country: 'DE'}
{value: {centAmount: 1500, currencyCode: 'EUR'}, country: 'IT'}
]
variants: [
{
id: 2
sku: 'v1'
prices: [
{value: {centAmount: 2000, currencyCode: 'USD'}}
]
},
{
sku: 'v2'
prices: [
{value: {centAmount: 3000, currencyCode: 'EUR'}, country: 'FR'}
]
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.name).toEqual {de: pName}
expect(updated.slug).toEqual {de: pSlug}
expect(updated.description).toEqual {de: 'A foo product'}
expect(updated.metaTitle).toEqual {de: 'The Foo'}
expect(updated.metaDescription).toEqual {de: 'The Foo product'}
expect(updated.masterVariant.prices[0].value.centAmount).toBe 1500
expect(updated.masterVariant.prices[1].value.centAmount).toBe 1500
expect(updated.masterVariant.prices[1].country).toBe 'IT'
expect(updated.searchKeywords.en[0].text).toBe 'new'
expect(updated.searchKeywords['fr-BE'][1].text).toBe 'liege'
expect(updated.variants[0].sku).toBe 'v1'
expect(updated.variants[0].prices[0].value.centAmount).toBe 2000
expect(updated.variants[1].sku).toBe 'v2'
expect(updated.variants[1].prices[0].value.centAmount).toBe 3000
expect(updated.variants[1].prices[0].country).toBe 'FR'
done()
.catch (error) -> done(_.prettify(error))
, 30000 # 30sec
describe 'State update actions', ->
initialStateId = null
secondStateId = null
testProduct = null
cleanupState = (client) ->
# remove states if they exist
states = [
'SdkIntegrationTestInitialState',
'SdkIntegrationTestSecondState'
]
Promise.all(states.map((state) ->
client.states
.where("key=\"#{state}\"")
.fetch()
.then(({ body: { results: [stateToDelete] } }) ->
if stateToDelete
client.states.byId(stateToDelete.id).delete(stateToDelete.version)
)
))
cleanupProduct = (client) ->
if testProduct
return client.productProjections
.byId(testProduct.id)
.staged(true)
.fetch()
.then ({ body: updatedProduct }) ->
testProduct = null
client.products
.byId(updatedProduct.id)
.delete(updatedProduct.version)
Promise.resolve()
beforeEach (done) ->
cleanupProduct(@client)
.then => cleanupState(@client)
.then =>
# setup states
@client.states.create({
key: '<KEY>',
type: 'ProductState',
}).then(({ body: state }) ->
initialStateId = state.id
)
.then =>
@client.states.create({
key: '<KEY>',
type: 'ProductState',
}).then(({ body: state }) ->
secondStateId = state.id
)
.then =>
# setup product
@client.products.save(newProduct(@productType))
.then ({ body: { id } }) =>
@client.productProjections.byId(id).staged(true).fetch()
.then ({ body }) ->
testProduct = body
.then -> done()
.catch (error) ->
done(_.prettify(error))
afterEach (done) ->
cleanupProduct(@client)
.then => cleanupState(@client)
.then -> done()
.catch (error) -> done(_.prettify(error))
it 'should add a the initial state to a product', (done) ->
updatedTestProd = _.extend({}, testProduct, {
state: {
typeId: 'state',
id: initialStateId
}
})
diff = @sync.buildActions(updatedTestProd, testProduct)
expect(diff.shouldUpdate()).toEqual(true)
@client.products.byId(updatedTestProd.id).update(diff.getUpdatePayload())
.then(({ body: { state } }) ->
expect(state).toEqual({
typeId: 'state',
id: initialStateId
})
done()
)
.catch (error) -> done(_.prettify(error))
, 10000 # 10sec
it 'should transition the state', (done) ->
# set the initial state
@client.products.byId(testProduct.id).update({
actions: [{
action: 'transitionState',
state: { typeId: 'state', id: initialStateId }
}]
version: testProduct.version
})
.then =>
@client.productProjections.byId(testProduct.id).staged(true).fetch()
.then(({ body: prodWithInitialState }) =>
updatedTestProd = _.extend({}, prodWithInitialState, {
state: {
typeId: 'state',
id: secondStateId
}
})
diff = @sync.buildActions(updatedTestProd, prodWithInitialState)
expect(diff.shouldUpdate()).toEqual(true)
@client.products
.byId(updatedTestProd.id)
.update(diff.getUpdatePayload())
)
.then(({ body: { state } }) ->
expect(state).toEqual({
typeId: 'state',
id: secondStateId
})
done()
)
.catch (error) ->
done(_.prettify(error))
, 10000 # 10sec
describe 'price custom type and field handling', (done) ->
customTypes = []
typesCleanup = (client) ->
customTypes = []
client.types.all().fetch()
.then (result) ->
Promise.all _.map result.body.results, (e) ->
client.types.byId(e.id).delete(e.version)
.then (results) ->
debug('Cleaned up all custom types.')
Promise.resolve()
.catch (error) ->
Promise.resolve(error)
beforeEach (done) ->
@client = new SphereClient config: Config
customTypePayloads = [
{
"key": "<KEY>",
"name": {
"en": "additional custom field kiloPrice"
},
"resourceTypeIds": [
"product-price"
],
"fieldDefinitions": [
{
"type": {
"name": "Money"
},
"name": "kiloPrice",
"label": {
"en": "kilo price"
},
"required": false,
"inputHint": "SingleLine"
}
]
},
{
"key": "<KEY>",
"name": {
"en": "additional custom field kiloPrice"
},
"resourceTypeIds": [
"product-price"
],
"fieldDefinitions": [
{
"type": {
"name": "Money"
},
"name": "kiloPrice",
"label": {
"en": "kilo price"
},
"required": false,
"inputHint": "SingleLine"
}
]
}
]
typesCleanup(@client).then =>
@client.types.create(customTypePayloads[0])
.then (result) =>
customTypes.push(result.body)
@client.types.create(customTypePayloads[1])
.then (result) ->
customTypes.push(result.body)
done()
.catch (error) ->
debug error
done()
it 'should update price custom type id', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[1].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.type.id).toBe customTypes[1].id
done()
.catch (error) -> done(_.prettify(error))
it 'should update custom fields', (done) ->
pName = uniqueId('<NAME>')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: <NAME>Name}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: <NAME>Name}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'JPY',
centAmount: 9000
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.currencyCode).toBe 'JPY'
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.centAmount).toBe 9000
done()
.catch (error) -> done(_.prettify(error))
it 'should add price custom type and fields', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 4948
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.type.id).toBe customTypes[0].id
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.currencyCode).toBe 'EUR'
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.centAmount).toBe 4948
done()
.catch (error) -> done(_.prettify(error))
, 60000
| true | debug = require('debug')('spec-integration:products')
_ = require 'underscore'
_.mixin require 'underscore-mixins'
Promise = require 'bluebird'
{SphereClient, ProductSync} = require '../../lib/main'
Config = require('../../config').config
uniqueId = (prefix) ->
_.uniqueId "#{prefix}#{new Date().getTime()}_"
newProductType = ->
name: 'Clothing'
description: 'A sample product type'
newProduct = (pType) ->
name:
en: uniqueId 'product'
slug:
en: uniqueId 'slug'
productType:
id: pType.id
typeId: 'product-type'
masterVariant:
images: [
url: 'http://my.image.url'
dimensions:
w: 100
h: 100
label: 'label'
]
updateUnpublish = (version) ->
version: version
actions: [
{action: "unpublish"}
]
describe 'Integration Products Sync', ->
beforeEach (done) ->
@client = new SphereClient config: Config
@sync = new ProductSync
debug 'Creating a ProductType'
@client.productTypes.save(newProductType())
.then (result) =>
expect(result.statusCode).toBe 201
@productType = result.body
done()
.catch (error) -> done(_.prettify(error))
afterEach (done) ->
debug 'Unpublishing all products'
@client.products.sort('id').where('masterData(published = "true")')
.process (payload) =>
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id)
.update(updateUnpublish(product.version))
.then (results) =>
debug "Unpublished #{results.length} products"
debug 'About to delete all products'
@client.products.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} products"
Promise.all _.map payload.body.results, (product) =>
@client.products.byId(product.id).delete(product.version)
.then (results) =>
debug "Deleted #{results.length} products"
debug 'About to delete all product types'
@client.productTypes.all().fetch()
.then (payload) =>
debug "Deleting #{payload.body.total} product types"
Promise.all _.map payload.body.results, (productType) =>
@client.productTypes.byId(productType.id).delete(productType.version)
.then () ->
debug "Deleted #{results.length} product types"
done()
.catch (error) -> done(_.prettify(error.body))
, 60000 # 1min
describe 'Image update actions', ->
beforeEach (done) ->
debug 'Creating a Product'
@client.products.save(newProduct(@productType))
.then (result) =>
expect(result.statusCode).toBe 201
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
@testProduct = result.body
done()
.catch (error) ->
done(_.prettify(error))
afterEach (done) ->
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) =>
@client.products.byId(@testProduct.id).delete(updatedProduct.version)
.then () ->
done()
.catch (error) -> done(_.prettify(error))
it 'should update the label of an image', (done) ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].label = 'newLabel'
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) ->
actual = updatedProduct.masterVariant.images[0].label
expected = NEW_PROD.masterVariant.images[0].label
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should update the url of an image', (done) ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].url = 'http://my.new.image.url'
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(@testProduct.id).staged(true).fetch()
.then ({ body: updatedProduct }) ->
actual = updatedProduct.masterVariant.images[0].url
expected = NEW_PROD.masterVariant.images[0].url
expect(actual).toEqual(expected)
done()
.catch (error) -> done(_.prettify(error))
it 'should not update the dimensions of an image', ->
NEW_PROD = _.deepClone(@testProduct)
NEW_PROD.masterVariant.images[0].dimensions =
w: 200
h: 200
syncedActions = @sync.buildActions(NEW_PROD, @testProduct)
updatePayload = syncedActions.getUpdatePayload()
update = ->
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
expect(update).toThrow()
it 'should create and sync product', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {en: pName}
slug: {en: pSlug}
description: {en: 'A foo product'}
metaTitle: {en: 'The Foo'}
metaDescription: {en: 'The Foo product'}
masterVariant:
sku: 'v0'
prices: [
{value: {centAmount: 1000, currencyCode: 'EUR'}, country: 'DE'}
]
variants: [
{
sku: 'v1'
prices: [
{value: {centAmount: 2000, currencyCode: 'USD'}}
]
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
metaTitle: {de: 'The Foo'}
metaDescription: {de: 'The Foo product'}
searchKeywords: {
en: [{text: 'new'}, {text: 'search'}, {text: 'keywords'}]
"fr-BE": [{text: 'bruxelles'}, {text:'liege'}, {text: 'brugge'}]
}
masterVariant:
id: 1
sku: 'v0'
prices: [
{value: {centAmount: 1500, currencyCode: 'EUR'}, country: 'DE'}
{value: {centAmount: 1500, currencyCode: 'EUR'}, country: 'IT'}
]
variants: [
{
id: 2
sku: 'v1'
prices: [
{value: {centAmount: 2000, currencyCode: 'USD'}}
]
},
{
sku: 'v2'
prices: [
{value: {centAmount: 3000, currencyCode: 'EUR'}, country: 'FR'}
]
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.name).toEqual {de: pName}
expect(updated.slug).toEqual {de: pSlug}
expect(updated.description).toEqual {de: 'A foo product'}
expect(updated.metaTitle).toEqual {de: 'The Foo'}
expect(updated.metaDescription).toEqual {de: 'The Foo product'}
expect(updated.masterVariant.prices[0].value.centAmount).toBe 1500
expect(updated.masterVariant.prices[1].value.centAmount).toBe 1500
expect(updated.masterVariant.prices[1].country).toBe 'IT'
expect(updated.searchKeywords.en[0].text).toBe 'new'
expect(updated.searchKeywords['fr-BE'][1].text).toBe 'liege'
expect(updated.variants[0].sku).toBe 'v1'
expect(updated.variants[0].prices[0].value.centAmount).toBe 2000
expect(updated.variants[1].sku).toBe 'v2'
expect(updated.variants[1].prices[0].value.centAmount).toBe 3000
expect(updated.variants[1].prices[0].country).toBe 'FR'
done()
.catch (error) -> done(_.prettify(error))
, 30000 # 30sec
describe 'State update actions', ->
initialStateId = null
secondStateId = null
testProduct = null
cleanupState = (client) ->
# remove states if they exist
states = [
'SdkIntegrationTestInitialState',
'SdkIntegrationTestSecondState'
]
Promise.all(states.map((state) ->
client.states
.where("key=\"#{state}\"")
.fetch()
.then(({ body: { results: [stateToDelete] } }) ->
if stateToDelete
client.states.byId(stateToDelete.id).delete(stateToDelete.version)
)
))
cleanupProduct = (client) ->
if testProduct
return client.productProjections
.byId(testProduct.id)
.staged(true)
.fetch()
.then ({ body: updatedProduct }) ->
testProduct = null
client.products
.byId(updatedProduct.id)
.delete(updatedProduct.version)
Promise.resolve()
beforeEach (done) ->
cleanupProduct(@client)
.then => cleanupState(@client)
.then =>
# setup states
@client.states.create({
key: 'PI:KEY:<KEY>END_PI',
type: 'ProductState',
}).then(({ body: state }) ->
initialStateId = state.id
)
.then =>
@client.states.create({
key: 'PI:KEY:<KEY>END_PI',
type: 'ProductState',
}).then(({ body: state }) ->
secondStateId = state.id
)
.then =>
# setup product
@client.products.save(newProduct(@productType))
.then ({ body: { id } }) =>
@client.productProjections.byId(id).staged(true).fetch()
.then ({ body }) ->
testProduct = body
.then -> done()
.catch (error) ->
done(_.prettify(error))
afterEach (done) ->
cleanupProduct(@client)
.then => cleanupState(@client)
.then -> done()
.catch (error) -> done(_.prettify(error))
it 'should add a the initial state to a product', (done) ->
updatedTestProd = _.extend({}, testProduct, {
state: {
typeId: 'state',
id: initialStateId
}
})
diff = @sync.buildActions(updatedTestProd, testProduct)
expect(diff.shouldUpdate()).toEqual(true)
@client.products.byId(updatedTestProd.id).update(diff.getUpdatePayload())
.then(({ body: { state } }) ->
expect(state).toEqual({
typeId: 'state',
id: initialStateId
})
done()
)
.catch (error) -> done(_.prettify(error))
, 10000 # 10sec
it 'should transition the state', (done) ->
# set the initial state
@client.products.byId(testProduct.id).update({
actions: [{
action: 'transitionState',
state: { typeId: 'state', id: initialStateId }
}]
version: testProduct.version
})
.then =>
@client.productProjections.byId(testProduct.id).staged(true).fetch()
.then(({ body: prodWithInitialState }) =>
updatedTestProd = _.extend({}, prodWithInitialState, {
state: {
typeId: 'state',
id: secondStateId
}
})
diff = @sync.buildActions(updatedTestProd, prodWithInitialState)
expect(diff.shouldUpdate()).toEqual(true)
@client.products
.byId(updatedTestProd.id)
.update(diff.getUpdatePayload())
)
.then(({ body: { state } }) ->
expect(state).toEqual({
typeId: 'state',
id: secondStateId
})
done()
)
.catch (error) ->
done(_.prettify(error))
, 10000 # 10sec
describe 'price custom type and field handling', (done) ->
customTypes = []
typesCleanup = (client) ->
customTypes = []
client.types.all().fetch()
.then (result) ->
Promise.all _.map result.body.results, (e) ->
client.types.byId(e.id).delete(e.version)
.then (results) ->
debug('Cleaned up all custom types.')
Promise.resolve()
.catch (error) ->
Promise.resolve(error)
beforeEach (done) ->
@client = new SphereClient config: Config
customTypePayloads = [
{
"key": "PI:KEY:<KEY>END_PI",
"name": {
"en": "additional custom field kiloPrice"
},
"resourceTypeIds": [
"product-price"
],
"fieldDefinitions": [
{
"type": {
"name": "Money"
},
"name": "kiloPrice",
"label": {
"en": "kilo price"
},
"required": false,
"inputHint": "SingleLine"
}
]
},
{
"key": "PI:KEY:<KEY>END_PI",
"name": {
"en": "additional custom field kiloPrice"
},
"resourceTypeIds": [
"product-price"
],
"fieldDefinitions": [
{
"type": {
"name": "Money"
},
"name": "kiloPrice",
"label": {
"en": "kilo price"
},
"required": false,
"inputHint": "SingleLine"
}
]
}
]
typesCleanup(@client).then =>
@client.types.create(customTypePayloads[0])
.then (result) =>
customTypes.push(result.body)
@client.types.create(customTypePayloads[1])
.then (result) ->
customTypes.push(result.body)
done()
.catch (error) ->
debug error
done()
it 'should update price custom type id', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[1].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.type.id).toBe customTypes[1].id
done()
.catch (error) -> done(_.prettify(error))
it 'should update custom fields', (done) ->
pName = uniqueId('PI:NAME:<NAME>END_PI')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: PI:NAME:<NAME>END_PIName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 2000
}
}
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: PI:NAME:<NAME>END_PIName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'JPY',
centAmount: 9000
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.currencyCode).toBe 'JPY'
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.centAmount).toBe 9000
done()
.catch (error) -> done(_.prettify(error))
it 'should add price custom type and fields', (done) ->
pName = uniqueId('Foo')
pSlug = uniqueId('foo')
OLD_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
}
}
]
NEW_PROD =
productType:
id: @productType.id
typeId: 'product-type'
name: {de: pName}
slug: {de: pSlug}
description: {de: 'A foo product'}
masterVariant:
id: 1
sku: 'v2'
prices: [
{
value: {
centAmount: 1000,
currencyCode: 'EUR'
},
custom: {
type: {
typeId: 'type',
id: customTypes[0].id,
}
fields: {
kiloPrice: {
currencyCode: 'EUR',
centAmount: 4948
}
}
}
}
]
debug 'Create initial product to be synced'
@client.products.create(OLD_PROD)
.then (result) =>
debug 'Fetch projection of created product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) =>
syncedActions = @sync.buildActions(NEW_PROD, result.body)
expect(syncedActions.shouldUpdate()).toBe true
updatePayload = syncedActions.getUpdatePayload()
debug 'About to update product with synced actions'
@client.products.byId(syncedActions.getUpdateId()).update(updatePayload)
.then (result) =>
debug 'Fetch projection of updated product'
@client.productProjections.byId(result.body.id).staged(true).fetch()
.then (result) ->
updated = result.body
expect(updated.masterVariant.prices[0].custom.type.id).toBe customTypes[0].id
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.currencyCode).toBe 'EUR'
expect(updated.masterVariant.prices[0].custom.fields.kiloPrice.centAmount).toBe 4948
done()
.catch (error) -> done(_.prettify(error))
, 60000
|
[
{
"context": "news detected\"\n\npermissions: []\n\nauthor: \"Ben from BenSites.com, ess090502, and contributors\"\n\nsandbox:\n pag",
"end": 805,
"score": 0.5727423429489136,
"start": 797,
"tag": "EMAIL",
"value": "BenSites"
},
{
"context": "ted\"\n\npermissions: []\n\nauthor: \"Ben from BenSites.com, ess090502, and contributors\"\n\nsandbox:\n pages: ",
"end": 809,
"score": 0.5225756764411926,
"start": 806,
"tag": "EMAIL",
"value": "com"
},
{
"context": "\n\npermissions: []\n\nauthor: \"Ben from BenSites.com, ess090502, and contributors\"\n\nsandbox:\n pages: [\"{{../shar",
"end": 820,
"score": 0.9815722107887268,
"start": 811,
"tag": "USERNAME",
"value": "ess090502"
}
] | src/chrome/manifest.cson | penne12/WhoseNews | 3 | manifest_version: 2
name: "Whose News"
description: "An extension to tell you where your news comes from"
version: "0.1.4"
icons:
16: "{{../shared/img/Whose-News-Icon-Small16.png}}"
19: "{{../shared/img/Whose-News-Icon-Small19.png}}"
32: "{{../shared/img/Whose-News-Icon32.png}}"
38: "{{../shared/img/Whose-News-Icon38.png}}"
48: "{{../shared/img/Whose-News-Icon48.png}}"
64: "{{../shared/img/Whose-News-Icon64.png}}"
128: "{{../shared/img/Whose-News-Icon128.png}}"
250: "{{../shared/img/Whose-News-Icon250.png}}"
browser_action:
default_icon:
19: "{{../shared/img/Whose-News-Icon-Small19.png}}"
38: "{{../shared/img/Whose-News-Icon38.png}}"
default_popup: "{{./views/popup/index}}"
default_title: "Whose News: No news detected"
permissions: []
author: "Ben from BenSites.com, ess090502, and contributors"
sandbox:
pages: ["{{../shared/views/popup/index}}"]
background:
scripts: [
"{{entry?name=background.js!./background}}"
]
persistent: false
content_scripts: [
{
matches: ["<all_urls>"],
js: ["{{entry?name=content.js!./content}}"]
}
]
| 66165 | manifest_version: 2
name: "Whose News"
description: "An extension to tell you where your news comes from"
version: "0.1.4"
icons:
16: "{{../shared/img/Whose-News-Icon-Small16.png}}"
19: "{{../shared/img/Whose-News-Icon-Small19.png}}"
32: "{{../shared/img/Whose-News-Icon32.png}}"
38: "{{../shared/img/Whose-News-Icon38.png}}"
48: "{{../shared/img/Whose-News-Icon48.png}}"
64: "{{../shared/img/Whose-News-Icon64.png}}"
128: "{{../shared/img/Whose-News-Icon128.png}}"
250: "{{../shared/img/Whose-News-Icon250.png}}"
browser_action:
default_icon:
19: "{{../shared/img/Whose-News-Icon-Small19.png}}"
38: "{{../shared/img/Whose-News-Icon38.png}}"
default_popup: "{{./views/popup/index}}"
default_title: "Whose News: No news detected"
permissions: []
author: "Ben from <EMAIL>.<EMAIL>, ess090502, and contributors"
sandbox:
pages: ["{{../shared/views/popup/index}}"]
background:
scripts: [
"{{entry?name=background.js!./background}}"
]
persistent: false
content_scripts: [
{
matches: ["<all_urls>"],
js: ["{{entry?name=content.js!./content}}"]
}
]
| true | manifest_version: 2
name: "Whose News"
description: "An extension to tell you where your news comes from"
version: "0.1.4"
icons:
16: "{{../shared/img/Whose-News-Icon-Small16.png}}"
19: "{{../shared/img/Whose-News-Icon-Small19.png}}"
32: "{{../shared/img/Whose-News-Icon32.png}}"
38: "{{../shared/img/Whose-News-Icon38.png}}"
48: "{{../shared/img/Whose-News-Icon48.png}}"
64: "{{../shared/img/Whose-News-Icon64.png}}"
128: "{{../shared/img/Whose-News-Icon128.png}}"
250: "{{../shared/img/Whose-News-Icon250.png}}"
browser_action:
default_icon:
19: "{{../shared/img/Whose-News-Icon-Small19.png}}"
38: "{{../shared/img/Whose-News-Icon38.png}}"
default_popup: "{{./views/popup/index}}"
default_title: "Whose News: No news detected"
permissions: []
author: "Ben from PI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI, ess090502, and contributors"
sandbox:
pages: ["{{../shared/views/popup/index}}"]
background:
scripts: [
"{{entry?name=background.js!./background}}"
]
persistent: false
content_scripts: [
{
matches: ["<all_urls>"],
js: ["{{entry?name=content.js!./content}}"]
}
]
|
[
{
"context": "##\n# @class MyClass\n# @author Test Author <test@xyz.com>\n# @version 2.0.0\n",
"end": 41,
"score": 0.8820454478263855,
"start": 30,
"tag": "NAME",
"value": "Test Author"
},
{
"context": "##\n# @class MyClass\n# @author Test Author <test@xyz.com>\n# @version 2.0.0\n",
"end": 55,
"score": 0.9999303817749023,
"start": 43,
"tag": "EMAIL",
"value": "test@xyz.com"
}
] | test/input/0001.coffee | JoshuaToenyes/coffeed | 0 | ##
# @class MyClass
# @author Test Author <test@xyz.com>
# @version 2.0.0
| 118438 | ##
# @class MyClass
# @author <NAME> <<EMAIL>>
# @version 2.0.0
| true | ##
# @class MyClass
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @version 2.0.0
|
[
{
"context": " \"mostCommonIsotopeMass\": 0.0,\n \"name\": \"Dummy\",\n \"outshellElectrons\": 0,\n \"rB0\": 0.0,",
"end": 228,
"score": 0.9982638955116272,
"start": 223,
"tag": "NAME",
"value": "Dummy"
},
{
"context": " \"boilingpoint\": 20.28,\n \"discoverers\": \"C. Cavendish\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 472,
"score": 0.9997859001159668,
"start": 460,
"tag": "NAME",
"value": "C. Cavendish"
},
{
"context": "stCommonIsotopeMass\": 1.007825032,\n \"name\": \"Hydrogen\",\n \"nameOrigin\": \"Greek 'hydro' and 'gennao'",
"end": 954,
"score": 0.9932306408882141,
"start": 946,
"tag": "NAME",
"value": "Hydrogen"
},
{
"context": " \"boilingpoint\": 4.216,\n \"discoverers\": [\"P. J. Janssen\", \"J. N. Lockyer\"],\n \"discoveryCountry\": [\"s",
"end": 1320,
"score": 0.9998205304145813,
"start": 1307,
"tag": "NAME",
"value": "P. J. Janssen"
},
{
"context": "\": 4.216,\n \"discoverers\": [\"P. J. Janssen\", \"J. N. Lockyer\"],\n \"discoveryCountry\": [\"se\", \"uk\"],\n ",
"end": 1337,
"score": 0.999891459941864,
"start": 1324,
"tag": "NAME",
"value": "J. N. Lockyer"
},
{
"context": "stCommonIsotopeMass\": 4.002603254,\n \"name\": \"Helium\",\n \"nameOrigin\": \"The Greek word for the sun",
"end": 1781,
"score": 0.999746561050415,
"start": 1775,
"tag": "NAME",
"value": "Helium"
},
{
"context": " \"boilingpoint\": 1615.0,\n \"discoverers\": \"A. Arfvedson\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 2141,
"score": 0.9998307824134827,
"start": 2129,
"tag": "NAME",
"value": "A. Arfvedson"
},
{
"context": "ostCommonIsotopeMass\": 7.01600455,\n \"name\": \"Lithium\",\n \"nameOrigin\": \"Greek 'lithos' means 'ston",
"end": 2623,
"score": 0.999754011631012,
"start": 2616,
"tag": "NAME",
"value": "Lithium"
},
{
"context": " \"boilingpoint\": 3243.0,\n \"discoverers\": \"Nicholas Louis Vauquelin\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 2985,
"score": 0.9998723864555359,
"start": 2961,
"tag": "NAME",
"value": "Nicholas Louis Vauquelin"
},
{
"context": "mostCommonIsotopeMass\": 9.0121822,\n \"name\": \"Beryllium\",\n \"nameOrigin\": \"Greek 'beryllos' for 'ligh",
"end": 3469,
"score": 0.9997011423110962,
"start": 3460,
"tag": "NAME",
"value": "Beryllium"
},
{
"context": "ame\": \"Beryllium\",\n \"nameOrigin\": \"Greek 'beryllos' for 'light-green stone'\",\n \"outshellElec",
"end": 3505,
"score": 0.8544465899467468,
"start": 3503,
"tag": "NAME",
"value": "yl"
},
{
"context": " \"boilingpoint\": 4275.0,\n \"discoverers\": [\"Louis Joseph Gay-Lussac\", \"Louis Jacques Thenard\"],\n \"discoveryCount",
"end": 3841,
"score": 0.9998647570610046,
"start": 3818,
"tag": "NAME",
"value": "Louis Joseph Gay-Lussac"
},
{
"context": " \"discoverers\": [\"Louis Joseph Gay-Lussac\", \"Louis Jacques Thenard\"],\n \"discoveryCountry\": [\"uk\", \"fr\"],\n ",
"end": 3866,
"score": 0.9998569488525391,
"start": 3845,
"tag": "NAME",
"value": "Louis Jacques Thenard"
},
{
"context": "ostCommonIsotopeMass\": 11.0093054,\n \"name\": \"Boron\",\n \"nameOrigin\": \"Boron means 'Bor(ax) + (ca",
"end": 4360,
"score": 0.9984326362609863,
"start": 4355,
"tag": "NAME",
"value": "Boron"
},
{
"context": "4,\n \"name\": \"Boron\",\n \"nameOrigin\": \"Boron means 'Bor(ax) + (carb)on'. It is found in borax ",
"end": 4389,
"score": 0.5346450209617615,
"start": 4387,
"tag": "NAME",
"value": "on"
},
{
"context": " \"mostCommonIsotopeMass\": 12.0,\n \"name\": \"Carbon\",\n \"nameOrigin\": \"Latin 'carboneum' for carb",
"end": 5204,
"score": 0.999289870262146,
"start": 5198,
"tag": "NAME",
"value": "Carbon"
},
{
"context": " \"boilingpoint\": 77.344,\n \"discoverers\": \"D. Rutherford\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 5554,
"score": 0.9998785853385925,
"start": 5541,
"tag": "NAME",
"value": "D. Rutherford"
},
{
"context": " \"boilingpoint\": 90.188,\n \"discoverers\": \"J. Priestley\",\n \"discoveryCountry\": [\"se\", \"uk\"],\n \"",
"end": 6397,
"score": 0.9998700022697449,
"start": 6385,
"tag": "NAME",
"value": "J. Priestley"
},
{
"context": " \"boilingpoint\": 85.0,\n \"discoverers\": \"H. F. Moissan\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 7245,
"score": 0.9998764991760254,
"start": 7232,
"tag": "NAME",
"value": "H. F. Moissan"
},
{
"context": " \"boilingpoint\": 27.1,\n \"discoverers\": [\"W. Ramsay\", \"M.W. Travers\"],\n \"discoveryCountry\": \"uk\"",
"end": 8080,
"score": 0.9998924136161804,
"start": 8071,
"tag": "NAME",
"value": "W. Ramsay"
},
{
"context": "point\": 27.1,\n \"discoverers\": [\"W. Ramsay\", \"M.W. Travers\"],\n \"discoveryCountry\": \"uk\",\n \"discove",
"end": 8096,
"score": 0.9998854994773865,
"start": 8084,
"tag": "NAME",
"value": "M.W. Travers"
},
{
"context": "stCommonIsotopeMass\": 19.99244018,\n \"name\": \"Neon\",\n \"nameOrigin\": \"Greek 'neo'. meaning 'new'",
"end": 8539,
"score": 0.9942238926887512,
"start": 8535,
"tag": "NAME",
"value": "Neon"
},
{
"context": " \"boilingpoint\": 1156.0,\n \"discoverers\": \"Sir Humphrey Davy\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 8893,
"score": 0.9998478889465332,
"start": 8876,
"tag": "NAME",
"value": "Sir Humphrey Davy"
},
{
"context": " \"boilingpoint\": 1380.0,\n \"discoverers\": \"H. B. Davy\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 9733,
"score": 0.9998872876167297,
"start": 9723,
"tag": "NAME",
"value": "H. B. Davy"
},
{
"context": "ostCommonIsotopeMass\": 23.9850417,\n \"name\": \"Magnesium\",\n \"nameOrigin\": \"Named after the ci",
"end": 10209,
"score": 0.6915020942687988,
"start": 10208,
"tag": "NAME",
"value": "M"
},
{
"context": " \"boilingpoint\": 2740.0,\n \"discoverers\": \"H. Ch. Oersted\",\n \"discoveryCountry\": \"dk\",\n \"discover",
"end": 10573,
"score": 0.9998948574066162,
"start": 10559,
"tag": "NAME",
"value": "H. Ch. Oersted"
},
{
"context": " \"boilingpoint\": 2630.0,\n \"discoverers\": \"J. J. Berzelius\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 11410,
"score": 0.9998849630355835,
"start": 11395,
"tag": "NAME",
"value": "J. J. Berzelius"
},
{
"context": "stCommonIsotopeMass\": 27.97692653,\n \"name\": \"Silicon\",\n \"nameOrigin\": \"Latin 'silex'\",\n \"out",
"end": 11899,
"score": 0.9996329545974731,
"start": 11892,
"tag": "NAME",
"value": "Silicon"
},
{
"context": " \"boilingpoint\": 553.0,\n \"discoverers\": \"H. Brandt\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 12235,
"score": 0.9998385310173035,
"start": 12226,
"tag": "NAME",
"value": "H. Brandt"
},
{
"context": "stCommonIsotopeMass\": 30.97376163,\n \"name\": \"Phosphorus\",\n \"nameOrigin\": \"Greek 'phosphoros' for 'ca",
"end": 12726,
"score": 0.9689092636108398,
"start": 12716,
"tag": "NAME",
"value": "Phosphorus"
},
{
"context": "mostCommonIsotopeMass\": 31.972071,\n \"name\": \"Sulfur\",\n \"nameOrigin\": \"In sanskrit 'sweb' means '",
"end": 13540,
"score": 0.999770998954773,
"start": 13534,
"tag": "NAME",
"value": "Sulfur"
},
{
"context": " \"boilingpoint\": 239.18,\n \"discoverers\": \"C. W. Scheele\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 13904,
"score": 0.9998693466186523,
"start": 13891,
"tag": "NAME",
"value": "C. W. Scheele"
},
{
"context": "stCommonIsotopeMass\": 34.96885268,\n \"name\": \"Chlorine\",\n \"nameOrigin\": \"Greek 'chloros' for 'yello",
"end": 14395,
"score": 0.9996070265769958,
"start": 14387,
"tag": "NAME",
"value": "Chlorine"
},
{
"context": " \"boilingpoint\": 87.45,\n \"discoverers\": [\"W. Ramsay\", \"J. Rayleigh\"],\n \"discoveryCountry\": \"uk\",",
"end": 14750,
"score": 0.9998477101325989,
"start": 14741,
"tag": "NAME",
"value": "W. Ramsay"
},
{
"context": "oint\": 87.45,\n \"discoverers\": [\"W. Ramsay\", \"J. Rayleigh\"],\n \"discoveryCountry\": \"uk\",\n \"discove",
"end": 14765,
"score": 0.9998533129692078,
"start": 14754,
"tag": "NAME",
"value": "J. Rayleigh"
},
{
"context": "stCommonIsotopeMass\": 39.96238312,\n \"name\": \"Argon\",\n \"nameOrigin\": \"Greek 'aergon' for 'inacti",
"end": 15208,
"score": 0.999712347984314,
"start": 15203,
"tag": "NAME",
"value": "Argon"
},
{
"context": " \"boilingpoint\": 1033.0,\n \"discoverers\": \"H. B. Davy\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 15559,
"score": 0.9998946785926819,
"start": 15549,
"tag": "NAME",
"value": "H. B. Davy"
},
{
"context": "stCommonIsotopeMass\": 38.96370668,\n \"name\": \"Potassium\",\n \"nameOrigin\": \"Arabic 'al qaliy' for pota",
"end": 16050,
"score": 0.8919489979743958,
"start": 16041,
"tag": "NAME",
"value": "Potassium"
},
{
"context": " \"boilingpoint\": 1757.0,\n \"discoverers\": \"H. B. Davy\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 16398,
"score": 0.9998934268951416,
"start": 16388,
"tag": "NAME",
"value": "H. B. Davy"
},
{
"context": "stCommonIsotopeMass\": 39.96259098,\n \"name\": \"Calcium\",\n \"nameOrigin\": \"Latin 'calx' for 'lime'\",\n",
"end": 16886,
"score": 0.9933657050132751,
"start": 16879,
"tag": "NAME",
"value": "Calcium"
},
{
"context": " \"boilingpoint\": 3109.0,\n \"discoverers\": \"L. Nilson\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 17229,
"score": 0.9998037815093994,
"start": 17220,
"tag": "NAME",
"value": "L. Nilson"
},
{
"context": "ostCommonIsotopeMass\": 44.9559119,\n \"name\": \"Scandium\",\n \"nameOrigin\": \"Named because it was found",
"end": 17717,
"score": 0.9946232438087463,
"start": 17709,
"tag": "NAME",
"value": "Scandium"
},
{
"context": " \"boilingpoint\": 3560.0,\n \"discoverers\": \"W. Gregor\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 18077,
"score": 0.9991627931594849,
"start": 18068,
"tag": "NAME",
"value": "W. Gregor"
},
{
"context": "ostCommonIsotopeMass\": 47.9479463,\n \"name\": \"Titanium\",\n \"nameOrigin\": \"The Titans were giants in ",
"end": 18565,
"score": 0.8012080192565918,
"start": 18557,
"tag": "NAME",
"value": "Titanium"
},
{
"context": " \"boilingpoint\": 3650.0,\n \"discoverers\": \"N. Sefstr\\u00f6m\",\n \"discoveryCountry\": \"se\",\n \"d",
"end": 18926,
"score": 0.9369629621505737,
"start": 18917,
"tag": "NAME",
"value": "N. Sefstr"
},
{
"context": "nt\": 3650.0,\n \"discoverers\": \"N. Sefstr\\u00f6m\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 18933,
"score": 0.5558240413665771,
"start": 18932,
"tag": "NAME",
"value": "m"
},
{
"context": "ostCommonIsotopeMass\": 49.9471585,\n \"name\": \"Vanadium\",\n \"nameOrigin\": \"'Vanadis' is another name ",
"end": 19421,
"score": 0.996751070022583,
"start": 19413,
"tag": "NAME",
"value": "Vanadium"
},
{
"context": ",\n \"name\": \"Vanadium\",\n \"nameOrigin\": \"'Vanadis' is another name for the Nordic goddess Freyja\",\n",
"end": 19453,
"score": 0.9981687664985657,
"start": 19446,
"tag": "NAME",
"value": "Vanadis"
},
{
"context": " \"nameOrigin\": \"'Vanadis' is another name for the Nordic goddess Freyja\",\n \"outshellElectrons\": ",
"end": 19480,
"score": 0.5745266079902649,
"start": 19479,
"tag": "NAME",
"value": "N"
},
{
"context": " \"'Vanadis' is another name for the Nordic goddess Freyja\",\n \"outshellElectrons\": 5,\n \"period\": 4",
"end": 19500,
"score": 0.9804862141609192,
"start": 19494,
"tag": "NAME",
"value": "Freyja"
},
{
"context": " \"boilingpoint\": 2945.0,\n \"discoverers\": \"Nicholas Louis Vauquelin\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 19810,
"score": 0.9998175501823425,
"start": 19786,
"tag": "NAME",
"value": "Nicholas Louis Vauquelin"
},
{
"context": "ostCommonIsotopeMass\": 51.9405075,\n \"name\": \"Chromium\",\n \"nameOrigin\": \"Greek 'chroma' means 'colo",
"end": 20300,
"score": 0.9512695670127869,
"start": 20292,
"tag": "NAME",
"value": "Chromium"
},
{
"context": " \"boilingpoint\": 2235.0,\n \"discoverers\": \"C. W. Scheele\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 20652,
"score": 0.9998087286949158,
"start": 20639,
"tag": "NAME",
"value": "C. W. Scheele"
},
{
"context": "ostCommonIsotopeMass\": 54.9380451,\n \"name\": \"Manganese\",\n \"nameOrigin\": \"It was discovered ",
"end": 21133,
"score": 0.7703796029090881,
"start": 21132,
"tag": "NAME",
"value": "M"
},
{
"context": "ommonIsotopeMass\": 54.9380451,\n \"name\": \"Manganese\",\n \"nameOrigin\": \"It was discovered near a t",
"end": 21141,
"score": 0.5061619877815247,
"start": 21136,
"tag": "NAME",
"value": "anese"
},
{
"context": "amed Magnesia in black earth. Thus, it was named 'magnesia nigra', or for short, Manganese.\",\n \"outsh",
"end": 21252,
"score": 0.6987395286560059,
"start": 21246,
"tag": "NAME",
"value": "magnes"
},
{
"context": "nesia in black earth. Thus, it was named 'magnesia nigra', or for short, Manganese.\",\n \"outshellElect",
"end": 21260,
"score": 0.6176938414573669,
"start": 21255,
"tag": "NAME",
"value": "nigra"
},
{
"context": "ostCommonIsotopeMass\": 55.9349375,\n \"name\": \"Iron\",\n \"nameOrigin\": \"Latin 'ferrum'\",\n \"ou",
"end": 22034,
"score": 0.9998005628585815,
"start": 22030,
"tag": "NAME",
"value": "Iron"
},
{
"context": " \"boilingpoint\": 3143.0,\n \"discoverers\": \"G. Brandt\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 22368,
"score": 0.9998592734336853,
"start": 22359,
"tag": "NAME",
"value": "G. Brandt"
},
{
"context": "mostCommonIsotopeMass\": 58.933195,\n \"name\": \"Cobalt\",\n \"nameOrigin\": \"Named after the German wor",
"end": 22855,
"score": 0.9997617602348328,
"start": 22849,
"tag": "NAME",
"value": "Cobalt"
},
{
"context": " \"nameOrigin\": \"Named after the German word 'Kobold' for 'goblin'\",\n \"outshellElectrons\": 9,\n ",
"end": 22914,
"score": 0.9893336296081543,
"start": 22908,
"tag": "NAME",
"value": "Kobold"
},
{
"context": " \"boilingpoint\": 3005.0,\n \"discoverers\": \"A. F. Cronstedt\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 23229,
"score": 0.9998325705528259,
"start": 23214,
"tag": "NAME",
"value": "A. F. Cronstedt"
},
{
"context": "ostCommonIsotopeMass\": 57.9353429,\n \"name\": \"Nickel\",\n \"nameOrigin\": \"'Nickel' was the name of a",
"end": 23718,
"score": 0.9997849464416504,
"start": 23712,
"tag": "NAME",
"value": "Nickel"
},
{
"context": "29,\n \"name\": \"Nickel\",\n \"nameOrigin\": \"'Nickel' was the name of a mountain goblin\",\n \"outsh",
"end": 23749,
"score": 0.9998284578323364,
"start": 23743,
"tag": "NAME",
"value": "Nickel"
},
{
"context": "ostCommonIsotopeMass\": 62.9295975,\n \"name\": \"Copper\",\n \"nameOrigin\": \"Greek 'cuprum' for Cypres\"",
"end": 24535,
"score": 0.9996586441993713,
"start": 24529,
"tag": "NAME",
"value": "Copper"
},
{
"context": " \"boilingpoint\": 1180.0,\n \"discoverers\": \"Andreas Marggraf\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 24887,
"score": 0.9999003410339355,
"start": 24871,
"tag": "NAME",
"value": "Andreas Marggraf"
},
{
"context": "ostCommonIsotopeMass\": 63.9291422,\n \"name\": \"Zinc\",\n \"nameOrigin\": \"German 'zinking' for 'roug",
"end": 25368,
"score": 0.9984678030014038,
"start": 25364,
"tag": "NAME",
"value": "Zinc"
},
{
"context": " \"boilingpoint\": 2478.0,\n \"discoverers\": \"P. E. Lecoq de Boisbaudran\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 25764,
"score": 0.9998934864997864,
"start": 25738,
"tag": "NAME",
"value": "P. E. Lecoq de Boisbaudran"
},
{
"context": "ostCommonIsotopeMass\": 68.9255736,\n \"name\": \"Gallium\",\n \"nameOrigin\": \"'Gallia' is an old name fo",
"end": 26256,
"score": 0.998370885848999,
"start": 26249,
"tag": "NAME",
"value": "Gallium"
},
{
"context": "6,\n \"name\": \"Gallium\",\n \"nameOrigin\": \"'Gallia' is an old name for France\",\n \"outshellElect",
"end": 26287,
"score": 0.9951527118682861,
"start": 26281,
"tag": "NAME",
"value": "Gallia"
},
{
"context": " \"boilingpoint\": 3107.0,\n \"discoverers\": \"C. A. Winkler\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 26614,
"score": 0.9998063445091248,
"start": 26601,
"tag": "NAME",
"value": "C. A. Winkler"
},
{
"context": "ostCommonIsotopeMass\": 73.9211778,\n \"name\": \"Germanium\",\n \"nameOrigin\": \"Latin 'germania' is an old",
"end": 27109,
"score": 0.9955668449401855,
"start": 27100,
"tag": "NAME",
"value": "Germanium"
},
{
"context": "ostCommonIsotopeMass\": 74.9215965,\n \"name\": \"Arsenic\",\n \"nameOrigin\": \"Greek 'arsenikos' for 'mal",
"end": 27932,
"score": 0.9898633360862732,
"start": 27925,
"tag": "NAME",
"value": "Arsenic"
},
{
"context": " \"boilingpoint\": 958.0,\n \"discoverers\": \"J. J. Berzelius\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 28298,
"score": 0.9998558163642883,
"start": 28283,
"tag": "NAME",
"value": "J. J. Berzelius"
},
{
"context": "ostCommonIsotopeMass\": 79.9165213,\n \"name\": \"Selenium\",\n \"nameOrigin\": \"Greek 'selena' for 'moon'\"",
"end": 28788,
"score": 0.9706166982650757,
"start": 28780,
"tag": "NAME",
"value": "Selenium"
},
{
"context": " \"boilingpoint\": 331.85,\n \"discoverers\": \"A. J. Balard\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 29142,
"score": 0.9998107552528381,
"start": 29130,
"tag": "NAME",
"value": "A. J. Balard"
},
{
"context": "ostCommonIsotopeMass\": 78.9183371,\n \"name\": \"Bromine\",\n \"nameOrigin\": \"Greek 'bromos' for 'smells",
"end": 29635,
"score": 0.9947540163993835,
"start": 29628,
"tag": "NAME",
"value": "Bromine"
},
{
"context": " \"boilingpoint\": 120.85,\n \"discoverers\": [\"W. Ramsay\", \"M. W. Travers\"],\n \"discoveryCountry\": \"uk",
"end": 29990,
"score": 0.9998909831047058,
"start": 29981,
"tag": "NAME",
"value": "W. Ramsay"
},
{
"context": "int\": 120.85,\n \"discoverers\": [\"W. Ramsay\", \"M. W. Travers\"],\n \"discoveryCountry\": \"uk\",\n \"discove",
"end": 30007,
"score": 0.9998851418495178,
"start": 29994,
"tag": "NAME",
"value": "M. W. Travers"
},
{
"context": "mostCommonIsotopeMass\": 83.911507,\n \"name\": \"Krypton\",\n \"nameOrigin\": \"Greek 'kryptos' for 'hidde",
"end": 30493,
"score": 0.999642550945282,
"start": 30486,
"tag": "NAME",
"value": "Krypton"
},
{
"context": " \"boilingpoint\": 961.0,\n \"discoverers\": [\"Robert W. Bunsen\", \"Gustav R. Kirchhoff\"],\n \"discoveryCountry",
"end": 30848,
"score": 0.9998782277107239,
"start": 30832,
"tag": "NAME",
"value": "Robert W. Bunsen"
},
{
"context": "961.0,\n \"discoverers\": [\"Robert W. Bunsen\", \"Gustav R. Kirchhoff\"],\n \"discoveryCountry\": \"de\",\n \"discove",
"end": 30871,
"score": 0.9998754262924194,
"start": 30852,
"tag": "NAME",
"value": "Gustav R. Kirchhoff"
},
{
"context": "stCommonIsotopeMass\": 84.91178974,\n \"name\": \"Rubidium\",\n \"nameOrigin\": \"Latin 'rubidus' for 'dark ",
"end": 31364,
"score": 0.9936299324035645,
"start": 31356,
"tag": "NAME",
"value": "Rubidium"
},
{
"context": " \"boilingpoint\": 1655.0,\n \"discoverers\": \"H. B. Davy\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 31715,
"score": 0.9998534321784973,
"start": 31705,
"tag": "NAME",
"value": "H. B. Davy"
},
{
"context": "ostCommonIsotopeMass\": 87.9056121,\n \"name\": \"Strontium\",\n \"nameOrigin\": \"Named after the mineral St",
"end": 32202,
"score": 0.9959873557090759,
"start": 32193,
"tag": "NAME",
"value": "Strontium"
},
{
"context": " \"boilingpoint\": 3611.0,\n \"discoverers\": \"Johann Gadolin\",\n \"discoveryCountry\": \"fi\",\n \"discover",
"end": 32563,
"score": 0.9998962879180908,
"start": 32549,
"tag": "NAME",
"value": "Johann Gadolin"
},
{
"context": "ostCommonIsotopeMass\": 88.9058483,\n \"name\": \"Yttrium\",\n \"nameOrigin\": \"Named after the small town",
"end": 33049,
"score": 0.9479631781578064,
"start": 33042,
"tag": "NAME",
"value": "Yttrium"
},
{
"context": " \"boilingpoint\": 4682.0,\n \"discoverers\": \"Martin Heinrich Klaproth\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 33511,
"score": 0.9998906254768372,
"start": 33487,
"tag": "NAME",
"value": "Martin Heinrich Klaproth"
},
{
"context": "ostCommonIsotopeMass\": 89.9047044,\n \"name\": \"Zirconium\",\n \"nameOrigin\": \"Named after the mineral zi",
"end": 34000,
"score": 0.9991391897201538,
"start": 33991,
"tag": "NAME",
"value": "Zirconium"
},
{
"context": " \"boilingpoint\": 5015.0,\n \"discoverers\": \"Ch. Hatchett\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 34352,
"score": 0.9998078346252441,
"start": 34340,
"tag": "NAME",
"value": "Ch. Hatchett"
},
{
"context": "ostCommonIsotopeMass\": 92.9063781,\n \"name\": \"Niobium\",\n \"nameOrigin\": \"Named after Niobe, the dau",
"end": 34836,
"score": 0.9993083477020264,
"start": 34829,
"tag": "NAME",
"value": "Niobium"
},
{
"context": "name\": \"Niobium\",\n \"nameOrigin\": \"Named after Niobe, the daughter of the Greek god Tantalus.\",\n ",
"end": 34877,
"score": 0.9948001503944397,
"start": 34872,
"tag": "NAME",
"value": "Niobe"
},
{
"context": " \"Named after Niobe, the daughter of the Greek god Tantalus.\",\n \"outshellElectrons\": 5,\n \"period\": ",
"end": 34917,
"score": 0.9369238018989563,
"start": 34909,
"tag": "NAME",
"value": "Tantalus"
},
{
"context": " \"boilingpoint\": 4912.0,\n \"discoverers\": \"C. W. Scheele\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 35218,
"score": 0.9998780488967896,
"start": 35205,
"tag": "NAME",
"value": "C. W. Scheele"
},
{
"context": "ostCommonIsotopeMass\": 97.9054082,\n \"name\": \"Molybdenum\",\n \"nameOrigin\": \"This name has Greek roots.",
"end": 35708,
"score": 0.8593718409538269,
"start": 35698,
"tag": "NAME",
"value": "Molybdenum"
},
{
"context": " \"boilingpoint\": 4538.0,\n \"discoverers\": [\"C. Perrier\", \"E. G. Segre\"],\n \"discoveryCountry\": \"it\",",
"end": 36139,
"score": 0.9998745918273926,
"start": 36129,
"tag": "NAME",
"value": "C. Perrier"
},
{
"context": "nt\": 4538.0,\n \"discoverers\": [\"C. Perrier\", \"E. G. Segre\"],\n \"discoveryCountry\": \"it\",\n \"discove",
"end": 36154,
"score": 0.9998714923858643,
"start": 36143,
"tag": "NAME",
"value": "E. G. Segre"
},
{
"context": "mostCommonIsotopeMass\": 96.906365,\n \"name\": \"Technetium\",\n \"nameOrigin\": \"Greek 'technetos' for arti",
"end": 36637,
"score": 0.9986198544502258,
"start": 36627,
"tag": "NAME",
"value": "Technetium"
},
{
"context": " \"boilingpoint\": 4425.0,\n \"discoverers\": \"K. Klaus\",\n \"discoveryCountry\": \"ru\",\n \"discover",
"end": 36988,
"score": 0.9997973442077637,
"start": 36980,
"tag": "NAME",
"value": "K. Klaus"
},
{
"context": "stCommonIsotopeMass\": 101.9043493,\n \"name\": \"Ruthenium\",\n \"nameOrigin\": \"Ruthenia is the old name o",
"end": 37481,
"score": 0.9993646144866943,
"start": 37472,
"tag": "NAME",
"value": "Ruthenium"
},
{
"context": ",\n \"name\": \"Ruthenium\",\n \"nameOrigin\": \"Ruthenia is the old name of Russia\",\n \"outshellElectr",
"end": 37513,
"score": 0.9934096932411194,
"start": 37505,
"tag": "NAME",
"value": "Ruthenia"
},
{
"context": ",\n \"nameOrigin\": \"Ruthenia is the old name of Russia\",\n \"outshellElectrons\": 8,\n \"perio",
"end": 37534,
"score": 0.9483534097671509,
"start": 37533,
"tag": "NAME",
"value": "R"
},
{
"context": " \"boilingpoint\": 3970.0,\n \"discoverers\": \"W. Wollaston\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 37838,
"score": 0.9998714923858643,
"start": 37826,
"tag": "NAME",
"value": "W. Wollaston"
},
{
"context": "ostCommonIsotopeMass\": 102.905504,\n \"name\": \"Rhodium\",\n \"nameOrigin\": \"Greek 'rhodeos' means 'red",
"end": 38330,
"score": 0.9476096630096436,
"start": 38323,
"tag": "NAME",
"value": "Rhodium"
},
{
"context": "ostCommonIsotopeMass\": 105.903486,\n \"name\": \"Palladium\",\n \"nameOrigin\": \"Named after the asteroid P",
"end": 39141,
"score": 0.9994804859161377,
"start": 39132,
"tag": "NAME",
"value": "Palladium"
},
{
"context": "ostCommonIsotopeMass\": 106.905097,\n \"name\": \"Silver\",\n \"nameOrigin\": \"Latin 'argentum' for silve",
"end": 39952,
"score": 0.9997245669364929,
"start": 39946,
"tag": "NAME",
"value": "Silver"
},
{
"context": " \"boilingpoint\": 1040.0,\n \"discoverers\": \"F. Stromeyer\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 40302,
"score": 0.9998828172683716,
"start": 40290,
"tag": "NAME",
"value": "F. Stromeyer"
},
{
"context": "stCommonIsotopeMass\": 113.9033585,\n \"name\": \"Cadmium\",\n \"nameOrigin\": \"Greek 'kadmia' ('Galmei' =",
"end": 40791,
"score": 0.9636352062225342,
"start": 40784,
"tag": "NAME",
"value": "Cadmium"
},
{
"context": " \"boilingpoint\": 2350.0,\n \"discoverers\": [\"F. Reich\", \"H.T. Richter\"],\n \"discoveryCountry\": \"de\"",
"end": 41152,
"score": 0.9998712539672852,
"start": 41144,
"tag": "NAME",
"value": "F. Reich"
},
{
"context": "oint\": 2350.0,\n \"discoverers\": [\"F. Reich\", \"H.T. Richter\"],\n \"discoveryCountry\": \"de\",\n \"discove",
"end": 41168,
"score": 0.9998828768730164,
"start": 41156,
"tag": "NAME",
"value": "H.T. Richter"
},
{
"context": "ostCommonIsotopeMass\": 114.903878,\n \"name\": \"Indium\",\n \"nameOrigin\": \"Named after 'Indigo' becau",
"end": 41663,
"score": 0.9995837211608887,
"start": 41657,
"tag": "NAME",
"value": "Indium"
},
{
"context": "ame\": \"Indium\",\n \"nameOrigin\": \"Named after 'Indigo' because of its blue spectrum\",\n \"outshellEl",
"end": 41706,
"score": 0.9865173101425171,
"start": 41700,
"tag": "NAME",
"value": "Indigo"
},
{
"context": "stCommonIsotopeMass\": 119.9021947,\n \"name\": \"Tin\",\n \"nameOrigin\": \"Latin 'stannum' for tin\",\n",
"end": 42492,
"score": 0.9990804195404053,
"start": 42489,
"tag": "NAME",
"value": "Tin"
},
{
"context": "\n \"name\": \"Tin\",\n \"nameOrigin\": \"Latin 'stannum' for tin\",\n \"outshellElectrons\": 4,\n ",
"end": 42525,
"score": 0.5522059798240662,
"start": 42523,
"tag": "NAME",
"value": "st"
},
{
"context": "stCommonIsotopeMass\": 120.9038157,\n \"name\": \"Antimony\",\n \"nameOrigin\": \"Arabic 'anthos ammonos' fo",
"end": 43304,
"score": 0.9976639747619629,
"start": 43296,
"tag": "NAME",
"value": "Antimony"
},
{
"context": " \"boilingpoint\": 1261.0,\n \"discoverers\": \"Franz Joseph Muller von Reichstein\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 43705,
"score": 0.9998344779014587,
"start": 43671,
"tag": "NAME",
"value": "Franz Joseph Muller von Reichstein"
},
{
"context": "stCommonIsotopeMass\": 129.9062244,\n \"name\": \"Tellurium\",\n \"nameOrigin\": \"Latin 'tellus' or 'telluri",
"end": 44202,
"score": 0.9997933506965637,
"start": 44193,
"tag": "NAME",
"value": "Tellurium"
},
{
"context": " \"boilingpoint\": 457.5,\n \"discoverers\": \"Bernard Courtois\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 44576,
"score": 0.99986332654953,
"start": 44560,
"tag": "NAME",
"value": "Bernard Courtois"
},
{
"context": "ostCommonIsotopeMass\": 126.904473,\n \"name\": \"Iodine\",\n \"nameOrigin\": \"Greek 'ioeides' for 'viole",
"end": 45069,
"score": 0.9997625350952148,
"start": 45063,
"tag": "NAME",
"value": "Iodine"
},
{
"context": " \"boilingpoint\": 165.1,\n \"discoverers\": [\"W. Ramsay\", \"M. W. Travers\"],\n \"discoveryCountry\": \"uk",
"end": 45424,
"score": 0.9998884201049805,
"start": 45415,
"tag": "NAME",
"value": "W. Ramsay"
},
{
"context": "oint\": 165.1,\n \"discoverers\": [\"W. Ramsay\", \"M. W. Travers\"],\n \"discoveryCountry\": \"uk\",\n \"discove",
"end": 45441,
"score": 0.999882698059082,
"start": 45428,
"tag": "NAME",
"value": "M. W. Travers"
},
{
"context": "stCommonIsotopeMass\": 131.9041535,\n \"name\": \"Xenon\",\n \"nameOrigin\": \"Greek 'xenos' for 'foreign",
"end": 45932,
"score": 0.9941389560699463,
"start": 45927,
"tag": "NAME",
"value": "Xenon"
},
{
"context": " \"boilingpoint\": 944.0,\n \"discoverers\": [\"Robert Wilhelm Bunsen\", \"Gustav Robert Kirchhoff\"],\n \"discoveryCou",
"end": 46296,
"score": 0.9998869895935059,
"start": 46275,
"tag": "NAME",
"value": "Robert Wilhelm Bunsen"
},
{
"context": ",\n \"discoverers\": [\"Robert Wilhelm Bunsen\", \"Gustav Robert Kirchhoff\"],\n \"discoveryCountry\": \"de\",\n \"discove",
"end": 46323,
"score": 0.9998739957809448,
"start": 46300,
"tag": "NAME",
"value": "Gustav Robert Kirchhoff"
},
{
"context": "stCommonIsotopeMass\": 132.9054519,\n \"name\": \"Caesium\",\n \"nameOrigin\": \"Latin 'caesius' for 'heave",
"end": 46820,
"score": 0.9990196228027344,
"start": 46813,
"tag": "NAME",
"value": "Caesium"
},
{
"context": " \"boilingpoint\": 2078.0,\n \"discoverers\": \"Humphry Bartholomew Davy\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 47189,
"score": 0.9997726678848267,
"start": 47165,
"tag": "NAME",
"value": "Humphry Bartholomew Davy"
},
{
"context": "stCommonIsotopeMass\": 137.9052472,\n \"name\": \"Barium\",\n \"nameOrigin\": \"Greek 'barys' for 'heavy'\"",
"end": 47679,
"score": 0.9992930889129639,
"start": 47673,
"tag": "NAME",
"value": "Barium"
},
{
"context": " \"boilingpoint\": 3737.0,\n \"discoverers\": \"K. G. Mosander\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 48029,
"score": 0.9998940229415894,
"start": 48015,
"tag": "NAME",
"value": "K. G. Mosander"
},
{
"context": "stCommonIsotopeMass\": 138.9063533,\n \"name\": \"Lanthanum\",\n \"nameOrigin\": \"Greek 'lanthanein' f",
"end": 48515,
"score": 0.7591508030891418,
"start": 48512,
"tag": "NAME",
"value": "Lan"
},
{
"context": " \"boilingpoint\": 3715.0,\n \"discoverers\": [\"J\\u00f6ns Jacob Berzelius\", \"W. Hisinger\", \"M. Klap",
"end": 48924,
"score": 0.9968501329421997,
"start": 48923,
"tag": "NAME",
"value": "J"
},
{
"context": "lingpoint\": 3715.0,\n \"discoverers\": [\"J\\u00f6ns Jacob Berzelius\", \"W. Hisinger\", \"M. Klaproth\"],\n \"discovery",
"end": 48948,
"score": 0.9902293086051941,
"start": 48930,
"tag": "NAME",
"value": "ns Jacob Berzelius"
},
{
"context": " \"discoverers\": [\"J\\u00f6ns Jacob Berzelius\", \"W. Hisinger\", \"M. Klaproth\"],\n \"discoveryDate\": \"1803\",\n",
"end": 48963,
"score": 0.9998852014541626,
"start": 48952,
"tag": "NAME",
"value": "W. Hisinger"
},
{
"context": "s\": [\"J\\u00f6ns Jacob Berzelius\", \"W. Hisinger\", \"M. Klaproth\"],\n \"discoveryDate\": \"1803\",\n \"electron",
"end": 48978,
"score": 0.999891459941864,
"start": 48967,
"tag": "NAME",
"value": "M. Klaproth"
},
{
"context": "stCommonIsotopeMass\": 139.9054387,\n \"name\": \"Cerium\",\n \"nameOrigin\": \"Named after the planetoid ",
"end": 49437,
"score": 0.9992449879646301,
"start": 49431,
"tag": "NAME",
"value": "Cerium"
},
{
"context": " \"boilingpoint\": 3785.0,\n \"discoverers\": \"Carl F. Auer von Welsbach\",\n \"discoveryDate\": \"1885\",\n \"electronA",
"end": 49774,
"score": 0.9998111724853516,
"start": 49749,
"tag": "NAME",
"value": "Carl F. Auer von Welsbach"
},
{
"context": "stCommonIsotopeMass\": 140.9076528,\n \"name\": \"Praseodymium\",\n \"nameOrigin\": \"Greek 'prasinos didymos' f",
"end": 50236,
"score": 0.9990488290786743,
"start": 50224,
"tag": "NAME",
"value": "Praseodymium"
},
{
"context": " \"boilingpoint\": 3347.0,\n \"discoverers\": \"Carl F. Auer von Welsbach\",\n \"discoveryDate\": \"1885\",\n \"electronA",
"end": 50583,
"score": 0.9998907446861267,
"start": 50558,
"tag": "NAME",
"value": "Carl F. Auer von Welsbach"
},
{
"context": "stCommonIsotopeMass\": 141.9077233,\n \"name\": \"Neodymium\",\n \"nameOrigin\": \"Greek 'neos didymos",
"end": 51033,
"score": 0.791795015335083,
"start": 51031,
"tag": "NAME",
"value": "Ne"
},
{
"context": " \"boilingpoint\": 3273.0,\n \"discoverers\": [\"J. A. Marinsky\", \"C. D. Coryell\", \"L. E. Glendenin\"],\n \"dis",
"end": 51371,
"score": 0.9998875856399536,
"start": 51357,
"tag": "NAME",
"value": "J. A. Marinsky"
},
{
"context": " 3273.0,\n \"discoverers\": [\"J. A. Marinsky\", \"C. D. Coryell\", \"L. E. Glendenin\"],\n \"discoveryDate\": \"194",
"end": 51388,
"score": 0.9998831152915955,
"start": 51375,
"tag": "NAME",
"value": "C. D. Coryell"
},
{
"context": "iscoverers\": [\"J. A. Marinsky\", \"C. D. Coryell\", \"L. E. Glendenin\"],\n \"discoveryDate\": \"1945\",\n \"electron",
"end": 51407,
"score": 0.9998877644538879,
"start": 51392,
"tag": "NAME",
"value": "L. E. Glendenin"
},
{
"context": "ostCommonIsotopeMass\": 144.912749,\n \"name\": \"Promethium\",\n \"nameOrigin\": \"Named after the Greek Prom",
"end": 51822,
"score": 0.9997592568397522,
"start": 51812,
"tag": "NAME",
"value": "Promethium"
},
{
"context": " \"boilingpoint\": 2067.0,\n \"discoverers\": \"P. Lecoq de Boisbaudran\",\n \"discoveryDate\": \"1879\",\n \"electronA",
"end": 52222,
"score": 0.9998961091041565,
"start": 52199,
"tag": "NAME",
"value": "P. Lecoq de Boisbaudran"
},
{
"context": "stCommonIsotopeMass\": 151.9197324,\n \"name\": \"Samarium\",\n \"nameOrigin\": \"Named after the mineral Sa",
"end": 52678,
"score": 0.9998343586921692,
"start": 52670,
"tag": "NAME",
"value": "Samarium"
},
{
"context": "ium\",\n \"nameOrigin\": \"Named after the mineral Samarskit\",\n \"outshellElectrons\": 6,\n \"period\": 6",
"end": 52735,
"score": 0.9658102989196777,
"start": 52726,
"tag": "NAME",
"value": "Samarskit"
},
{
"context": " \"boilingpoint\": 1800.0,\n \"discoverers\": \"E. A. Demarcay\",\n \"discoveryDate\": \"1901\",\n \"electronA",
"end": 53005,
"score": 0.9993128180503845,
"start": 52991,
"tag": "NAME",
"value": "E. A. Demarcay"
},
{
"context": "stCommonIsotopeMass\": 152.9212303,\n \"name\": \"Europium\",\n \"nameOrigin\": \"Named after Europe\",\n ",
"end": 53422,
"score": 0.9996509552001953,
"start": 53414,
"tag": "NAME",
"value": "Europium"
},
{
"context": " \"boilingpoint\": 3545.0,\n \"discoverers\": \"Jean de Marignac\",\n \"discoveryDate\": \"1880\",\n \"electronA",
"end": 53736,
"score": 0.9998670220375061,
"start": 53720,
"tag": "NAME",
"value": "Jean de Marignac"
},
{
"context": "stCommonIsotopeMass\": 157.9241039,\n \"name\": \"Gadolinium\",\n \"nameOrigin\": \"Named after the Finnish ch",
"end": 54197,
"score": 0.9995660185813904,
"start": 54187,
"tag": "NAME",
"value": "Gadolinium"
},
{
"context": " \"nameOrigin\": \"Named after the Finnish chemist Johan Gadolin\",\n \"outshellElectrons\": 8,\n \"period\": 6",
"end": 54266,
"score": 0.9974556565284729,
"start": 54253,
"tag": "NAME",
"value": "Johan Gadolin"
},
{
"context": " \"boilingpoint\": 3500.0,\n \"discoverers\": \"K. G. Mosander\",\n \"discoveryDate\": \"1843\",\n \"electronA",
"end": 54537,
"score": 0.999896228313446,
"start": 54523,
"tag": "NAME",
"value": "K. G. Mosander"
},
{
"context": "stCommonIsotopeMass\": 158.9253468,\n \"name\": \"Terbium\",\n \"nameOrigin\": \"Named after the Swedish to",
"end": 54955,
"score": 0.9998590350151062,
"start": 54948,
"tag": "NAME",
"value": "Terbium"
},
{
"context": " \"boilingpoint\": 2840.0,\n \"discoverers\": \"F. E. Lecoq de Boisbaudran\",\n \"discoveryDate\": \"1886\",\n \"electronA",
"end": 55301,
"score": 0.9998986124992371,
"start": 55275,
"tag": "NAME",
"value": "F. E. Lecoq de Boisbaudran"
},
{
"context": "stCommonIsotopeMass\": 163.9291748,\n \"name\": \"Dysprosium\",\n \"nameOrigin\": \"Greek 'dysprositor' for 'd",
"end": 55759,
"score": 0.9995297193527222,
"start": 55749,
"tag": "NAME",
"value": "Dysprosium"
},
{
"context": " \"boilingpoint\": 2968.0,\n \"discoverers\": [\"J. L. Soret\", \"P.T. Cleve\"],\n \"discoveryDate\": \"1878\",\n ",
"end": 56097,
"score": 0.9998705983161926,
"start": 56086,
"tag": "NAME",
"value": "J. L. Soret"
},
{
"context": "t\": 2968.0,\n \"discoverers\": [\"J. L. Soret\", \"P.T. Cleve\"],\n \"discoveryDate\": \"1878\",\n \"electron",
"end": 56111,
"score": 0.9998762011528015,
"start": 56101,
"tag": "NAME",
"value": "P.T. Cleve"
},
{
"context": "stCommonIsotopeMass\": 164.9303221,\n \"name\": \"Holmium\",\n \"nameOrigin\": \"Latin 'holmia' for the old",
"end": 56570,
"score": 0.9996192455291748,
"start": 56563,
"tag": "NAME",
"value": "Holmium"
},
{
"context": " \"boilingpoint\": 3140.0,\n \"discoverers\": \"K. G. Mosander\",\n \"discoveryDate\": \"1843\",\n \"electronA",
"end": 56910,
"score": 0.9998889565467834,
"start": 56896,
"tag": "NAME",
"value": "K. G. Mosander"
},
{
"context": "stCommonIsotopeMass\": 165.9302931,\n \"name\": \"Erbium\",\n \"nameOrigin\": \"Named ofter the Swedish to",
"end": 57365,
"score": 0.9990859627723694,
"start": 57359,
"tag": "NAME",
"value": "Erbium"
},
{
"context": " \"boilingpoint\": 2223.0,\n \"discoverers\": \"P. T. Cleve\",\n \"discoveryDate\": \"1879\",\n \"electronA",
"end": 57752,
"score": 0.9998852014541626,
"start": 57741,
"tag": "NAME",
"value": "P. T. Cleve"
},
{
"context": "stCommonIsotopeMass\": 168.9342133,\n \"name\": \"Thulium\",\n \"nameOrigin\": \"Named after the old name o",
"end": 58211,
"score": 0.9993588328361511,
"start": 58204,
"tag": "NAME",
"value": "Thulium"
},
{
"context": "igin\": \"Named after the old name of Scandinavia, 'Thule'.\",\n \"outshellElectrons\": 13,\n \"period\"",
"end": 58282,
"score": 0.9974273443222046,
"start": 58277,
"tag": "NAME",
"value": "Thule"
},
{
"context": " \"boilingpoint\": 1469.0,\n \"discoverers\": \"J. Ch. Marignac\",\n \"discoveryDate\": \"1878\",\n \"electronA",
"end": 58556,
"score": 0.9998406767845154,
"start": 58541,
"tag": "NAME",
"value": "J. Ch. Marignac"
},
{
"context": "stCommonIsotopeMass\": 173.9388621,\n \"name\": \"Ytterbium\",\n \"nameOrigin\": \"Like Terbium and Gadoliniu",
"end": 58975,
"score": 0.9989790916442871,
"start": 58966,
"tag": "NAME",
"value": "Ytterbium"
},
{
"context": " \"name\": \"Ytterbium\",\n \"nameOrigin\": \"Like Terbium and Gadolinium, this is named after the Swedish t",
"end": 59011,
"score": 0.9198200702667236,
"start": 59004,
"tag": "NAME",
"value": "Terbium"
},
{
"context": "\"Ytterbium\",\n \"nameOrigin\": \"Like Terbium and Gadolinium, this is named after the Swedish town of Ytter",
"end": 59023,
"score": 0.7066283822059631,
"start": 59016,
"tag": "NAME",
"value": "Gadolin"
},
{
"context": "adolinium, this is named after the Swedish town of Ytterby.\",\n \"outshellElectrons\": 14,\n \"period",
"end": 59073,
"score": 0.7627356648445129,
"start": 59068,
"tag": "NAME",
"value": "Ytter"
},
{
"context": " \"boilingpoint\": 3668.0,\n \"discoverers\": [\"Carl F. Auer von Welsbach\", \"G. Urbain\"],\n \"discoveryDate\": \"1907\",\n ",
"end": 59360,
"score": 0.9998801946640015,
"start": 59335,
"tag": "NAME",
"value": "Carl F. Auer von Welsbach"
},
{
"context": " \"discoverers\": [\"Carl F. Auer von Welsbach\", \"G. Urbain\"],\n \"discoveryDate\": \"1907\",\n \"electron",
"end": 59373,
"score": 0.9996927976608276,
"start": 59364,
"tag": "NAME",
"value": "G. Urbain"
},
{
"context": "stCommonIsotopeMass\": 174.9407718,\n \"name\": \"Lutetium\",\n \"nameOrigin\": \"Named after the Roman name",
"end": 59837,
"score": 0.9916862845420837,
"start": 59829,
"tag": "NAME",
"value": "Lutetium"
},
{
"context": "\n \"nameOrigin\": \"Named after the Roman name 'Lutetia' for Paris\",\n \"outshellElectrons\": 15,\n ",
"end": 59896,
"score": 0.9775452613830566,
"start": 59889,
"tag": "NAME",
"value": "Lutetia"
},
{
"context": " \"boilingpoint\": 4875.0,\n \"discoverers\": [\"D. Coster\", \"G. Hevesy\"],\n \"discoveryCountry\": \"dk\",\n ",
"end": 60204,
"score": 0.9998553991317749,
"start": 60195,
"tag": "NAME",
"value": "D. Coster"
},
{
"context": "int\": 4875.0,\n \"discoverers\": [\"D. Coster\", \"G. Hevesy\"],\n \"discoveryCountry\": \"dk\",\n \"discove",
"end": 60217,
"score": 0.99986332654953,
"start": 60208,
"tag": "NAME",
"value": "G. Hevesy"
},
{
"context": "mostCommonIsotopeMass\": 179.94655,\n \"name\": \"Hafnium\",\n \"nameOrigin\": \"'Hafnia' is the old name o",
"end": 60704,
"score": 0.9997255802154541,
"start": 60697,
"tag": "NAME",
"value": "Hafnium"
},
{
"context": "5,\n \"name\": \"Hafnium\",\n \"nameOrigin\": \"'Hafnia' is the old name of Kopenhagen (Denmark)\",\n ",
"end": 60735,
"score": 0.999237060546875,
"start": 60729,
"tag": "NAME",
"value": "Hafnia"
},
{
"context": " \"nameOrigin\": \"'Hafnia' is the old name of Kopenhagen (Denmark)\",\n \"outshellElectrons\": 4,\n \"",
"end": 60766,
"score": 0.6094405651092529,
"start": 60761,
"tag": "NAME",
"value": "hagen"
},
{
"context": " \"boilingpoint\": 5730.0,\n \"discoverers\": \"A. Ekeberg\",\n \"discoveryCountry\": \"se\",\n \"discover",
"end": 61072,
"score": 0.9998208284378052,
"start": 61062,
"tag": "NAME",
"value": "A. Ekeberg"
},
{
"context": "stCommonIsotopeMass\": 180.9479958,\n \"name\": \"Tantalum\",\n \"nameOrigin\": \"Named after the Greek myth",
"end": 61568,
"score": 0.9994123578071594,
"start": 61560,
"tag": "NAME",
"value": "Tantalum"
},
{
"context": " \"nameOrigin\": \"Named after the Greek myth of Tantalos\",\n \"outshellElectrons\": 5,\n \"period\": 6",
"end": 61630,
"score": 0.9989067912101746,
"start": 61622,
"tag": "NAME",
"value": "Tantalos"
},
{
"context": "\": 1.38,\n \"radiusVDW\": 2.2,\n \"symbol\": \"Ta\",\n \"valences\": []\n }, {\n \"atomicNumb",
"end": 61805,
"score": 0.7915531396865845,
"start": 61803,
"tag": "NAME",
"value": "Ta"
},
{
"context": " \"boilingpoint\": 5825.0,\n \"discoverers\": \"C. W. Scheele\",\n \"discoveryCountry\": \"es\",\n \"discover",
"end": 61929,
"score": 0.9998401999473572,
"start": 61916,
"tag": "NAME",
"value": "C. W. Scheele"
},
{
"context": "stCommonIsotopeMass\": 183.9509312,\n \"name\": \"Tungsten\",\n \"nameOrigin\": \"'tung sten' means 'heavy s",
"end": 62423,
"score": 0.9996382594108582,
"start": 62415,
"tag": "NAME",
"value": "Tungsten"
},
{
"context": "wedish. The old name (and thus the symbol 'W') was Wolfram, named after a mineral.\",\n \"outshellEl",
"end": 62535,
"score": 0.7636653184890747,
"start": 62534,
"tag": "NAME",
"value": "W"
},
{
"context": "sh. The old name (and thus the symbol 'W') was Wolfram, named after a mineral.\",\n \"outshellElectron",
"end": 62541,
"score": 0.8103268146514893,
"start": 62537,
"tag": "NAME",
"value": "fram"
},
{
"context": " \"boilingpoint\": 5870.0,\n \"discoverers\": [\"Walter Noddack\", \"Ida Tacke-Noddack\", \"Otto Berg\"],\n \"disco",
"end": 62864,
"score": 0.9998766183853149,
"start": 62850,
"tag": "NAME",
"value": "Walter Noddack"
},
{
"context": " 5870.0,\n \"discoverers\": [\"Walter Noddack\", \"Ida Tacke-Noddack\", \"Otto Berg\"],\n \"discoveryCountry\": \"de\",\n ",
"end": 62885,
"score": 0.9998776912689209,
"start": 62868,
"tag": "NAME",
"value": "Ida Tacke-Noddack"
},
{
"context": "verers\": [\"Walter Noddack\", \"Ida Tacke-Noddack\", \"Otto Berg\"],\n \"discoveryCountry\": \"de\",\n \"discove",
"end": 62898,
"score": 0.9998819231987,
"start": 62889,
"tag": "NAME",
"value": "Otto Berg"
},
{
"context": "stCommonIsotopeMass\": 186.9557531,\n \"name\": \"Rhenium\",\n \"nameOrigin\": \"Named after the German riv",
"end": 63393,
"score": 0.9997368454933167,
"start": 63386,
"tag": "NAME",
"value": "Rhenium"
},
{
"context": " \"boilingpoint\": 5300.0,\n \"discoverers\": \"S. Tennant\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 63767,
"score": 0.9998720288276672,
"start": 63757,
"tag": "NAME",
"value": "S. Tennant"
},
{
"context": "stCommonIsotopeMass\": 191.9614807,\n \"name\": \"Osmium\",\n \"nameOrigin\": \"Greek for 'smell'. Its oxi",
"end": 64260,
"score": 0.9998295307159424,
"start": 64254,
"tag": "NAME",
"value": "Osmium"
},
{
"context": " \"boilingpoint\": 4700.0,\n \"discoverers\": \"S. Tennant\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 64639,
"score": 0.9998747706413269,
"start": 64629,
"tag": "NAME",
"value": "S. Tennant"
},
{
"context": "stCommonIsotopeMass\": 192.9629264,\n \"name\": \"Iridium\",\n \"nameOrigin\": \"Greek 'iris' for 'rainbow'",
"end": 65135,
"score": 0.9996703267097473,
"start": 65128,
"tag": "NAME",
"value": "Iridium"
},
{
"context": " \"boilingpoint\": 4100.0,\n \"discoverers\": \"A. de Ulloa\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 65482,
"score": 0.9998756647109985,
"start": 65471,
"tag": "NAME",
"value": "A. de Ulloa"
},
{
"context": "stCommonIsotopeMass\": 194.9647911,\n \"name\": \"Platinum\",\n \"nameOrigin\": \"Spanish 'platina' means 's",
"end": 65980,
"score": 0.9761908650398254,
"start": 65972,
"tag": "NAME",
"value": "Platinum"
},
{
"context": "stCommonIsotopeMass\": 196.9665687,\n \"name\": \"Gold\",\n \"nameOrigin\": \"Latin 'aurum'. Named after",
"end": 66805,
"score": 0.9997178912162781,
"start": 66801,
"tag": "NAME",
"value": "Gold"
},
{
"context": "\",\n \"nameOrigin\": \"Latin 'aurum'. Named after Aurora, the goddess of sunrise\",\n \"outshellEle",
"end": 66857,
"score": 0.9089922904968262,
"start": 66856,
"tag": "NAME",
"value": "A"
},
{
"context": "ostCommonIsotopeMass\": 201.970643,\n \"name\": \"Mercury\",\n \"nameOrigin\": \"Graeco-Latin 'hydrargyrum'",
"end": 67642,
"score": 0.9992451667785645,
"start": 67635,
"tag": "NAME",
"value": "Mercury"
},
{
"context": " \"boilingpoint\": 1746.0,\n \"discoverers\": \"W. Crookes\",\n \"discoveryCountry\": \"uk\",\n \"discover",
"end": 68009,
"score": 0.9998453855514526,
"start": 67999,
"tag": "NAME",
"value": "W. Crookes"
},
{
"context": "stCommonIsotopeMass\": 204.9744275,\n \"name\": \"Thallium\",\n \"nameOrigin\": \"Greek 'tallos' for 'young ",
"end": 68511,
"score": 0.9993016719818115,
"start": 68503,
"tag": "NAME",
"value": "Thallium"
},
{
"context": "stCommonIsotopeMass\": 207.9766521,\n \"name\": \"Lead\",\n \"nameOrigin\": \"Latin 'plumbum' for Lead\",",
"end": 69327,
"score": 0.9995357394218445,
"start": 69323,
"tag": "NAME",
"value": "Lead"
},
{
"context": ": \"Lead\",\n \"nameOrigin\": \"Latin 'plumbum' for Lead\",\n \"outshellElectrons\": 4,\n \"period\": 6",
"end": 69375,
"score": 0.9733991622924805,
"start": 69371,
"tag": "NAME",
"value": "Lead"
},
{
"context": "stCommonIsotopeMass\": 208.9803987,\n \"name\": \"Bismuth\",\n \"nameOrigin\": \"The old name of Bismuth is",
"end": 70145,
"score": 0.9997254014015198,
"start": 70138,
"tag": "NAME",
"value": "Bismuth"
},
{
"context": "\": \"Bismuth\",\n \"nameOrigin\": \"The old name of Bismuth is 'Wismut', which stood for 'white mass'.\",\n ",
"end": 70192,
"score": 0.999468982219696,
"start": 70185,
"tag": "NAME",
"value": "Bismuth"
},
{
"context": "\n \"nameOrigin\": \"The old name of Bismuth is 'Wismut', which stood for 'white mass'.\",\n \"outshell",
"end": 70203,
"score": 0.9997791647911072,
"start": 70197,
"tag": "NAME",
"value": "Wismut"
},
{
"context": "\n \"atomicNumber\": 84,\n \"discoverers\": [\"M. Sklodowska-Curie\", \"P. Curie\"],\n \"discoveryCountry\": \"fr\",\n ",
"end": 70512,
"score": 0.9988887310028076,
"start": 70493,
"tag": "NAME",
"value": "M. Sklodowska-Curie"
},
{
"context": "84,\n \"discoverers\": [\"M. Sklodowska-Curie\", \"P. Curie\"],\n \"discoveryCountry\": \"fr\",\n \"discove",
"end": 70524,
"score": 0.9998026490211487,
"start": 70516,
"tag": "NAME",
"value": "P. Curie"
},
{
"context": "stCommonIsotopeMass\": 208.9824304,\n \"name\": \"Polonium\",\n \"nameOrigin\": \"Named after Poland to hono",
"end": 71019,
"score": 0.9995766282081604,
"start": 71011,
"tag": "NAME",
"value": "Polonium"
},
{
"context": ",\n \"nameOrigin\": \"Named after Poland to honor Marie Curie\",\n \"outshellElectrons\": 6,\n \"period\": 6",
"end": 71082,
"score": 0.9998136758804321,
"start": 71071,
"tag": "NAME",
"value": "Marie Curie"
},
{
"context": " \"boilingpoint\": 610.0,\n \"discoverers\": [\"D. R. Corson\", \"K. R. McKenzie\", \"E. Segre\"],\n \"discovery",
"end": 71351,
"score": 0.9998888969421387,
"start": 71339,
"tag": "NAME",
"value": "D. R. Corson"
},
{
"context": "t\": 610.0,\n \"discoverers\": [\"D. R. Corson\", \"K. R. McKenzie\", \"E. Segre\"],\n \"discoveryCountry\": \"us\",\n ",
"end": 71369,
"score": 0.9998906254768372,
"start": 71355,
"tag": "NAME",
"value": "K. R. McKenzie"
},
{
"context": "discoverers\": [\"D. R. Corson\", \"K. R. McKenzie\", \"E. Segre\"],\n \"discoveryCountry\": \"us\",\n \"discove",
"end": 71381,
"score": 0.9998795390129089,
"start": 71373,
"tag": "NAME",
"value": "E. Segre"
},
{
"context": "ostCommonIsotopeMass\": 209.987148,\n \"name\": \"Astatine\",\n \"nameOrigin\": \"Greek 'astator' for 'chang",
"end": 71870,
"score": 0.9995393753051758,
"start": 71862,
"tag": "NAME",
"value": "Astatine"
},
{
"context": " \"boilingpoint\": 211.4,\n \"discoverers\": \"E. Dorn\",\n \"discoveryCountry\": \"de\",\n \"discover",
"end": 72187,
"score": 0.9998602271080017,
"start": 72180,
"tag": "NAME",
"value": "E. Dorn"
},
{
"context": "ostCommonIsotopeMass\": 210.990601,\n \"name\": \"Radon\",\n \"nameOrigin\": \"Named after Radium. It end",
"end": 72639,
"score": 0.9997667074203491,
"start": 72634,
"tag": "NAME",
"value": "Radon"
},
{
"context": " \"boilingpoint\": 950.0,\n \"discoverers\": \"M. Perey\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 73034,
"score": 0.9997888803482056,
"start": 73026,
"tag": "NAME",
"value": "M. Perey"
},
{
"context": "stCommonIsotopeMass\": 223.0197359,\n \"name\": \"Francium\",\n \"nameOrigin\": \"Named after France to hono",
"end": 73485,
"score": 0.9997275471687317,
"start": 73477,
"tag": "NAME",
"value": "Francium"
},
{
"context": " \"boilingpoint\": 1413.0,\n \"discoverers\": [\"M. Sklodowska-Curie\", \"P. Curie\"],\n \"discoveryCountry\": \"fr\",\n ",
"end": 73829,
"score": 0.9998675584793091,
"start": 73810,
"tag": "NAME",
"value": "M. Sklodowska-Curie"
},
{
"context": ".0,\n \"discoverers\": [\"M. Sklodowska-Curie\", \"P. Curie\"],\n \"discoveryCountry\": \"fr\",\n \"discove",
"end": 73841,
"score": 0.9998876452445984,
"start": 73833,
"tag": "NAME",
"value": "P. Curie"
},
{
"context": "stCommonIsotopeMass\": 223.0185022,\n \"name\": \"Radium\",\n \"nameOrigin\": \"Latin 'radius' for 'beam',",
"end": 74293,
"score": 0.8960884809494019,
"start": 74287,
"tag": "NAME",
"value": "Radium"
},
{
"context": " \"boilingpoint\": 3470.0,\n \"discoverers\": \"A. L. Debierne\",\n \"discoveryCountry\": \"fr\",\n \"discover",
"end": 74634,
"score": 0.9998931884765625,
"start": 74620,
"tag": "NAME",
"value": "A. L. Debierne"
},
{
"context": "stCommonIsotopeMass\": 227.0277521,\n \"name\": \"Actinium\",\n \"nameOrigin\": \"Greek 'aktis' for 'beam' -",
"end": 75089,
"score": 0.9992966055870056,
"start": 75081,
"tag": "NAME",
"value": "Actinium"
},
{
"context": " \"boilingpoint\": 5060.0,\n \"discoverers\": \"J. J. Berzelius\",\n \"discoveryDate\": \"1828\",\n \"electrone",
"end": 75434,
"score": 0.9996126890182495,
"start": 75419,
"tag": "NAME",
"value": "J. J. Berzelius"
},
{
"context": "stCommonIsotopeMass\": 232.0380553,\n \"name\": \"Thorium\",\n \"nameOrigin\": \"Named after the German god",
"end": 75860,
"score": 0.9988473057746887,
"start": 75853,
"tag": "NAME",
"value": "Thorium"
},
{
"context": "meOrigin\": \"Named after the German god of thunder: Thor\",\n \"outshellElectrons\": 4,\n \"period\": 7",
"end": 75927,
"score": 0.998898446559906,
"start": 75923,
"tag": "NAME",
"value": "Thor"
},
{
"context": " \"boilingpoint\": 4300.0,\n \"discoverers\": [\"O. Hahn\", \"L. Meitern\", \"W. Wollaston\"],\n \"discovery",
"end": 76191,
"score": 0.9998858571052551,
"start": 76184,
"tag": "NAME",
"value": "O. Hahn"
},
{
"context": "point\": 4300.0,\n \"discoverers\": [\"O. Hahn\", \"L. Meitern\", \"W. Wollaston\"],\n \"discoveryDate\": \"1917\",",
"end": 76205,
"score": 0.9998785257339478,
"start": 76195,
"tag": "NAME",
"value": "L. Meitern"
},
{
"context": ",\n \"discoverers\": [\"O. Hahn\", \"L. Meitern\", \"W. Wollaston\"],\n \"discoveryDate\": \"1917\",\n \"electron",
"end": 76221,
"score": 0.9998707175254822,
"start": 76209,
"tag": "NAME",
"value": "W. Wollaston"
},
{
"context": " \"boilingpoint\": 4407.0,\n \"discoverers\": \"M. M. Klaproth\",\n \"discoveryDate\": \"1789\",\n \"electrone",
"end": 77032,
"score": 0.9998864531517029,
"start": 77018,
"tag": "NAME",
"value": "M. M. Klaproth"
},
{
"context": "stCommonIsotopeMass\": 238.0507882,\n \"name\": \"Uranium\",\n \"nameOrigin\": \"Greek 'ouranos' for 'heave",
"end": 77462,
"score": 0.7009499669075012,
"start": 77455,
"tag": "NAME",
"value": "Uranium"
},
{
"context": " \"boilingpoint\": 4175.0,\n \"discoverers\": [\"E. M. McMillan\", \"P. Aberson\"],\n \"discoveryDate\": \"1940\",\n ",
"end": 77816,
"score": 0.9998852014541626,
"start": 77802,
"tag": "NAME",
"value": "E. M. McMillan"
},
{
"context": " 4175.0,\n \"discoverers\": [\"E. M. McMillan\", \"P. Aberson\"],\n \"discoveryDate\": \"1940\",\n \"electron",
"end": 77830,
"score": 0.9998902082443237,
"start": 77820,
"tag": "NAME",
"value": "P. Aberson"
},
{
"context": "mostCommonIsotopeMass\": 236.04657,\n \"name\": \"Neptunium\",\n \"nameOrigin\": \"Named after the planet Nep",
"end": 78256,
"score": 0.7020810842514038,
"start": 78247,
"tag": "NAME",
"value": "Neptunium"
},
{
"context": " \"boilingpoint\": 3505.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"E. M. McMillan\", \"J. W. Kennedy\", \"A.C. Wahl\"]",
"end": 78584,
"score": 0.9998911023139954,
"start": 78568,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "505.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"E. M. McMillan\", \"J. W. Kennedy\", \"A.C. Wahl\"],\n \"discovery",
"end": 78602,
"score": 0.9998828172683716,
"start": 78588,
"tag": "NAME",
"value": "E. M. McMillan"
},
{
"context": "overers\": [\"Glenn T. Seaborg\", \"E. M. McMillan\", \"J. W. Kennedy\", \"A.C. Wahl\"],\n \"discoveryDate\": \"1940\",\n ",
"end": 78619,
"score": 0.9998806118965149,
"start": 78606,
"tag": "NAME",
"value": "J. W. Kennedy"
},
{
"context": " T. Seaborg\", \"E. M. McMillan\", \"J. W. Kennedy\", \"A.C. Wahl\"],\n \"discoveryDate\": \"1940\",\n \"electron",
"end": 78632,
"score": 0.9998840689659119,
"start": 78623,
"tag": "NAME",
"value": "A.C. Wahl"
},
{
"context": "stCommonIsotopeMass\": 238.0495599,\n \"name\": \"Plutonium\",\n \"nameOrigin\": \"Named after the pla",
"end": 79048,
"score": 0.8208580017089844,
"start": 79046,
"tag": "NAME",
"value": "Pl"
},
{
"context": " \"boilingpoint\": 2880.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"L. O. Morgan\", \"R. A. James\", \"A. Ghiors\"],\n ",
"end": 79381,
"score": 0.9998897314071655,
"start": 79365,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "880.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"L. O. Morgan\", \"R. A. James\", \"A. Ghiors\"],\n \"discoveryDa",
"end": 79397,
"score": 0.9998837113380432,
"start": 79385,
"tag": "NAME",
"value": "L. O. Morgan"
},
{
"context": "scoverers\": [\"Glenn T. Seaborg\", \"L. O. Morgan\", \"R. A. James\", \"A. Ghiors\"],\n \"discoveryDate\": \"1945\",\n ",
"end": 79412,
"score": 0.9998871088027954,
"start": 79401,
"tag": "NAME",
"value": "R. A. James"
},
{
"context": "lenn T. Seaborg\", \"L. O. Morgan\", \"R. A. James\", \"A. Ghiors\"],\n \"discoveryDate\": \"1945\",\n \"electron",
"end": 79425,
"score": 0.9998883008956909,
"start": 79416,
"tag": "NAME",
"value": "A. Ghiors"
},
{
"context": "stCommonIsotopeMass\": 241.0568291,\n \"name\": \"Americium\",\n \"nameOrigin\": \"Named after America.\"",
"end": 79847,
"score": 0.834192156791687,
"start": 79843,
"tag": "NAME",
"value": "Amer"
},
{
"context": " \"boilingpoint\": 3383.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"R. A. James\", \"A. Ghiors\"],\n \"discoveryDa",
"end": 80169,
"score": 0.9998975992202759,
"start": 80153,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "383.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"R. A. James\", \"A. Ghiors\"],\n \"discoveryDate\": \"1944\",\n ",
"end": 80184,
"score": 0.9998959302902222,
"start": 80173,
"tag": "NAME",
"value": "R. A. James"
},
{
"context": "iscoverers\": [\"Glenn T. Seaborg\", \"R. A. James\", \"A. Ghiors\"],\n \"discoveryDate\": \"1944\",\n \"electron",
"end": 80197,
"score": 0.9998936653137207,
"start": 80188,
"tag": "NAME",
"value": "A. Ghiors"
},
{
"context": "stCommonIsotopeMass\": 243.0613891,\n \"name\": \"Curium\",\n \"nameOrigin\": \"Named after Marie Curie.\",",
"end": 80624,
"score": 0.9998026490211487,
"start": 80618,
"tag": "NAME",
"value": "Curium"
},
{
"context": "\"name\": \"Curium\",\n \"nameOrigin\": \"Named after Marie Curie.\",\n \"outshellElectrons\": 8,\n \"period\": ",
"end": 80671,
"score": 0.9998712539672852,
"start": 80660,
"tag": "NAME",
"value": "Marie Curie"
},
{
"context": " \"boilingpoint\": 983.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"A. Ghiors\", \"S. G. Thompson\"],\n \"discover",
"end": 80943,
"score": 0.9998998641967773,
"start": 80927,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "983.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"A. Ghiors\", \"S. G. Thompson\"],\n \"discoveryDate\": \"1949",
"end": 80956,
"score": 0.9998957514762878,
"start": 80947,
"tag": "NAME",
"value": "A. Ghiors"
},
{
"context": "\"discoverers\": [\"Glenn T. Seaborg\", \"A. Ghiors\", \"S. G. Thompson\"],\n \"discoveryDate\": \"1949\",\n \"electron",
"end": 80974,
"score": 0.9998970031738281,
"start": 80960,
"tag": "NAME",
"value": "S. G. Thompson"
},
{
"context": "ostCommonIsotopeMass\": 247.070307,\n \"name\": \"Berkelium\",\n \"nameOrigin\": \"Named after the town Berke",
"end": 81399,
"score": 0.999873161315918,
"start": 81390,
"tag": "NAME",
"value": "Berkelium"
},
{
"context": " \"boilingpoint\": 1173.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"A. Ghiors\", \"S. G. Thompson\"],\n \"discover",
"end": 81749,
"score": 0.9998875856399536,
"start": 81733,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "173.0,\n \"discoverers\": [\"Glenn T. Seaborg\", \"A. Ghiors\", \"S. G. Thompson\"],\n \"discoveryDate\": \"1950",
"end": 81762,
"score": 0.9998906850814819,
"start": 81753,
"tag": "NAME",
"value": "A. Ghiors"
},
{
"context": "\"discoverers\": [\"Glenn T. Seaborg\", \"A. Ghiors\", \"S. G. Thompson\"],\n \"discoveryDate\": \"1950\",\n \"electron",
"end": 81780,
"score": 0.999850869178772,
"start": 81766,
"tag": "NAME",
"value": "S. G. Thompson"
},
{
"context": "stCommonIsotopeMass\": 249.0748535,\n \"name\": \"Californium\",\n \"nameOrigin\": \"Named after the US-State o",
"end": 82209,
"score": 0.9998253583908081,
"start": 82198,
"tag": "NAME",
"value": "Californium"
},
{
"context": "\n \"atomicNumber\": 99,\n \"discoverers\": [\"Glenn T. Seaborg\", \"et al.\"],\n \"discoveryDate\": \"1952\",\n ",
"end": 82515,
"score": 0.9998730421066284,
"start": 82499,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "mostCommonIsotopeMass\": 252.08298,\n \"name\": \"Einsteinium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 82948,
"score": 0.9998745322227478,
"start": 82937,
"tag": "NAME",
"value": "Einsteinium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Albert Einstein.\",\n \"outshellElectrons\": 11,\n \"period\":",
"end": 83013,
"score": 0.9998504519462585,
"start": 82998,
"tag": "NAME",
"value": "Albert Einstein"
},
{
"context": " \"atomicNumber\": 100,\n \"discoverers\": [\"Glenn T. Seaborg\", \"et al.\"],\n \"discoveryDate\": \"1953\",\n ",
"end": 83258,
"score": 0.9998788833618164,
"start": 83242,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": "ostCommonIsotopeMass\": 257.095105,\n \"name\": \"Fermium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 83688,
"score": 0.999862015247345,
"start": 83681,
"tag": "NAME",
"value": "Fermium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Enrico Fermi.\",\n \"outshellElectrons\": 12,\n \"period\":",
"end": 83750,
"score": 0.9994381070137024,
"start": 83738,
"tag": "NAME",
"value": "Enrico Fermi"
},
{
"context": " \"atomicNumber\": 101,\n \"discoverers\": [\"Glenn T. Seaborg\", \"Albert Ghiorso\", \"Bernard Harvey\", \"Gregory Ch",
"end": 83995,
"score": 0.9998857975006104,
"start": 83979,
"tag": "NAME",
"value": "Glenn T. Seaborg"
},
{
"context": ": 101,\n \"discoverers\": [\"Glenn T. Seaborg\", \"Albert Ghiorso\", \"Bernard Harvey\", \"Gregory Choppin\", \"Stanley G",
"end": 84013,
"score": 0.9998787045478821,
"start": 83999,
"tag": "NAME",
"value": "Albert Ghiorso"
},
{
"context": "overers\": [\"Glenn T. Seaborg\", \"Albert Ghiorso\", \"Bernard Harvey\", \"Gregory Choppin\", \"Stanley G. Thompson\"],\n ",
"end": 84031,
"score": 0.9998804330825806,
"start": 84017,
"tag": "NAME",
"value": "Bernard Harvey"
},
{
"context": "T. Seaborg\", \"Albert Ghiorso\", \"Bernard Harvey\", \"Gregory Choppin\", \"Stanley G. Thompson\"],\n \"discoveryDate\": ",
"end": 84050,
"score": 0.9998776912689209,
"start": 84035,
"tag": "NAME",
"value": "Gregory Choppin"
},
{
"context": "t Ghiorso\", \"Bernard Harvey\", \"Gregory Choppin\", \"Stanley G. Thompson\"],\n \"discoveryDate\": \"1955\",\n \"electron",
"end": 84073,
"score": 0.9998707175254822,
"start": 84054,
"tag": "NAME",
"value": "Stanley G. Thompson"
},
{
"context": "ostCommonIsotopeMass\": 258.098431,\n \"name\": \"Mendelevium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 84498,
"score": 0.9983595013618469,
"start": 84487,
"tag": "NAME",
"value": "Mendelevium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist D.I. Mendeleev.\",\n \"outshellElectrons\": 13,\n \"period\": 7,",
"end": 84562,
"score": 0.9776992797851562,
"start": 84548,
"tag": "NAME",
"value": "D.I. Mendeleev"
},
{
"context": "mostCommonIsotopeMass\": 259.10103,\n \"name\": \"Nobelium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 85185,
"score": 0.9998278617858887,
"start": 85177,
"tag": "NAME",
"value": "Nobelium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Alfred Nobel.\",\n \"outshellElectrons\": 14,\n \"period\":",
"end": 85247,
"score": 0.999860942363739,
"start": 85235,
"tag": "NAME",
"value": "Alfred Nobel"
},
{
"context": " \"atomicNumber\": 103,\n \"discoverers\": [\"Albert Ghiorso\", \"Torbjorn Sikkeland\", \"Almon Larsh\", \"Robert M.",
"end": 85490,
"score": 0.999890148639679,
"start": 85476,
"tag": "NAME",
"value": "Albert Ghiorso"
},
{
"context": "r\": 103,\n \"discoverers\": [\"Albert Ghiorso\", \"Torbjorn Sikkeland\", \"Almon Larsh\", \"Robert M. Latimer\"],\n \"dis",
"end": 85512,
"score": 0.9998842477798462,
"start": 85494,
"tag": "NAME",
"value": "Torbjorn Sikkeland"
},
{
"context": "erers\": [\"Albert Ghiorso\", \"Torbjorn Sikkeland\", \"Almon Larsh\", \"Robert M. Latimer\"],\n \"discoveryDate\": \"1",
"end": 85527,
"score": 0.9998762011528015,
"start": 85516,
"tag": "NAME",
"value": "Almon Larsh"
},
{
"context": "t Ghiorso\", \"Torbjorn Sikkeland\", \"Almon Larsh\", \"Robert M. Latimer\"],\n \"discoveryDate\": \"1961\",\n \"electron",
"end": 85548,
"score": 0.9998824000358582,
"start": 85531,
"tag": "NAME",
"value": "Robert M. Latimer"
},
{
"context": "mostCommonIsotopeMass\": 262.10963,\n \"name\": \"Lawrencium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 85933,
"score": 0.9997849464416504,
"start": 85923,
"tag": "NAME",
"value": "Lawrencium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Ernest Orlando Lawrence.\",\n \"outshellElectrons\": 15,\n \"period\":",
"end": 86006,
"score": 0.99986732006073,
"start": 85983,
"tag": "NAME",
"value": "Ernest Orlando Lawrence"
},
{
"context": "mostCommonIsotopeMass\": 267.12153,\n \"name\": \"Rutherfordium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 86605,
"score": 0.9998208284378052,
"start": 86592,
"tag": "NAME",
"value": "Rutherfordium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Ernest Rutherford\",\n \"outshellElectrons\": 2,\n \"period\": 7",
"end": 86672,
"score": 0.9998607039451599,
"start": 86655,
"tag": "NAME",
"value": "Ernest Rutherford"
},
{
"context": "mostCommonIsotopeMass\": 268.12545,\n \"name\": \"Dubnium\",\n \"nameOrigin\": \"Named after the science-to",
"end": 87239,
"score": 0.9997478723526001,
"start": 87232,
"tag": "NAME",
"value": "Dubnium"
},
{
"context": " \"atomicNumber\": 106,\n \"discoverers\": [\"Albert Ghiorso\", \"et al.\"],\n \"discoveryCountry\": [\"ru\", \"us",
"end": 87548,
"score": 0.9998610019683838,
"start": 87534,
"tag": "NAME",
"value": "Albert Ghiorso"
},
{
"context": "mostCommonIsotopeMass\": 271.13347,\n \"name\": \"Seaborgium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 87876,
"score": 0.9997683167457581,
"start": 87866,
"tag": "NAME",
"value": "Seaborgium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist G. Theodore Seaborg.\",\n \"outshellElectrons\": 2,\n \"period\": 7,\n",
"end": 87945,
"score": 0.9521891474723816,
"start": 87926,
"tag": "NAME",
"value": "G. Theodore Seaborg"
},
{
"context": " \"atomicNumber\": 107,\n \"discoverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"d",
"end": 88189,
"score": 0.9998823404312134,
"start": 88173,
"tag": "NAME",
"value": "Peter Armbruster"
},
{
"context": ": 107,\n \"discoverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"discoveryCountry",
"end": 88204,
"score": 0.9997010231018066,
"start": 88193,
"tag": "NAME",
"value": "Gottfried M"
},
{
"context": "coverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"discoveryCountry\": \"ru\",\n ",
"end": 88217,
"score": 0.9657623171806335,
"start": 88210,
"tag": "NAME",
"value": "nzenber"
},
{
"context": "mostCommonIsotopeMass\": 270.13362,\n \"name\": \"Bohrium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 88533,
"score": 0.9998207092285156,
"start": 88526,
"tag": "NAME",
"value": "Bohrium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Niels Bohr.\",\n \"outshellElectrons\": 2,\n \"period\": 7,\n",
"end": 88593,
"score": 0.9826908707618713,
"start": 88583,
"tag": "NAME",
"value": "Niels Bohr"
},
{
"context": " \"atomicNumber\": 108,\n \"discoverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"d",
"end": 88837,
"score": 0.9998890161514282,
"start": 88821,
"tag": "NAME",
"value": "Peter Armbruster"
},
{
"context": ": 108,\n \"discoverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"discoveryCountry",
"end": 88852,
"score": 0.9997292757034302,
"start": 88841,
"tag": "NAME",
"value": "Gottfried M"
},
{
"context": "coverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"discoveryCountry\": \"de\",\n ",
"end": 88865,
"score": 0.9684987664222717,
"start": 88858,
"tag": "NAME",
"value": "nzenber"
},
{
"context": "mostCommonIsotopeMass\": 269.13406,\n \"name\": \"Hassium\",\n \"nameOrigin\": \"Latin 'hassia' for the Ger",
"end": 89181,
"score": 0.9998310208320618,
"start": 89174,
"tag": "NAME",
"value": "Hassium"
},
{
"context": " \"atomicNumber\": 109,\n \"discoverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"d",
"end": 89539,
"score": 0.9998818635940552,
"start": 89523,
"tag": "NAME",
"value": "Peter Armbruster"
},
{
"context": ": 109,\n \"discoverers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"discoveryCountry",
"end": 89554,
"score": 0.9998071193695068,
"start": 89543,
"tag": "NAME",
"value": "Gottfried M"
},
{
"context": "overers\": [\"Peter Armbruster\", \"Gottfried M\\u00fcnzenber\", \"et al.\"],\n \"discoveryCountry\": \"de\",\n ",
"end": 89567,
"score": 0.9995324015617371,
"start": 89561,
"tag": "NAME",
"value": "zenber"
},
{
"context": "mostCommonIsotopeMass\": 278.15481,\n \"name\": \"Meitnerium\",\n \"nameOrigin\": \"Named after the scientist ",
"end": 89887,
"score": 0.9996824860572815,
"start": 89877,
"tag": "NAME",
"value": "Meitnerium"
},
{
"context": "m\",\n \"nameOrigin\": \"Named after the scientist Lise Meitner.\",\n \"outshellElectrons\": 2,\n \"period\": ",
"end": 89949,
"score": 0.998583972454071,
"start": 89937,
"tag": "NAME",
"value": "Lise Meitner"
},
{
"context": " \"atomicNumber\": 110,\n \"discoverers\": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\"",
"end": 90187,
"score": 0.9998761415481567,
"start": 90177,
"tag": "NAME",
"value": "S. Hofmann"
},
{
"context": "umber\": 110,\n \"discoverers\": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger",
"end": 90199,
"score": 0.9998771548271179,
"start": 90191,
"tag": "NAME",
"value": "V. Ninov"
},
{
"context": "\n \"discoverers\": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenbe",
"end": 90219,
"score": 0.9998860359191895,
"start": 90203,
"tag": "NAME",
"value": "F. P. Hessberger"
},
{
"context": ": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"H. ",
"end": 90236,
"score": 0.9998871684074402,
"start": 90223,
"tag": "NAME",
"value": "P. Armbruster"
},
{
"context": "\"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"H. J. Sch\\u00f6t",
"end": 90249,
"score": 0.9998695254325867,
"start": 90240,
"tag": "NAME",
"value": "H. Folger"
},
{
"context": "F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"H. J. Sch\\u00f6tt\", \"et ",
"end": 90257,
"score": 0.9998092651367188,
"start": 90253,
"tag": "NAME",
"value": "G. M"
},
{
"context": "berger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"H. J. Sch\\u00f6tt\", \"et al.\"],\n \"",
"end": 90271,
"score": 0.9986680150032043,
"start": 90263,
"tag": "NAME",
"value": "nzenberg"
},
{
"context": "ter\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"H. J. Sch\\u00f6tt\", \"et al.\"],\n \"discoveryCountry\": \"de",
"end": 90292,
"score": 0.9318493008613586,
"start": 90283,
"tag": "NAME",
"value": "H. J. Sch"
},
{
"context": "r\", \"G. M\\u00fcnzenberg\",\n \"H. J. Sch\\u00f6tt\", \"et al.\"],\n \"discoveryCountry\": \"de\",\n ",
"end": 90300,
"score": 0.9996935725212097,
"start": 90298,
"tag": "NAME",
"value": "tt"
},
{
"context": "mostCommonIsotopeMass\": 281.16206,\n \"name\": \"Darmstadtium\",\n \"nameOrigin\": \"Named after the German cit",
"end": 90622,
"score": 0.997996985912323,
"start": 90610,
"tag": "NAME",
"value": "Darmstadtium"
},
{
"context": " \"atomicNumber\": 111,\n \"discoverers\": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\"",
"end": 90938,
"score": 0.9998518824577332,
"start": 90928,
"tag": "NAME",
"value": "S. Hofmann"
},
{
"context": "umber\": 111,\n \"discoverers\": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger",
"end": 90950,
"score": 0.9998531341552734,
"start": 90942,
"tag": "NAME",
"value": "V. Ninov"
},
{
"context": "\n \"discoverers\": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenbe",
"end": 90970,
"score": 0.9998829364776611,
"start": 90954,
"tag": "NAME",
"value": "F. P. Hessberger"
},
{
"context": ": [\"S. Hofmann\", \"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"et ",
"end": 90987,
"score": 0.9998711347579956,
"start": 90974,
"tag": "NAME",
"value": "P. Armbruster"
},
{
"context": "\"V. Ninov\", \"F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"et al.\"],\n ",
"end": 91000,
"score": 0.9998573660850525,
"start": 90991,
"tag": "NAME",
"value": "H. Folger"
},
{
"context": "F. P. Hessberger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"et al.\"],\n \"discovery",
"end": 91010,
"score": 0.9053317308425903,
"start": 91004,
"tag": "NAME",
"value": "G. M\\u"
},
{
"context": "berger\", \"P. Armbruster\", \"H. Folger\", \"G. M\\u00fcnzenberg\",\n \"et al.\"],\n \"discoveryCountry\": \"d",
"end": 91022,
"score": 0.9991022944450378,
"start": 91014,
"tag": "NAME",
"value": "nzenberg"
},
{
"context": "mostCommonIsotopeMass\": 281.16537,\n \"name\": \"Roentgenium\",\n \"nameOrigin\": \"Named after Wilhelm Conrad",
"end": 91351,
"score": 0.9990469217300415,
"start": 91340,
"tag": "NAME",
"value": "Roentgenium"
},
{
"context": "\": \"Roentgenium\",\n \"nameOrigin\": \"Named after Wilhelm Conrad R\\u00f6ntgen.\",\n \"outshellElectrons\": 2,\n ",
"end": 91403,
"score": 0.9993525743484497,
"start": 91387,
"tag": "NAME",
"value": "Wilhelm Conrad R"
},
{
"context": " \"nameOrigin\": \"Named after Wilhelm Conrad R\\u00f6ntgen.\",\n \"outshellElectrons\": 2,\n \"period\": ",
"end": 91414,
"score": 0.8246622085571289,
"start": 91409,
"tag": "NAME",
"value": "ntgen"
},
{
"context": "mostCommonIsotopeMass\": 285.17411,\n \"name\": \"Copernicium\",\n \"nameOrigin\": \"Historically known as eka-",
"end": 91972,
"score": 0.9745103716850281,
"start": 91961,
"tag": "NAME",
"value": "Copernicium"
},
{
"context": "Other_Metal\",\n \"mass\": 284.0,\n \"name\": \"Ununtrium\",\n \"nameOrigin\": \"Historically known as eka-",
"end": 92622,
"score": 0.9926495552062988,
"start": 92613,
"tag": "NAME",
"value": "Ununtrium"
},
{
"context": "Other_Metal\",\n \"mass\": 289.0,\n \"name\": \"Ununquadium\",\n \"nameOrigin\": \"Historically known as eka-",
"end": 93128,
"score": 0.9924226999282837,
"start": 93117,
"tag": "NAME",
"value": "Ununquadium"
},
{
"context": "Other_Metal\",\n \"mass\": 288.0,\n \"name\": \"Ununpentium\",\n \"nameOrigin\": \"Historically known as eka-",
"end": 93711,
"score": 0.9934114217758179,
"start": 93700,
"tag": "NAME",
"value": "Ununpentium"
},
{
"context": "Other_Metal\",\n \"mass\": 293.0,\n \"name\": \"Ununhexium\",\n \"nameOrigin\": \"Historically known as eka-",
"end": 94210,
"score": 0.9961193203926086,
"start": 94200,
"tag": "NAME",
"value": "Ununhexium"
},
{
"context": " 0.07],\n \"family\": \"Halogen\",\n \"name\": \"Ununseptium\",\n \"nameOrigin\": \"Temporary symbol and name.",
"end": 94559,
"score": 0.9966413378715515,
"start": 94548,
"tag": "NAME",
"value": "Ununseptium"
},
{
"context": ": \"Noblegas\",\n \"mass\": 294.0,\n \"name\": \"Ununoctium\",\n \"nameOrigin\": \"Historically known as eka-",
"end": 95085,
"score": 0.9906585216522217,
"start": 95075,
"tag": "NAME",
"value": "Ununoctium"
}
] | src/core/periodic_table.coffee | mnowotka/elaphe | 0 | define ->
{
"atoms": [{
"atomicNumber": 0,
"elementColor": [0.07, 0.5, 0.7],
"exactMass": 0.0,
"mass": 0.0,
"mostCommonIsotope": "Xx0",
"mostCommonIsotopeMass": 0.0,
"name": "Dummy",
"outshellElectrons": 0,
"rB0": 0.0,
"radiusCovalent": 0.0,
"radiusVDW": 0.0,
"symbol": "Xx",
"valences": []
}, {
"atomicNumber": 1,
"boilingpoint": 20.28,
"discoverers": "C. Cavendish",
"discoveryCountry": "uk",
"discoveryDate": "1766",
"electronAffinity": 0.75420375,
"electronegativityPauling": 2.2,
"electronicConfiguration": "1s1",
"elementColor": [1.0, 1.0, 1.0],
"exactMass": 1.007825032,
"family": "Non-Metal",
"group": 1,
"ionization": 13.5984,
"mass": 1.00794,
"meltingpoint": 14.01,
"mostCommonIsotope": "H1",
"mostCommonIsotopeMass": 1.007825032,
"name": "Hydrogen",
"nameOrigin": "Greek 'hydro' and 'gennao' for 'forms water'",
"outshellElectrons": 1,
"period": 1,
"periodTableBlock": "s",
"rB0": 0.33,
"radiusCovalent": 0.37,
"radiusVDW": 1.2,
"symbol": "H",
"valences": [1]
}, {
"atomicNumber": 2,
"boilingpoint": 4.216,
"discoverers": ["P. J. Janssen", "J. N. Lockyer"],
"discoveryCountry": ["se", "uk"],
"discoveryDate": "1895",
"electronAffinity": 0.0,
"electronicConfiguration": "1s2",
"elementColor": [0.85, 1.0, 1.0],
"exactMass": 4.002603254,
"family": "Noblegas",
"group": 8,
"ionization": 24.5874,
"mass": 4.002602,
"meltingpoint": 0.95,
"mostCommonIsotope": "He4",
"mostCommonIsotopeMass": 4.002603254,
"name": "Helium",
"nameOrigin": "The Greek word for the sun was 'helios'",
"outshellElectrons": 2,
"period": 1,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.32,
"radiusVDW": 1.4,
"symbol": "He",
"valences": [0]
}, {
"atomicNumber": 3,
"boilingpoint": 1615.0,
"discoverers": "A. Arfvedson",
"discoveryCountry": "se",
"discoveryDate": "1817",
"electronAffinity": 0.618049,
"electronegativityPauling": 0.98,
"electronicConfiguration": "He 2s1",
"elementColor": [0.8, 0.5, 1.0],
"exactMass": 7.01600455,
"family": "Alkali_Earth",
"group": 1,
"ionization": 5.3917,
"mass": 6.941,
"meltingpoint": 453.7,
"mostCommonIsotope": "Li7",
"mostCommonIsotopeMass": 7.01600455,
"name": "Lithium",
"nameOrigin": "Greek 'lithos' means 'stone'",
"outshellElectrons": 1,
"period": 2,
"periodTableBlock": "s",
"rB0": 1.23,
"radiusCovalent": 1.34,
"radiusVDW": 2.2,
"symbol": "Li",
"valences": [1]
}, {
"atomicNumber": 4,
"boilingpoint": 3243.0,
"discoverers": "Nicholas Louis Vauquelin",
"discoveryCountry": "fr",
"discoveryDate": "1797",
"electronAffinity": 0.0,
"electronegativityPauling": 1.57,
"electronicConfiguration": "He 2s2",
"elementColor": [0.76, 1.0, 0.0],
"exactMass": 9.0121822,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 9.3227,
"mass": 9.012182,
"meltingpoint": 1560.0,
"mostCommonIsotope": "Be9",
"mostCommonIsotopeMass": 9.0121822,
"name": "Beryllium",
"nameOrigin": "Greek 'beryllos' for 'light-green stone'",
"outshellElectrons": 2,
"period": 2,
"periodTableBlock": "s",
"rB0": 0.9,
"radiusCovalent": 0.9,
"radiusVDW": 1.9,
"symbol": "Be",
"valences": [2]
}, {
"atomicNumber": 5,
"boilingpoint": 4275.0,
"discoverers": ["Louis Joseph Gay-Lussac", "Louis Jacques Thenard"],
"discoveryCountry": ["uk", "fr"],
"discoveryDate": "1808",
"electronAffinity": 0.279723,
"electronegativityPauling": 2.04,
"electronicConfiguration": "He 2s2 2p1",
"elementColor": [1.0, 0.71, 0.71],
"exactMass": 11.0093054,
"family": "Metalloids",
"group": 3,
"ionization": 8.298,
"mass": 10.811,
"meltingpoint": 2365.0,
"mostCommonIsotope": "B11",
"mostCommonIsotopeMass": 11.0093054,
"name": "Boron",
"nameOrigin": "Boron means 'Bor(ax) + (carb)on'. It is found in borax and behaves a lot like carbon",
"outshellElectrons": 3,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.82,
"radiusCovalent": 0.82,
"radiusVDW": 1.8,
"symbol": "B",
"valences": [3]
}, {
"atomicNumber": 6,
"boilingpoint": 5100.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.262118,
"electronegativityPauling": 2.55,
"electronicConfiguration": "He 2s2 2p2",
"elementColor": [0.5, 0.5, 0.5],
"exactMass": 12.0,
"family": "Non-Metal",
"group": 4,
"ionization": 11.2603,
"mass": 12.0107,
"meltingpoint": 3825.0,
"mostCommonIsotope": "C12",
"mostCommonIsotopeMass": 12.0,
"name": "Carbon",
"nameOrigin": "Latin 'carboneum' for carbon",
"outshellElectrons": 4,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.77,
"radiusCovalent": 0.77,
"radiusVDW": 1.7,
"symbol": "C",
"valences": [4]
}, {
"atomicNumber": 7,
"boilingpoint": 77.344,
"discoverers": "D. Rutherford",
"discoveryCountry": "uk",
"discoveryDate": "1772",
"electronAffinity": -0.07,
"electronegativityPauling": 3.04,
"electronicConfiguration": "He 2s2 2p3",
"elementColor": [0.05, 0.05, 1.0],
"exactMass": 14.003074,
"family": "Non-Metal",
"group": 5,
"ionization": 14.5341,
"mass": 14.0067,
"meltingpoint": 63.15,
"mostCommonIsotope": "N14",
"mostCommonIsotopeMass": 14.003074,
"name": "Nitrogen",
"nameOrigin": "Latin 'nitrogenium' ('forms saltpeter')",
"outshellElectrons": 5,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.75,
"radiusVDW": 1.6,
"symbol": "N",
"valences": [3]
}, {
"atomicNumber": 8,
"boilingpoint": 90.188,
"discoverers": "J. Priestley",
"discoveryCountry": ["se", "uk"],
"discoveryDate": "1774",
"electronAffinity": 1.461112,
"electronegativityPauling": 3.44,
"electronicConfiguration": "He 2s2 2p4",
"elementColor": [1.0, 0.05, 0.05],
"exactMass": 15.99491462,
"family": "Non-Metal",
"group": 6,
"ionization": 13.6181,
"mass": 15.9994,
"meltingpoint": 54.8,
"mostCommonIsotope": "O16",
"mostCommonIsotopeMass": 15.99491462,
"name": "Oxygen",
"nameOrigin": "Latin 'oxygenium' (forms acids)",
"outshellElectrons": 6,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.66,
"radiusCovalent": 0.73,
"radiusVDW": 1.55,
"symbol": "O",
"valences": [2]
}, {
"atomicNumber": 9,
"boilingpoint": 85.0,
"discoverers": "H. F. Moissan",
"discoveryCountry": "fr",
"discoveryDate": "1886",
"electronAffinity": 3.4011887,
"electronegativityPauling": 3.98,
"electronicConfiguration": "He 2s2 2p5",
"elementColor": [0.7, 1.0, 1.0],
"exactMass": 18.99840322,
"family": "Halogen",
"group": 7,
"ionization": 17.4228,
"mass": 18.9984032,
"meltingpoint": 53.55,
"mostCommonIsotope": "F19",
"mostCommonIsotopeMass": 18.99840322,
"name": "Fluorine",
"nameOrigin": "Latin 'fluere' ('floats')",
"outshellElectrons": 7,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.611,
"radiusCovalent": 0.71,
"radiusVDW": 1.5,
"symbol": "F",
"valences": [1]
}, {
"atomicNumber": 10,
"boilingpoint": 27.1,
"discoverers": ["W. Ramsay", "M.W. Travers"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronicConfiguration": "He 2s2 2p6",
"elementColor": [0.7, 0.89, 0.96],
"exactMass": 19.99244018,
"family": "Noblegas",
"group": 8,
"ionization": 21.5645,
"mass": 20.1797,
"meltingpoint": 24.55,
"mostCommonIsotope": "Ne20",
"mostCommonIsotopeMass": 19.99244018,
"name": "Neon",
"nameOrigin": "Greek 'neo'. meaning 'new'",
"outshellElectrons": 8,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.69,
"radiusVDW": 1.54,
"symbol": "Ne",
"valences": [0]
}, {
"atomicNumber": 11,
"boilingpoint": 1156.0,
"discoverers": "Sir Humphrey Davy",
"discoveryCountry": "uk",
"discoveryDate": "1807",
"electronAffinity": 0.547926,
"electronegativityPauling": 0.93,
"electronicConfiguration": "Ne 3s1",
"elementColor": [0.67, 0.36, 0.95],
"exactMass": 22.98976928,
"family": "Alkali_Earth",
"group": 1,
"ionization": 5.1391,
"mass": 22.98976928,
"meltingpoint": 371.0,
"mostCommonIsotope": "Na23",
"mostCommonIsotopeMass": 22.98976928,
"name": "Sodium",
"nameOrigin": "Arabic 'natrun' for 'soda'",
"outshellElectrons": 1,
"period": 3,
"periodTableBlock": "s",
"rB0": 1.54,
"radiusCovalent": 1.54,
"radiusVDW": 2.4,
"symbol": "Na",
"valences": [1]
}, {
"atomicNumber": 12,
"boilingpoint": 1380.0,
"discoverers": "H. B. Davy",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.0,
"electronegativityPauling": 1.31,
"electronicConfiguration": "Ne 3s2",
"elementColor": [0.54, 1.0, 0.0],
"exactMass": 23.9850417,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 7.6462,
"mass": 24.305,
"meltingpoint": 922.0,
"mostCommonIsotope": "Mg24",
"mostCommonIsotopeMass": 23.9850417,
"name": "Magnesium",
"nameOrigin": "Named after the city of Magnesia",
"outshellElectrons": 2,
"period": 3,
"periodTableBlock": "s",
"rB0": 1.36,
"radiusCovalent": 1.3,
"radiusVDW": 2.2,
"symbol": "Mg",
"valences": [2]
}, {
"atomicNumber": 13,
"boilingpoint": 2740.0,
"discoverers": "H. Ch. Oersted",
"discoveryCountry": "dk",
"discoveryDate": "1825",
"electronAffinity": 0.43283,
"electronegativityPauling": 1.61,
"electronicConfiguration": "Ne 3s2 3p1",
"elementColor": [0.75, 0.65, 0.65],
"exactMass": 26.98153863,
"family": "Other_Metal",
"group": 3,
"ionization": 5.9858,
"mass": 26.9815386,
"meltingpoint": 933.5,
"mostCommonIsotope": "Al27",
"mostCommonIsotopeMass": 26.98153863,
"name": "Aluminium",
"nameOrigin": "Latin 'alumen'",
"outshellElectrons": 3,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.18,
"radiusCovalent": 1.18,
"radiusVDW": 2.1,
"symbol": "Al",
"valences": [6]
}, {
"atomicNumber": 14,
"boilingpoint": 2630.0,
"discoverers": "J. J. Berzelius",
"discoveryCountry": "se",
"discoveryDate": "1823",
"electronAffinity": 1.389521,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Ne 3s2 3p2",
"elementColor": [0.5, 0.6, 0.6],
"exactMass": 27.97692653,
"family": "Metalloids",
"group": 4,
"ionization": 8.1517,
"mass": 28.0855,
"meltingpoint": 1683.0,
"mostCommonIsotope": "Si28",
"mostCommonIsotopeMass": 27.97692653,
"name": "Silicon",
"nameOrigin": "Latin 'silex'",
"outshellElectrons": 4,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.937,
"radiusCovalent": 1.11,
"radiusVDW": 2.1,
"symbol": "Si",
"valences": [4, 6]
}, {
"atomicNumber": 15,
"boilingpoint": 553.0,
"discoverers": "H. Brandt",
"discoveryCountry": "de",
"discoveryDate": "1669",
"electronAffinity": 0.7465,
"electronegativityPauling": 2.19,
"electronicConfiguration": "Ne 3s2 3p3",
"elementColor": [1.0, 0.5, 0.0],
"exactMass": 30.97376163,
"family": "Non-Metal",
"group": 5,
"ionization": 10.4867,
"mass": 30.973762,
"meltingpoint": 317.3,
"mostCommonIsotope": "P31",
"mostCommonIsotopeMass": 30.97376163,
"name": "Phosphorus",
"nameOrigin": "Greek 'phosphoros' for 'carries light'",
"outshellElectrons": 5,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.89,
"radiusCovalent": 1.06,
"radiusVDW": 1.95,
"symbol": "P",
"valences": [3, 5, 7]
}, {
"atomicNumber": 16,
"boilingpoint": 717.82,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 2.0771029,
"electronegativityPauling": 2.58,
"electronicConfiguration": "Ne 3s2 3p4",
"elementColor": [1.0, 1.0, 0.19],
"exactMass": 31.972071,
"family": "Non-Metal",
"group": 6,
"ionization": 10.36,
"mass": 32.065,
"meltingpoint": 392.2,
"mostCommonIsotope": "S32",
"mostCommonIsotopeMass": 31.972071,
"name": "Sulfur",
"nameOrigin": "In sanskrit 'sweb' means 'to sleep'",
"outshellElectrons": 6,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.04,
"radiusCovalent": 1.02,
"radiusVDW": 1.8,
"symbol": "S",
"valences": [2, 4, 6]
}, {
"atomicNumber": 17,
"boilingpoint": 239.18,
"discoverers": "C. W. Scheele",
"discoveryCountry": "se",
"discoveryDate": "1774",
"electronAffinity": 3.612724,
"electronegativityPauling": 3.16,
"electronicConfiguration": "Ne 3s2 3p5",
"elementColor": [0.12, 0.94, 0.12],
"exactMass": 34.96885268,
"family": "Halogen",
"group": 7,
"ionization": 12.9676,
"mass": 35.453,
"meltingpoint": 172.17,
"mostCommonIsotope": "Cl35",
"mostCommonIsotopeMass": 34.96885268,
"name": "Chlorine",
"nameOrigin": "Greek 'chloros' for 'yellow-green'",
"outshellElectrons": 7,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.997,
"radiusCovalent": 0.99,
"radiusVDW": 1.8,
"symbol": "Cl",
"valences": [1]
}, {
"atomicNumber": 18,
"boilingpoint": 87.45,
"discoverers": ["W. Ramsay", "J. Rayleigh"],
"discoveryCountry": "uk",
"discoveryDate": "1894",
"electronAffinity": 0.0,
"electronicConfiguration": "Ne 3s2 3p6",
"elementColor": [0.5, 0.82, 0.89],
"exactMass": 39.96238312,
"family": "Noblegas",
"group": 8,
"ionization": 15.7596,
"mass": 39.948,
"meltingpoint": 83.95,
"mostCommonIsotope": "Ar40",
"mostCommonIsotopeMass": 39.96238312,
"name": "Argon",
"nameOrigin": "Greek 'aergon' for 'inactive'",
"outshellElectrons": 8,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.74,
"radiusCovalent": 0.97,
"radiusVDW": 1.88,
"symbol": "Ar",
"valences": [0]
}, {
"atomicNumber": 19,
"boilingpoint": 1033.0,
"discoverers": "H. B. Davy",
"discoveryCountry": "uk",
"discoveryDate": "1807",
"electronAffinity": 0.501459,
"electronegativityPauling": 0.82,
"electronicConfiguration": "Ar 4s1",
"elementColor": [0.56, 0.25, 0.83],
"exactMass": 38.96370668,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.3407,
"mass": 39.0983,
"meltingpoint": 336.8,
"mostCommonIsotope": "K39",
"mostCommonIsotopeMass": 38.96370668,
"name": "Potassium",
"nameOrigin": "Arabic 'al qaliy' for potash",
"outshellElectrons": 1,
"period": 4,
"periodTableBlock": "s",
"rB0": 2.03,
"radiusCovalent": 1.96,
"radiusVDW": 2.8,
"symbol": "K",
"valences": [1]
}, {
"atomicNumber": 20,
"boilingpoint": 1757.0,
"discoverers": "H. B. Davy",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.02455,
"electronegativityPauling": 1.0,
"electronicConfiguration": "Ar 4s2",
"elementColor": [0.24, 1.0, 0.0],
"exactMass": 39.96259098,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 6.1132,
"mass": 40.078,
"meltingpoint": 1112.0,
"mostCommonIsotope": "Ca40",
"mostCommonIsotopeMass": 39.96259098,
"name": "Calcium",
"nameOrigin": "Latin 'calx' for 'lime'",
"outshellElectrons": 2,
"period": 4,
"periodTableBlock": "s",
"rB0": 1.74,
"radiusCovalent": 1.74,
"radiusVDW": 2.4,
"symbol": "Ca",
"valences": [2]
}, {
"atomicNumber": 21,
"boilingpoint": 3109.0,
"discoverers": "L. Nilson",
"discoveryCountry": "se",
"discoveryDate": "1879",
"electronAffinity": 0.188,
"electronegativityPauling": 1.36,
"electronicConfiguration": "Ar 3d1 4s2",
"elementColor": [0.9, 0.9, 0.9],
"exactMass": 44.9559119,
"family": "Transition",
"group": 3,
"ionization": 6.5615,
"mass": 44.955912,
"meltingpoint": 1814.0,
"mostCommonIsotope": "Sc45",
"mostCommonIsotopeMass": 44.9559119,
"name": "Scandium",
"nameOrigin": "Named because it was found in Scandinavia",
"outshellElectrons": 3,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.44,
"radiusCovalent": 1.44,
"radiusVDW": 2.3,
"symbol": "Sc",
"valences": []
}, {
"atomicNumber": 22,
"boilingpoint": 3560.0,
"discoverers": "W. Gregor",
"discoveryCountry": "uk",
"discoveryDate": "1791",
"electronAffinity": 0.084,
"electronegativityPauling": 1.54,
"electronicConfiguration": "Ar 3d2 4s2",
"elementColor": [0.75, 0.76, 0.78],
"exactMass": 47.9479463,
"family": "Transition",
"group": 4,
"ionization": 6.8281,
"mass": 47.867,
"meltingpoint": 1935.0,
"mostCommonIsotope": "Ti48",
"mostCommonIsotopeMass": 47.9479463,
"name": "Titanium",
"nameOrigin": "The Titans were giants in Greek mythology",
"outshellElectrons": 4,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.32,
"radiusCovalent": 1.36,
"radiusVDW": 2.15,
"symbol": "Ti",
"valences": []
}, {
"atomicNumber": 23,
"boilingpoint": 3650.0,
"discoverers": "N. Sefstr\u00f6m",
"discoveryCountry": "se",
"discoveryDate": "1830",
"electronAffinity": 0.525,
"electronegativityPauling": 1.63,
"electronicConfiguration": "Ar 3d3 4s2",
"elementColor": [0.65, 0.65, 0.67],
"exactMass": 50.9439595,
"family": "Transition",
"group": 5,
"ionization": 6.7462,
"mass": 50.9415,
"meltingpoint": 2163.0,
"mostCommonIsotope": "V50",
"mostCommonIsotopeMass": 49.9471585,
"name": "Vanadium",
"nameOrigin": "'Vanadis' is another name for the Nordic goddess Freyja",
"outshellElectrons": 5,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.22,
"radiusCovalent": 1.25,
"radiusVDW": 2.05,
"symbol": "V",
"valences": []
}, {
"atomicNumber": 24,
"boilingpoint": 2945.0,
"discoverers": "Nicholas Louis Vauquelin",
"discoveryCountry": "fr",
"discoveryDate": "1797",
"electronAffinity": 0.67584,
"electronegativityPauling": 1.66,
"electronicConfiguration": "Ar 3d5 4s1",
"elementColor": [0.54, 0.6, 0.78],
"exactMass": 51.9405075,
"family": "Transition",
"group": 6,
"ionization": 6.7665,
"mass": 51.9961,
"meltingpoint": 2130.0,
"mostCommonIsotope": "Cr52",
"mostCommonIsotopeMass": 51.9405075,
"name": "Chromium",
"nameOrigin": "Greek 'chroma' means 'color'",
"outshellElectrons": 6,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.18,
"radiusCovalent": 1.27,
"radiusVDW": 2.05,
"symbol": "Cr",
"valences": []
}, {
"atomicNumber": 25,
"boilingpoint": 2235.0,
"discoverers": "C. W. Scheele",
"discoveryCountry": "se",
"discoveryDate": "1774",
"electronAffinity": 0.0,
"electronegativityPauling": 1.55,
"electronicConfiguration": "Ar 3d5 4s2",
"elementColor": [0.61, 0.48, 0.78],
"exactMass": 54.9380451,
"family": "Transition",
"group": 7,
"ionization": 7.434,
"mass": 54.938045,
"meltingpoint": 1518.0,
"mostCommonIsotope": "Mn55",
"mostCommonIsotopeMass": 54.9380451,
"name": "Manganese",
"nameOrigin": "It was discovered near a town named Magnesia in black earth. Thus, it was named 'magnesia nigra', or for short, Manganese.",
"outshellElectrons": 7,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.39,
"radiusVDW": 2.05,
"symbol": "Mn",
"valences": []
}, {
"atomicNumber": 26,
"boilingpoint": 3023.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.151,
"electronegativityPauling": 1.83,
"electronicConfiguration": "Ar 3d6 4s2",
"elementColor": [0.5, 0.48, 0.78],
"exactMass": 55.9349375,
"family": "Transition",
"group": 8,
"ionization": 7.9024,
"mass": 55.845,
"meltingpoint": 1808.0,
"mostCommonIsotope": "Fe56",
"mostCommonIsotopeMass": 55.9349375,
"name": "Iron",
"nameOrigin": "Latin 'ferrum'",
"outshellElectrons": 8,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.25,
"radiusVDW": 2.05,
"symbol": "Fe",
"valences": []
}, {
"atomicNumber": 27,
"boilingpoint": 3143.0,
"discoverers": "G. Brandt",
"discoveryCountry": "se",
"discoveryDate": "1737",
"electronAffinity": 0.6633,
"electronegativityPauling": 1.88,
"electronicConfiguration": "Ar 3d7 4s2",
"elementColor": [0.44, 0.48, 0.78],
"exactMass": 58.933195,
"family": "Transition",
"group": 8,
"ionization": 7.881,
"mass": 58.933195,
"meltingpoint": 1768.0,
"mostCommonIsotope": "Co59",
"mostCommonIsotopeMass": 58.933195,
"name": "Cobalt",
"nameOrigin": "Named after the German word 'Kobold' for 'goblin'",
"outshellElectrons": 9,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.16,
"radiusCovalent": 1.26,
"radiusVDW": 2.0,
"symbol": "Co",
"valences": []
}, {
"atomicNumber": 28,
"boilingpoint": 3005.0,
"discoverers": "A. F. Cronstedt",
"discoveryCountry": "se",
"discoveryDate": "1751",
"electronAffinity": 1.15716,
"electronegativityPauling": 1.91,
"electronicConfiguration": "Ar 3d8 4s2",
"elementColor": [0.36, 0.48, 0.76],
"exactMass": 57.9353429,
"family": "Transition",
"group": 8,
"ionization": 7.6398,
"mass": 58.6934,
"meltingpoint": 1726.0,
"mostCommonIsotope": "Ni58",
"mostCommonIsotopeMass": 57.9353429,
"name": "Nickel",
"nameOrigin": "'Nickel' was the name of a mountain goblin",
"outshellElectrons": 10,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.15,
"radiusCovalent": 1.21,
"radiusVDW": 2.0,
"symbol": "Ni",
"valences": []
}, {
"atomicNumber": 29,
"boilingpoint": 2840.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.23578,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Ar 3d10 4s1",
"elementColor": [1.0, 0.48, 0.38],
"exactMass": 62.9295975,
"family": "Transition",
"group": 1,
"ionization": 7.7264,
"mass": 63.546,
"meltingpoint": 1356.6,
"mostCommonIsotope": "Cu63",
"mostCommonIsotopeMass": 62.9295975,
"name": "Copper",
"nameOrigin": "Greek 'cuprum' for Cypres",
"outshellElectrons": 11,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.38,
"radiusVDW": 2.0,
"symbol": "Cu",
"valences": []
}, {
"atomicNumber": 30,
"boilingpoint": 1180.0,
"discoverers": "Andreas Marggraf",
"discoveryCountry": "de",
"discoveryDate": "1746",
"electronAffinity": 0.0,
"electronegativityPauling": 1.65,
"electronicConfiguration": "Ar 3d10 4s2",
"elementColor": [0.49, 0.5, 0.69],
"exactMass": 63.9291422,
"family": "Transition",
"group": 2,
"ionization": 9.3942,
"mass": 65.38,
"meltingpoint": 692.73,
"mostCommonIsotope": "Zn64",
"mostCommonIsotopeMass": 63.9291422,
"name": "Zinc",
"nameOrigin": "German 'zinking' for 'rough', because zinc ore is very rough",
"outshellElectrons": 2,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.31,
"radiusVDW": 2.1,
"symbol": "Zn",
"valences": []
}, {
"atomicNumber": 31,
"boilingpoint": 2478.0,
"discoverers": "P. E. Lecoq de Boisbaudran",
"discoveryCountry": "fr",
"discoveryDate": "1875",
"electronAffinity": 0.41,
"electronegativityPauling": 1.81,
"electronicConfiguration": "Ar 3d10 4s2 4p1",
"elementColor": [0.76, 0.56, 0.56],
"exactMass": 68.9255736,
"family": "Other_Metal",
"group": 3,
"ionization": 5.9993,
"mass": 69.723,
"meltingpoint": 302.92,
"mostCommonIsotope": "Ga69",
"mostCommonIsotopeMass": 68.9255736,
"name": "Gallium",
"nameOrigin": "'Gallia' is an old name for France",
"outshellElectrons": 3,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.26,
"radiusCovalent": 1.26,
"radiusVDW": 2.1,
"symbol": "Ga",
"valences": [3]
}, {
"atomicNumber": 32,
"boilingpoint": 3107.0,
"discoverers": "C. A. Winkler",
"discoveryCountry": "de",
"discoveryDate": "1886",
"electronAffinity": 1.232712,
"electronegativityPauling": 2.01,
"electronicConfiguration": "Ar 3d10 4s2 4p2",
"elementColor": [0.4, 0.56, 0.56],
"exactMass": 73.9211778,
"family": "Metalloids",
"group": 4,
"ionization": 7.8994,
"mass": 72.64,
"meltingpoint": 1211.5,
"mostCommonIsotope": "Ge74",
"mostCommonIsotopeMass": 73.9211778,
"name": "Germanium",
"nameOrigin": "Latin 'germania' is an old name for Germany",
"outshellElectrons": 4,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.188,
"radiusCovalent": 1.22,
"radiusVDW": 2.1,
"symbol": "Ge",
"valences": [4]
}, {
"atomicNumber": 33,
"boilingpoint": 876.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.814,
"electronegativityPauling": 2.18,
"electronicConfiguration": "Ar 3d10 4s2 4p3",
"elementColor": [0.74, 0.5, 0.89],
"exactMass": 74.9215965,
"family": "Metalloids",
"group": 5,
"ionization": 9.7886,
"mass": 74.9216,
"meltingpoint": 1090.0,
"mostCommonIsotope": "As75",
"mostCommonIsotopeMass": 74.9215965,
"name": "Arsenic",
"nameOrigin": "Greek 'arsenikos' for 'male' or 'bold'",
"outshellElectrons": 5,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.2,
"radiusCovalent": 1.19,
"radiusVDW": 2.05,
"symbol": "As",
"valences": [3, 5]
}, {
"atomicNumber": 34,
"boilingpoint": 958.0,
"discoverers": "J. J. Berzelius",
"discoveryCountry": "se",
"discoveryDate": "1817",
"electronAffinity": 2.02067,
"electronegativityPauling": 2.55,
"electronicConfiguration": "Ar 3d10 4s2 4p4",
"elementColor": [1.0, 0.63, 0.0],
"exactMass": 79.9165213,
"family": "Non-Metal",
"group": 6,
"ionization": 9.7524,
"mass": 78.96,
"meltingpoint": 494.0,
"mostCommonIsotope": "Se80",
"mostCommonIsotopeMass": 79.9165213,
"name": "Selenium",
"nameOrigin": "Greek 'selena' for 'moon'",
"outshellElectrons": 6,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.17,
"radiusCovalent": 1.16,
"radiusVDW": 1.9,
"symbol": "Se",
"valences": [2, 4, 6]
}, {
"atomicNumber": 35,
"boilingpoint": 331.85,
"discoverers": "A. J. Balard",
"discoveryCountry": "fr",
"discoveryDate": "1826",
"electronAffinity": 3.363588,
"electronegativityPauling": 2.96,
"electronicConfiguration": "Ar 3d10 4s2 4p5",
"elementColor": [0.65, 0.16, 0.16],
"exactMass": 78.9183371,
"family": "Halogen",
"group": 7,
"ionization": 11.8138,
"mass": 79.904,
"meltingpoint": 265.95,
"mostCommonIsotope": "Br79",
"mostCommonIsotopeMass": 78.9183371,
"name": "Bromine",
"nameOrigin": "Greek 'bromos' for 'smells badly'",
"outshellElectrons": 7,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.167,
"radiusCovalent": 1.14,
"radiusVDW": 1.9,
"symbol": "Br",
"valences": [1]
}, {
"atomicNumber": 36,
"boilingpoint": 120.85,
"discoverers": ["W. Ramsay", "M. W. Travers"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronegativityPauling": 3.0,
"electronicConfiguration": "Ar 3d10 4s2 4p6",
"elementColor": [0.36, 0.72, 0.82],
"exactMass": 83.911507,
"family": "Noblegas",
"group": 8,
"ionization": 13.9996,
"mass": 83.798,
"meltingpoint": 116.0,
"mostCommonIsotope": "Kr84",
"mostCommonIsotopeMass": 83.911507,
"name": "Krypton",
"nameOrigin": "Greek 'kryptos' for 'hidden'",
"outshellElectrons": 8,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.91,
"radiusCovalent": 1.1,
"radiusVDW": 2.02,
"symbol": "Kr",
"valences": [0]
}, {
"atomicNumber": 37,
"boilingpoint": 961.0,
"discoverers": ["Robert W. Bunsen", "Gustav R. Kirchhoff"],
"discoveryCountry": "de",
"discoveryDate": "1861",
"electronAffinity": 0.485916,
"electronegativityPauling": 0.82,
"electronicConfiguration": "Kr 5s1",
"elementColor": [0.44, 0.18, 0.69],
"exactMass": 84.91178974,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.1771,
"mass": 85.4678,
"meltingpoint": 312.63,
"mostCommonIsotope": "Rb85",
"mostCommonIsotopeMass": 84.91178974,
"name": "Rubidium",
"nameOrigin": "Latin 'rubidus' for 'dark red'",
"outshellElectrons": 1,
"period": 5,
"periodTableBlock": "s",
"rB0": 2.16,
"radiusCovalent": 2.11,
"radiusVDW": 2.9,
"symbol": "Rb",
"valences": [1]
}, {
"atomicNumber": 38,
"boilingpoint": 1655.0,
"discoverers": "H. B. Davy",
"discoveryCountry": "uk",
"discoveryDate": "1790",
"electronAffinity": 0.05206,
"electronegativityPauling": 0.95,
"electronicConfiguration": "Kr 5s2",
"elementColor": [0.0, 1.0, 0.0],
"exactMass": 87.9056121,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.6949,
"mass": 87.62,
"meltingpoint": 1042.0,
"mostCommonIsotope": "Sr88",
"mostCommonIsotopeMass": 87.9056121,
"name": "Strontium",
"nameOrigin": "Named after the mineral Strontianit",
"outshellElectrons": 2,
"period": 5,
"periodTableBlock": "s",
"rB0": 1.91,
"radiusCovalent": 1.92,
"radiusVDW": 2.55,
"symbol": "Sr",
"valences": [2]
}, {
"atomicNumber": 39,
"boilingpoint": 3611.0,
"discoverers": "Johann Gadolin",
"discoveryCountry": "fi",
"discoveryDate": "1794",
"electronAffinity": 0.307,
"electronegativityPauling": 1.22,
"electronicConfiguration": "Kr 4d1 5s2",
"elementColor": [0.58, 1.0, 1.0],
"exactMass": 88.9058483,
"family": "Transition",
"group": 3,
"ionization": 6.2173,
"mass": 88.90585,
"meltingpoint": 1795.0,
"mostCommonIsotope": "Y89",
"mostCommonIsotopeMass": 88.9058483,
"name": "Yttrium",
"nameOrigin": "Named after the small town of Ytterby near Stockholm in Sweden. Terbium. Ytterbium and Gadolinium are also named after this town.",
"outshellElectrons": 3,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.62,
"radiusCovalent": 1.62,
"radiusVDW": 2.4,
"symbol": "Y",
"valences": []
}, {
"atomicNumber": 40,
"boilingpoint": 4682.0,
"discoverers": "Martin Heinrich Klaproth",
"discoveryCountry": "de",
"discoveryDate": "1789",
"electronAffinity": 0.426,
"electronegativityPauling": 1.33,
"electronicConfiguration": "Kr 4d2 5s2",
"elementColor": [0.58, 0.88, 0.88],
"exactMass": 89.9047044,
"family": "Transition",
"group": 4,
"ionization": 6.6339,
"mass": 91.224,
"meltingpoint": 2128.0,
"mostCommonIsotope": "Zr90",
"mostCommonIsotopeMass": 89.9047044,
"name": "Zirconium",
"nameOrigin": "Named after the mineral zircon",
"outshellElectrons": 4,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.45,
"radiusCovalent": 1.48,
"radiusVDW": 2.3,
"symbol": "Zr",
"valences": []
}, {
"atomicNumber": 41,
"boilingpoint": 5015.0,
"discoverers": "Ch. Hatchett",
"discoveryCountry": "uk",
"discoveryDate": "1801",
"electronAffinity": 0.893,
"electronegativityPauling": 1.6,
"electronicConfiguration": "Kr 4d4",
"elementColor": [0.45, 0.76, 0.79],
"exactMass": 92.9063781,
"family": "Transition",
"group": 5,
"ionization": 6.7589,
"mass": 92.90638,
"meltingpoint": 2742.0,
"mostCommonIsotope": "Nb93",
"mostCommonIsotopeMass": 92.9063781,
"name": "Niobium",
"nameOrigin": "Named after Niobe, the daughter of the Greek god Tantalus.",
"outshellElectrons": 5,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.37,
"radiusVDW": 2.15,
"symbol": "Nb",
"valences": []
}, {
"atomicNumber": 42,
"boilingpoint": 4912.0,
"discoverers": "C. W. Scheele",
"discoveryCountry": "se",
"discoveryDate": "1778",
"electronAffinity": 0.7472,
"electronegativityPauling": 2.16,
"electronicConfiguration": "Kr 4d5 5s1",
"elementColor": [0.33, 0.71, 0.71],
"exactMass": 97.9054082,
"family": "Transition",
"group": 6,
"ionization": 7.0924,
"mass": 95.96,
"meltingpoint": 2896.0,
"mostCommonIsotope": "Mo98",
"mostCommonIsotopeMass": 97.9054082,
"name": "Molybdenum",
"nameOrigin": "This name has Greek roots. It means 'like Platinum' - it was difficult to distinguish Molybdenum from Platinum.",
"outshellElectrons": 6,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.45,
"radiusVDW": 2.1,
"symbol": "Mo",
"valences": []
}, {
"atomicNumber": 43,
"boilingpoint": 4538.0,
"discoverers": ["C. Perrier", "E. G. Segre"],
"discoveryCountry": "it",
"discoveryDate": "1937",
"electronAffinity": 0.55,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Kr 4d6 5s1",
"elementColor": [0.23, 0.62, 0.62],
"exactMass": 97.907216,
"family": "Transition",
"group": 7,
"ionization": 7.28,
"mass": 98.0,
"meltingpoint": 2477.0,
"mostCommonIsotope": "Tc97",
"mostCommonIsotopeMass": 96.906365,
"name": "Technetium",
"nameOrigin": "Greek 'technetos' for artificial",
"outshellElectrons": 7,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.27,
"radiusCovalent": 1.56,
"radiusVDW": 2.05,
"symbol": "Tc",
"valences": []
}, {
"atomicNumber": 44,
"boilingpoint": 4425.0,
"discoverers": "K. Klaus",
"discoveryCountry": "ru",
"discoveryDate": "1844",
"electronAffinity": 1.04638,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Kr 4d7 5s1",
"elementColor": [0.14, 0.56, 0.56],
"exactMass": 101.9043493,
"family": "Transition",
"group": 8,
"ionization": 7.3605,
"mass": 101.07,
"meltingpoint": 2610.0,
"mostCommonIsotope": "Ru102",
"mostCommonIsotopeMass": 101.9043493,
"name": "Ruthenium",
"nameOrigin": "Ruthenia is the old name of Russia",
"outshellElectrons": 8,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.26,
"radiusVDW": 2.05,
"symbol": "Ru",
"valences": []
}, {
"atomicNumber": 45,
"boilingpoint": 3970.0,
"discoverers": "W. Wollaston",
"discoveryCountry": "uk",
"discoveryDate": "1803",
"electronAffinity": 1.14289,
"electronegativityPauling": 2.28,
"electronicConfiguration": "Kr 4d8 5s1",
"elementColor": [0.04, 0.49, 0.55],
"exactMass": 102.905504,
"family": "Transition",
"group": 8,
"ionization": 7.4589,
"mass": 102.9055,
"meltingpoint": 2236.0,
"mostCommonIsotope": "Rh103",
"mostCommonIsotopeMass": 102.905504,
"name": "Rhodium",
"nameOrigin": "Greek 'rhodeos' means 'red like a rose'",
"outshellElectrons": 9,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.35,
"radiusVDW": 2.0,
"symbol": "Rh",
"valences": []
}, {
"atomicNumber": 46,
"boilingpoint": 3240.0,
"discoveryCountry": "uk",
"discoveryDate": "1803",
"electronAffinity": 0.56214,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Kr 4d10",
"elementColor": [0.0, 0.41, 0.52],
"exactMass": 105.903486,
"family": "Transition",
"group": 8,
"ionization": 8.3369,
"mass": 106.42,
"meltingpoint": 1825.0,
"mostCommonIsotope": "Pd106",
"mostCommonIsotopeMass": 105.903486,
"name": "Palladium",
"nameOrigin": "Named after the asteroid Pallas",
"outshellElectrons": 10,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.28,
"radiusCovalent": 1.31,
"radiusVDW": 2.05,
"symbol": "Pd",
"valences": []
}, {
"atomicNumber": 47,
"boilingpoint": 2436.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.30447,
"electronegativityPauling": 1.93,
"electronicConfiguration": "Kr 4d10 5s1",
"elementColor": [0.88, 0.88, 1.0],
"exactMass": 106.905097,
"family": "Transition",
"group": 1,
"ionization": 7.5762,
"mass": 107.8682,
"meltingpoint": 1235.1,
"mostCommonIsotope": "Ag107",
"mostCommonIsotopeMass": 106.905097,
"name": "Silver",
"nameOrigin": "Latin 'argentum' for silver",
"outshellElectrons": 11,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.53,
"radiusVDW": 2.1,
"symbol": "Ag",
"valences": []
}, {
"atomicNumber": 48,
"boilingpoint": 1040.0,
"discoverers": "F. Stromeyer",
"discoveryCountry": "de",
"discoveryDate": "1817",
"electronAffinity": 0.0,
"electronegativityPauling": 1.69,
"electronicConfiguration": "Kr 4d10 5s2",
"elementColor": [1.0, 0.85, 0.56],
"exactMass": 113.9033585,
"family": "Transition",
"group": 2,
"ionization": 8.9938,
"mass": 112.411,
"meltingpoint": 594.26,
"mostCommonIsotope": "Cd114",
"mostCommonIsotopeMass": 113.9033585,
"name": "Cadmium",
"nameOrigin": "Greek 'kadmia' ('Galmei' = Zinc carbonate)",
"outshellElectrons": 2,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.48,
"radiusCovalent": 1.48,
"radiusVDW": 2.2,
"symbol": "Cd",
"valences": []
}, {
"atomicNumber": 49,
"boilingpoint": 2350.0,
"discoverers": ["F. Reich", "H.T. Richter"],
"discoveryCountry": "de",
"discoveryDate": "1863",
"electronAffinity": 0.404,
"electronegativityPauling": 1.78,
"electronicConfiguration": "Kr 4d10 5s2 5p1",
"elementColor": [0.65, 0.46, 0.45],
"exactMass": 114.903878,
"family": "Other_Metal",
"group": 3,
"ionization": 5.7864,
"mass": 114.818,
"meltingpoint": 429.78,
"mostCommonIsotope": "In115",
"mostCommonIsotopeMass": 114.903878,
"name": "Indium",
"nameOrigin": "Named after 'Indigo' because of its blue spectrum",
"outshellElectrons": 3,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.44,
"radiusCovalent": 1.44,
"radiusVDW": 2.2,
"symbol": "In",
"valences": [3]
}, {
"atomicNumber": 50,
"boilingpoint": 2876.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.112066,
"electronegativityPauling": 1.96,
"electronicConfiguration": "Kr 4d10 5s2 5p2",
"elementColor": [0.4, 0.5, 0.5],
"exactMass": 119.9021947,
"family": "Other_Metal",
"group": 4,
"ionization": 7.3439,
"mass": 118.71,
"meltingpoint": 505.12,
"mostCommonIsotope": "Sn120",
"mostCommonIsotopeMass": 119.9021947,
"name": "Tin",
"nameOrigin": "Latin 'stannum' for tin",
"outshellElectrons": 4,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.385,
"radiusCovalent": 1.41,
"radiusVDW": 2.25,
"symbol": "Sn",
"valences": [4]
}, {
"atomicNumber": 51,
"boilingpoint": 1860.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.047401,
"electronegativityPauling": 2.05,
"electronicConfiguration": "Kr 4d10 5s2 5p3",
"elementColor": [0.62, 0.39, 0.71],
"exactMass": 120.9038157,
"family": "Metalloids",
"group": 5,
"ionization": 8.6084,
"mass": 121.76,
"meltingpoint": 903.91,
"mostCommonIsotope": "Sb121",
"mostCommonIsotopeMass": 120.9038157,
"name": "Antimony",
"nameOrigin": "Arabic 'anthos ammonos' for 'blossom of the god Ammon'",
"outshellElectrons": 5,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.4,
"radiusCovalent": 1.38,
"radiusVDW": 2.2,
"symbol": "Sb",
"valences": [3, 5]
}, {
"atomicNumber": 52,
"boilingpoint": 1261.0,
"discoverers": "Franz Joseph Muller von Reichstein",
"discoveryCountry": "de",
"discoveryDate": "1782",
"electronAffinity": 1.970875,
"electronegativityPauling": 2.1,
"electronicConfiguration": "Kr 4d10 5s2 5p4",
"elementColor": [0.83, 0.48, 0.0],
"exactMass": 129.9062244,
"family": "Metalloids",
"group": 6,
"ionization": 9.0096,
"mass": 127.6,
"meltingpoint": 722.72,
"mostCommonIsotope": "Te130",
"mostCommonIsotopeMass": 129.9062244,
"name": "Tellurium",
"nameOrigin": "Latin 'tellus' or 'telluris' for 'Planet Earth'",
"outshellElectrons": 6,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.378,
"radiusCovalent": 1.35,
"radiusVDW": 2.1,
"symbol": "Te",
"valences": [2]
}, {
"atomicNumber": 53,
"boilingpoint": 457.5,
"discoverers": "Bernard Courtois",
"discoveryCountry": "fr",
"discoveryDate": "1811",
"electronAffinity": 3.059038,
"electronegativityPauling": 2.66,
"electronicConfiguration": "Kr 4d10 5s2 5p5",
"elementColor": [0.58, 0.0, 0.58],
"exactMass": 126.904473,
"family": "Halogen",
"group": 7,
"ionization": 10.4513,
"mass": 126.90447,
"meltingpoint": 386.7,
"mostCommonIsotope": "I127",
"mostCommonIsotopeMass": 126.904473,
"name": "Iodine",
"nameOrigin": "Greek 'ioeides' for 'violet'.",
"outshellElectrons": 7,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.387,
"radiusCovalent": 1.33,
"radiusVDW": 2.1,
"symbol": "I",
"valences": [1, 2, 5]
}, {
"atomicNumber": 54,
"boilingpoint": 165.1,
"discoverers": ["W. Ramsay", "M. W. Travers"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronegativityPauling": 2.6,
"electronicConfiguration": "Kr 4d10 5s2 5p6",
"elementColor": [0.26, 0.62, 0.69],
"exactMass": 131.9041535,
"family": "Noblegas",
"group": 8,
"ionization": 12.1298,
"mass": 131.293,
"meltingpoint": 161.39,
"mostCommonIsotope": "Xe132",
"mostCommonIsotopeMass": 131.9041535,
"name": "Xenon",
"nameOrigin": "Greek 'xenos' for 'foreigner'",
"outshellElectrons": 8,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.98,
"radiusCovalent": 1.3,
"radiusVDW": 2.16,
"symbol": "Xe",
"valences": [0, 2]
}, {
"atomicNumber": 55,
"boilingpoint": 944.0,
"discoverers": ["Robert Wilhelm Bunsen", "Gustav Robert Kirchhoff"],
"discoveryCountry": "de",
"discoveryDate": "1860",
"electronAffinity": 0.471626,
"electronegativityPauling": 0.79,
"electronicConfiguration": "Xe 6s1",
"elementColor": [0.34, 0.09, 0.56],
"exactMass": 132.9054519,
"family": "Alkali_Earth",
"group": 1,
"ionization": 3.8939,
"mass": 132.9054519,
"meltingpoint": 301.54,
"mostCommonIsotope": "Cs133",
"mostCommonIsotopeMass": 132.9054519,
"name": "Caesium",
"nameOrigin": "Latin 'caesius' for 'heaven blue'.",
"outshellElectrons": 1,
"period": 6,
"periodTableBlock": "s",
"rB0": 2.35,
"radiusCovalent": 2.25,
"radiusVDW": 3.0,
"symbol": "Cs",
"valences": [1]
}, {
"atomicNumber": 56,
"boilingpoint": 2078.0,
"discoverers": "Humphry Bartholomew Davy",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.14462,
"electronegativityPauling": 0.89,
"electronicConfiguration": "Xe 6s2",
"elementColor": [0.0, 0.79, 0.0],
"exactMass": 137.9052472,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.2117,
"mass": 137.327,
"meltingpoint": 1002.0,
"mostCommonIsotope": "Ba138",
"mostCommonIsotopeMass": 137.9052472,
"name": "Barium",
"nameOrigin": "Greek 'barys' for 'heavy'",
"outshellElectrons": 2,
"period": 6,
"periodTableBlock": "s",
"rB0": 1.98,
"radiusCovalent": 1.98,
"radiusVDW": 2.7,
"symbol": "Ba",
"valences": [2]
}, {
"atomicNumber": 57,
"boilingpoint": 3737.0,
"discoverers": "K. G. Mosander",
"discoveryCountry": "se",
"discoveryDate": "1839",
"electronAffinity": 0.47,
"electronegativityPauling": 1.1,
"electronicConfiguration": "Xe 5d1 6s2",
"elementColor": [0.44, 0.83, 1.0],
"exactMass": 138.9063533,
"family": "Rare_Earth",
"group": 3,
"ionization": 5.5769,
"mass": 138.90547,
"meltingpoint": 1191.0,
"mostCommonIsotope": "La139",
"mostCommonIsotopeMass": 138.9063533,
"name": "Lanthanum",
"nameOrigin": "Greek 'lanthanein' for 'hidden'. The Lanthanoids are also called the 'rare earth' elements.",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.69,
"radiusCovalent": 1.69,
"radiusVDW": 2.5,
"symbol": "La",
"valences": []
}, {
"atomicNumber": 58,
"boilingpoint": 3715.0,
"discoverers": ["J\u00f6ns Jacob Berzelius", "W. Hisinger", "M. Klaproth"],
"discoveryDate": "1803",
"electronAffinity": 0.5,
"electronegativityPauling": 1.12,
"electronicConfiguration": "Xe 4f1 5d1 6s2",
"elementColor": [1.0, 1.0, 0.78],
"exactMass": 139.9054387,
"family": "Rare_Earth",
"group": 4,
"ionization": 5.5387,
"mass": 140.116,
"meltingpoint": 1071.0,
"mostCommonIsotope": "Ce140",
"mostCommonIsotopeMass": 139.9054387,
"name": "Cerium",
"nameOrigin": "Named after the planetoid Ceres",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.83,
"radiusVDW": 2.48,
"symbol": "Ce",
"valences": []
}, {
"atomicNumber": 59,
"boilingpoint": 3785.0,
"discoverers": "Carl F. Auer von Welsbach",
"discoveryDate": "1885",
"electronAffinity": 0.5,
"electronegativityPauling": 1.13,
"electronicConfiguration": "Xe 4f3 6s2",
"elementColor": [0.85, 1.0, 0.78],
"exactMass": 140.9076528,
"family": "Rare_Earth",
"group": 5,
"ionization": 5.473,
"mass": 140.90765,
"meltingpoint": 1204.0,
"mostCommonIsotope": "Pr141",
"mostCommonIsotopeMass": 140.9076528,
"name": "Praseodymium",
"nameOrigin": "Greek 'prasinos didymos' for 'green twin'",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.82,
"radiusVDW": 2.47,
"symbol": "Pr",
"valences": []
}, {
"atomicNumber": 60,
"boilingpoint": 3347.0,
"discoverers": "Carl F. Auer von Welsbach",
"discoveryDate": "1885",
"electronAffinity": 0.5,
"electronegativityPauling": 1.14,
"electronicConfiguration": "Xe 4f4 6s2",
"elementColor": [0.78, 1.0, 0.78],
"exactMass": 141.9077233,
"family": "Rare_Earth",
"group": 6,
"ionization": 5.525,
"mass": 144.242,
"meltingpoint": 1294.0,
"mostCommonIsotope": "Nd142",
"mostCommonIsotopeMass": 141.9077233,
"name": "Neodymium",
"nameOrigin": "Greek 'neos didymos' for 'new twin'",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.81,
"radiusVDW": 2.45,
"symbol": "Nd",
"valences": []
}, {
"atomicNumber": 61,
"boilingpoint": 3273.0,
"discoverers": ["J. A. Marinsky", "C. D. Coryell", "L. E. Glendenin"],
"discoveryDate": "1945",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f5 6s2",
"elementColor": [0.64, 1.0, 0.78],
"exactMass": 144.912749,
"family": "Rare_Earth",
"group": 7,
"ionization": 5.582,
"mass": 145.0,
"meltingpoint": 1315.0,
"mostCommonIsotope": "Pm145",
"mostCommonIsotopeMass": 144.912749,
"name": "Promethium",
"nameOrigin": "Named after the Greek Prometheus. Prometheus stole the fire from the gods and gave it to mankind.",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.8,
"radiusVDW": 2.43,
"symbol": "Pm",
"valences": []
}, {
"atomicNumber": 62,
"boilingpoint": 2067.0,
"discoverers": "P. Lecoq de Boisbaudran",
"discoveryDate": "1879",
"electronAffinity": 0.5,
"electronegativityPauling": 1.17,
"electronicConfiguration": "Xe 4f6 6s2",
"elementColor": [0.56, 1.0, 0.78],
"exactMass": 151.9197324,
"family": "Rare_Earth",
"group": 8,
"ionization": 5.6437,
"mass": 150.36,
"meltingpoint": 1347.0,
"mostCommonIsotope": "Sm152",
"mostCommonIsotopeMass": 151.9197324,
"name": "Samarium",
"nameOrigin": "Named after the mineral Samarskit",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.8,
"radiusVDW": 2.42,
"symbol": "Sm",
"valences": []
}, {
"atomicNumber": 63,
"boilingpoint": 1800.0,
"discoverers": "E. A. Demarcay",
"discoveryDate": "1901",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f7 6s2",
"elementColor": [0.38, 1.0, 0.78],
"exactMass": 152.9212303,
"family": "Rare_Earth",
"group": 8,
"ionization": 5.6704,
"mass": 151.964,
"meltingpoint": 1095.0,
"mostCommonIsotope": "Eu153",
"mostCommonIsotopeMass": 152.9212303,
"name": "Europium",
"nameOrigin": "Named after Europe",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.99,
"radiusVDW": 2.4,
"symbol": "Eu",
"valences": []
}, {
"atomicNumber": 64,
"boilingpoint": 3545.0,
"discoverers": "Jean de Marignac",
"discoveryDate": "1880",
"electronAffinity": 0.5,
"electronegativityPauling": 1.2,
"electronicConfiguration": "Xe 4f7 5d1 6s2",
"elementColor": [0.27, 1.0, 0.78],
"exactMass": 157.9241039,
"family": "Rare_Earth",
"group": 8,
"ionization": 6.1498,
"mass": 157.25,
"meltingpoint": 1585.0,
"mostCommonIsotope": "Gd158",
"mostCommonIsotopeMass": 157.9241039,
"name": "Gadolinium",
"nameOrigin": "Named after the Finnish chemist Johan Gadolin",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.79,
"radiusVDW": 2.38,
"symbol": "Gd",
"valences": []
}, {
"atomicNumber": 65,
"boilingpoint": 3500.0,
"discoverers": "K. G. Mosander",
"discoveryDate": "1843",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f9 6s2",
"elementColor": [0.19, 1.0, 0.78],
"exactMass": 158.9253468,
"family": "Rare_Earth",
"group": 1,
"ionization": 5.8638,
"mass": 158.92535,
"meltingpoint": 1629.0,
"mostCommonIsotope": "Tb159",
"mostCommonIsotopeMass": 158.9253468,
"name": "Terbium",
"nameOrigin": "Named after the Swedish town of Ytterby",
"outshellElectrons": 9,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.76,
"radiusVDW": 2.37,
"symbol": "Tb",
"valences": []
}, {
"atomicNumber": 66,
"boilingpoint": 2840.0,
"discoverers": "F. E. Lecoq de Boisbaudran",
"discoveryDate": "1886",
"electronAffinity": 0.5,
"electronegativityPauling": 1.22,
"electronicConfiguration": "Xe 4f10 6s2",
"elementColor": [0.12, 1.0, 0.78],
"exactMass": 163.9291748,
"family": "Rare_Earth",
"group": 2,
"ionization": 5.9389,
"mass": 162.5,
"meltingpoint": 1685.0,
"mostCommonIsotope": "Dy164",
"mostCommonIsotopeMass": 163.9291748,
"name": "Dysprosium",
"nameOrigin": "Greek 'dysprositor' for 'difficult to reach'",
"outshellElectrons": 10,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.75,
"radiusVDW": 2.35,
"symbol": "Dy",
"valences": []
}, {
"atomicNumber": 67,
"boilingpoint": 2968.0,
"discoverers": ["J. L. Soret", "P.T. Cleve"],
"discoveryDate": "1878",
"electronAffinity": 0.5,
"electronegativityPauling": 1.23,
"electronicConfiguration": "Xe 4f11 6s2",
"elementColor": [0.0, 1.0, 0.61],
"exactMass": 164.9303221,
"family": "Rare_Earth",
"group": 3,
"ionization": 6.0215,
"mass": 164.93032,
"meltingpoint": 1747.0,
"mostCommonIsotope": "Ho165",
"mostCommonIsotopeMass": 164.9303221,
"name": "Holmium",
"nameOrigin": "Latin 'holmia' for the old name of Stockholm",
"outshellElectrons": 11,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.74,
"radiusVDW": 2.33,
"symbol": "Ho",
"valences": []
}, {
"atomicNumber": 68,
"boilingpoint": 3140.0,
"discoverers": "K. G. Mosander",
"discoveryDate": "1843",
"electronAffinity": 0.5,
"electronegativityPauling": 1.24,
"electronicConfiguration": "Xe 4f12 6s2",
"elementColor": [0.0, 0.9, 0.46],
"exactMass": 165.9302931,
"family": "Rare_Earth",
"group": 4,
"ionization": 6.1077,
"mass": 167.259,
"meltingpoint": 1802.0,
"mostCommonIsotope": "Er166",
"mostCommonIsotopeMass": 165.9302931,
"name": "Erbium",
"nameOrigin": "Named ofter the Swedish town of Ytterby. Terbium and Ytterbium are also named after this town.",
"outshellElectrons": 12,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.73,
"radiusVDW": 2.32,
"symbol": "Er",
"valences": []
}, {
"atomicNumber": 69,
"boilingpoint": 2223.0,
"discoverers": "P. T. Cleve",
"discoveryDate": "1879",
"electronAffinity": 0.5,
"electronegativityPauling": 1.25,
"electronicConfiguration": "Xe 4f13 6s2",
"elementColor": [0.0, 0.83, 0.32],
"exactMass": 168.9342133,
"family": "Rare_Earth",
"group": 5,
"ionization": 6.1843,
"mass": 168.93421,
"meltingpoint": 1818.0,
"mostCommonIsotope": "Tm169",
"mostCommonIsotopeMass": 168.9342133,
"name": "Thulium",
"nameOrigin": "Named after the old name of Scandinavia, 'Thule'.",
"outshellElectrons": 13,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.72,
"radiusVDW": 2.3,
"symbol": "Tm",
"valences": []
}, {
"atomicNumber": 70,
"boilingpoint": 1469.0,
"discoverers": "J. Ch. Marignac",
"discoveryDate": "1878",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f14 6s2",
"elementColor": [0.0, 0.75, 0.22],
"exactMass": 173.9388621,
"family": "Rare_Earth",
"group": 6,
"ionization": 6.2542,
"mass": 173.054,
"meltingpoint": 1092.0,
"mostCommonIsotope": "Yb174",
"mostCommonIsotopeMass": 173.9388621,
"name": "Ytterbium",
"nameOrigin": "Like Terbium and Gadolinium, this is named after the Swedish town of Ytterby.",
"outshellElectrons": 14,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.94,
"radiusVDW": 2.28,
"symbol": "Yb",
"valences": []
}, {
"atomicNumber": 71,
"boilingpoint": 3668.0,
"discoverers": ["Carl F. Auer von Welsbach", "G. Urbain"],
"discoveryDate": "1907",
"electronAffinity": 0.5,
"electronegativityPauling": 1.27,
"electronicConfiguration": "Xe 4f14 5d1 6s2",
"elementColor": [0.0, 0.67, 0.14],
"exactMass": 174.9407718,
"family": "Rare_Earth",
"group": 7,
"ionization": 5.4259,
"mass": 174.9668,
"meltingpoint": 1936.0,
"mostCommonIsotope": "Lu175",
"mostCommonIsotopeMass": 174.9407718,
"name": "Lutetium",
"nameOrigin": "Named after the Roman name 'Lutetia' for Paris",
"outshellElectrons": 15,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.72,
"radiusCovalent": 1.6,
"radiusVDW": 2.27,
"symbol": "Lu",
"valences": []
}, {
"atomicNumber": 72,
"boilingpoint": 4875.0,
"discoverers": ["D. Coster", "G. Hevesy"],
"discoveryCountry": "dk",
"discoveryDate": "1923",
"electronAffinity": 0.0,
"electronegativityPauling": 1.3,
"electronicConfiguration": "Xe 4f14 5d2 6s2",
"elementColor": [0.3, 0.76, 1.0],
"exactMass": 179.94655,
"family": "Transition",
"group": 4,
"ionization": 6.8251,
"mass": 178.49,
"meltingpoint": 2504.0,
"mostCommonIsotope": "Hf180",
"mostCommonIsotopeMass": 179.94655,
"name": "Hafnium",
"nameOrigin": "'Hafnia' is the old name of Kopenhagen (Denmark)",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.44,
"radiusCovalent": 1.5,
"radiusVDW": 2.25,
"symbol": "Hf",
"valences": []
}, {
"atomicNumber": 73,
"boilingpoint": 5730.0,
"discoverers": "A. Ekeberg",
"discoveryCountry": "se",
"discoveryDate": "1802",
"electronAffinity": 0.322,
"electronegativityPauling": 1.5,
"electronicConfiguration": "Xe 4f14 5d3 6s2",
"elementColor": [0.3, 0.65, 1.0],
"exactMass": 180.9479958,
"family": "Transition",
"group": 5,
"ionization": 7.5496,
"mass": 180.94788,
"meltingpoint": 3293.0,
"mostCommonIsotope": "Ta181",
"mostCommonIsotopeMass": 180.9479958,
"name": "Tantalum",
"nameOrigin": "Named after the Greek myth of Tantalos",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.38,
"radiusVDW": 2.2,
"symbol": "Ta",
"valences": []
}, {
"atomicNumber": 74,
"boilingpoint": 5825.0,
"discoverers": "C. W. Scheele",
"discoveryCountry": "es",
"discoveryDate": "1783",
"electronAffinity": 0.815,
"electronegativityPauling": 2.36,
"electronicConfiguration": "Xe 4f14 5d4 6s2",
"elementColor": [0.13, 0.58, 0.84],
"exactMass": 183.9509312,
"family": "Transition",
"group": 6,
"ionization": 7.864,
"mass": 183.84,
"meltingpoint": 3695.0,
"mostCommonIsotope": "W184",
"mostCommonIsotopeMass": 183.9509312,
"name": "Tungsten",
"nameOrigin": "'tung sten' means 'heavy stone' in Swedish. The old name (and thus the symbol 'W') was Wolfram, named after a mineral.",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.46,
"radiusVDW": 2.1,
"symbol": "W",
"valences": []
}, {
"atomicNumber": 75,
"boilingpoint": 5870.0,
"discoverers": ["Walter Noddack", "Ida Tacke-Noddack", "Otto Berg"],
"discoveryCountry": "de",
"discoveryDate": "1925",
"electronAffinity": 0.15,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Xe 4f14 5d5 6s2",
"elementColor": [0.15, 0.49, 0.67],
"exactMass": 186.9557531,
"family": "Transition",
"group": 7,
"ionization": 7.8335,
"mass": 186.207,
"meltingpoint": 3455.0,
"mostCommonIsotope": "Re187",
"mostCommonIsotopeMass": 186.9557531,
"name": "Rhenium",
"nameOrigin": "Named after the German river Rhine (latin 'Rhenium').",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.28,
"radiusCovalent": 1.59,
"radiusVDW": 2.05,
"symbol": "Re",
"valences": []
}, {
"atomicNumber": 76,
"boilingpoint": 5300.0,
"discoverers": "S. Tennant",
"discoveryCountry": "uk",
"discoveryDate": "1804",
"electronAffinity": 1.0778,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d6 6s2",
"elementColor": [0.15, 0.4, 0.59],
"exactMass": 191.9614807,
"family": "Transition",
"group": 8,
"ionization": 8.4382,
"mass": 190.23,
"meltingpoint": 3300.0,
"mostCommonIsotope": "Os192",
"mostCommonIsotopeMass": 191.9614807,
"name": "Osmium",
"nameOrigin": "Greek for 'smell'. Its oxides smell strongly like radishes.",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.26,
"radiusCovalent": 1.28,
"radiusVDW": 2.0,
"symbol": "Os",
"valences": []
}, {
"atomicNumber": 77,
"boilingpoint": 4700.0,
"discoverers": "S. Tennant",
"discoveryCountry": "uk",
"discoveryDate": "1804",
"electronAffinity": 1.56436,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d7 6s2",
"elementColor": [0.09, 0.33, 0.53],
"exactMass": 192.9629264,
"family": "Transition",
"group": 8,
"ionization": 8.967,
"mass": 192.217,
"meltingpoint": 2720.0,
"mostCommonIsotope": "Ir193",
"mostCommonIsotopeMass": 192.9629264,
"name": "Iridium",
"nameOrigin": "Greek 'iris' for 'rainbow'",
"outshellElectrons": 9,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.27,
"radiusCovalent": 1.37,
"radiusVDW": 2.0,
"symbol": "Ir",
"valences": []
}, {
"atomicNumber": 78,
"boilingpoint": 4100.0,
"discoverers": "A. de Ulloa",
"discoveryCountry": "uk",
"discoveryDate": "1735",
"electronAffinity": 2.1251,
"electronegativityPauling": 2.28,
"electronicConfiguration": "Xe 4f14 5d9 6s1",
"elementColor": [0.96, 0.93, 0.82],
"exactMass": 194.9647911,
"family": "Transition",
"group": 8,
"ionization": 8.9588,
"mass": 195.084,
"meltingpoint": 2042.1,
"mostCommonIsotope": "Pt195",
"mostCommonIsotopeMass": 194.9647911,
"name": "Platinum",
"nameOrigin": "Spanish 'platina' means 'small silver'",
"outshellElectrons": 10,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.28,
"radiusVDW": 2.05,
"symbol": "Pt",
"valences": []
}, {
"atomicNumber": 79,
"boilingpoint": 3130.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 2.30861,
"electronegativityPauling": 2.54,
"electronicConfiguration": "Xe 4f14 5d10 6s1",
"elementColor": [0.8, 0.82, 0.12],
"exactMass": 196.9665687,
"family": "Transition",
"group": 1,
"ionization": 9.2255,
"mass": 196.966569,
"meltingpoint": 1337.58,
"mostCommonIsotope": "Au197",
"mostCommonIsotopeMass": 196.9665687,
"name": "Gold",
"nameOrigin": "Latin 'aurum'. Named after Aurora, the goddess of sunrise",
"outshellElectrons": 11,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.44,
"radiusVDW": 2.1,
"symbol": "Au",
"valences": []
}, {
"atomicNumber": 80,
"boilingpoint": 629.88,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.0,
"electronegativityPauling": 2.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2",
"elementColor": [0.71, 0.71, 0.76],
"exactMass": 201.970643,
"family": "Transition",
"group": 2,
"ionization": 10.4375,
"mass": 200.59,
"meltingpoint": 234.31,
"mostCommonIsotope": "Hg202",
"mostCommonIsotopeMass": 201.970643,
"name": "Mercury",
"nameOrigin": "Graeco-Latin 'hydrargyrum' for 'liquid silver'",
"outshellElectrons": 2,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.49,
"radiusCovalent": 1.49,
"radiusVDW": 2.05,
"symbol": "Hg",
"valences": []
}, {
"atomicNumber": 81,
"boilingpoint": 1746.0,
"discoverers": "W. Crookes",
"discoveryCountry": "uk",
"discoveryDate": "1861",
"electronAffinity": 0.377,
"electronegativityPauling": 1.62,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p1",
"elementColor": [0.65, 0.33, 0.3],
"exactMass": 204.9744275,
"family": "Other_Metal",
"group": 3,
"ionization": 6.1082,
"mass": 204.3833,
"meltingpoint": 577.0,
"mostCommonIsotope": "Tl205",
"mostCommonIsotopeMass": 204.9744275,
"name": "Thallium",
"nameOrigin": "Greek 'tallos' for 'young twig'",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.48,
"radiusCovalent": 1.48,
"radiusVDW": 2.2,
"symbol": "Tl",
"valences": [3]
}, {
"atomicNumber": 82,
"boilingpoint": 2023.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.364,
"electronegativityPauling": 2.33,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p2",
"elementColor": [0.34, 0.35, 0.38],
"exactMass": 207.9766521,
"family": "Other_Metal",
"group": 4,
"ionization": 7.4167,
"mass": 207.2,
"meltingpoint": 600.65,
"mostCommonIsotope": "Pb208",
"mostCommonIsotopeMass": 207.9766521,
"name": "Lead",
"nameOrigin": "Latin 'plumbum' for Lead",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.48,
"radiusCovalent": 1.47,
"radiusVDW": 2.3,
"symbol": "Pb",
"valences": [4]
}, {
"atomicNumber": 83,
"boilingpoint": 1837.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.942363,
"electronegativityPauling": 2.02,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p3",
"elementColor": [0.62, 0.31, 0.71],
"exactMass": 208.9803987,
"family": "Other_Metal",
"group": 5,
"ionization": 7.2855,
"mass": 208.9804,
"meltingpoint": 544.59,
"mostCommonIsotope": "Bi209",
"mostCommonIsotopeMass": 208.9803987,
"name": "Bismuth",
"nameOrigin": "The old name of Bismuth is 'Wismut', which stood for 'white mass'.",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.45,
"radiusCovalent": 1.46,
"radiusVDW": 2.3,
"symbol": "Bi",
"valences": [3]
}, {
"atomicNumber": 84,
"discoverers": ["M. Sklodowska-Curie", "P. Curie"],
"discoveryCountry": "fr",
"discoveryDate": "1898",
"electronAffinity": 1.9,
"electronegativityPauling": 2.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p4",
"elementColor": [0.67, 0.36, 0.0],
"exactMass": 208.9824304,
"family": "Metalloids",
"group": 6,
"ionization": 8.414,
"mass": 209.0,
"meltingpoint": 527.0,
"mostCommonIsotope": "Po209",
"mostCommonIsotopeMass": 208.9824304,
"name": "Polonium",
"nameOrigin": "Named after Poland to honor Marie Curie",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.46,
"radiusVDW": 2.0,
"symbol": "Po",
"valences": [2]
}, {
"atomicNumber": 85,
"boilingpoint": 610.0,
"discoverers": ["D. R. Corson", "K. R. McKenzie", "E. Segre"],
"discoveryCountry": "us",
"discoveryDate": "1940",
"electronAffinity": 2.8,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p5",
"elementColor": [0.46, 0.31, 0.27],
"exactMass": 209.987148,
"family": "Halogen",
"group": 7,
"ionization": 0.0,
"mass": 210.0,
"meltingpoint": 575.0,
"mostCommonIsotope": "At210",
"mostCommonIsotopeMass": 209.987148,
"name": "Astatine",
"nameOrigin": "Greek 'astator' for 'changing'",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.45,
"radiusVDW": 2.0,
"symbol": "At",
"valences": [1]
}, {
"atomicNumber": 86,
"boilingpoint": 211.4,
"discoverers": "E. Dorn",
"discoveryCountry": "de",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p6",
"elementColor": [0.26, 0.51, 0.59],
"exactMass": 222.0175777,
"family": "Noblegas",
"group": 8,
"ionization": 10.7485,
"mass": 222.0,
"meltingpoint": 202.0,
"mostCommonIsotope": "Rn211",
"mostCommonIsotopeMass": 210.990601,
"name": "Radon",
"nameOrigin": "Named after Radium. It ends with 'on' to make it clear that it is a noble gas.",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "p",
"rB0": 2.4,
"radiusCovalent": 1.45,
"radiusVDW": 2.0,
"symbol": "Rn",
"valences": [0]
}, {
"atomicNumber": 87,
"boilingpoint": 950.0,
"discoverers": "M. Perey",
"discoveryCountry": "fr",
"discoveryDate": "1939",
"electronegativityPauling": 0.7,
"electronicConfiguration": "Rn 7s1",
"elementColor": [0.26, 0.0, 0.4],
"exactMass": 223.0197359,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.0727,
"mass": 223.0,
"meltingpoint": 300.0,
"mostCommonIsotope": "Fr223",
"mostCommonIsotopeMass": 223.0197359,
"name": "Francium",
"nameOrigin": "Named after France to honor Marguerite Perey",
"outshellElectrons": 1,
"period": 7,
"periodTableBlock": "s",
"rB0": 2.0,
"radiusVDW": 2.0,
"symbol": "Fr",
"valences": [1]
}, {
"atomicNumber": 88,
"boilingpoint": 1413.0,
"discoverers": ["M. Sklodowska-Curie", "P. Curie"],
"discoveryCountry": "fr",
"discoveryDate": "1898",
"electronegativityPauling": 0.9,
"electronicConfiguration": "Rn 7s2",
"elementColor": [0.0, 0.49, 0.0],
"exactMass": 226.0254098,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.2784,
"mass": 226.0,
"meltingpoint": 973.0,
"mostCommonIsotope": "Ra223",
"mostCommonIsotopeMass": 223.0185022,
"name": "Radium",
"nameOrigin": "Latin 'radius' for 'beam', as it is radioactive",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "s",
"rB0": 1.9,
"radiusVDW": 2.0,
"symbol": "Ra",
"valences": [2]
}, {
"atomicNumber": 89,
"boilingpoint": 3470.0,
"discoverers": "A. L. Debierne",
"discoveryCountry": "fr",
"discoveryDate": "1899",
"electronegativityPauling": 1.1,
"electronicConfiguration": "Rn 6d1 7s2",
"elementColor": [0.44, 0.67, 0.98],
"exactMass": 227.0277521,
"family": "Other_Metal",
"group": 3,
"ionization": 5.17,
"mass": 227.0,
"meltingpoint": 1324.0,
"mostCommonIsotope": "Ac227",
"mostCommonIsotopeMass": 227.0277521,
"name": "Actinium",
"nameOrigin": "Greek 'aktis' for 'beam' - actinium is radioactive",
"outshellElectrons": 3,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.88,
"radiusVDW": 2.0,
"symbol": "Ac",
"valences": []
}, {
"atomicNumber": 90,
"boilingpoint": 5060.0,
"discoverers": "J. J. Berzelius",
"discoveryDate": "1828",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 6d2 7s2",
"elementColor": [0.0, 0.73, 1.0],
"exactMass": 232.0380553,
"family": "Other_Metal",
"group": 4,
"ionization": 6.3067,
"mass": 232.03806,
"meltingpoint": 2028.0,
"mostCommonIsotope": "Th232",
"mostCommonIsotopeMass": 232.0380553,
"name": "Thorium",
"nameOrigin": "Named after the German god of thunder: Thor",
"outshellElectrons": 4,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.79,
"radiusVDW": 2.4,
"symbol": "Th",
"valences": []
}, {
"atomicNumber": 91,
"boilingpoint": 4300.0,
"discoverers": ["O. Hahn", "L. Meitern", "W. Wollaston"],
"discoveryDate": "1917",
"electronegativityPauling": 1.5,
"electronicConfiguration": "Rn 5f2 6d1 7s2",
"elementColor": [0.0, 0.63, 1.0],
"exactMass": 231.035884,
"family": "Other_Metal",
"group": 5,
"ionization": 5.89,
"mass": 231.03588,
"meltingpoint": 1845.0,
"mostCommonIsotope": "Pa231",
"mostCommonIsotopeMass": 231.035884,
"name": "Protactinium",
"nameOrigin": "Greek 'protos' for 'ancester'. Protactinium is before Actinium in the periodic table.",
"outshellElectrons": 3,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.61,
"radiusVDW": 2.0,
"symbol": "Pa",
"valences": []
}, {
"atomicNumber": 92,
"boilingpoint": 4407.0,
"discoverers": "M. M. Klaproth",
"discoveryDate": "1789",
"electronegativityPauling": 1.38,
"electronicConfiguration": "Rn 5f3 6d1 7s2",
"elementColor": [0.0, 0.56, 1.0],
"exactMass": 238.0507882,
"family": "Other_Metal",
"group": 6,
"ionization": 6.1941,
"mass": 238.02891,
"meltingpoint": 1408.0,
"mostCommonIsotope": "U238",
"mostCommonIsotopeMass": 238.0507882,
"name": "Uranium",
"nameOrigin": "Greek 'ouranos' for 'heaven'. Named after the planet Uranus.",
"outshellElectrons": 4,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.58,
"radiusVDW": 2.3,
"symbol": "U",
"valences": []
}, {
"atomicNumber": 93,
"boilingpoint": 4175.0,
"discoverers": ["E. M. McMillan", "P. Aberson"],
"discoveryDate": "1940",
"electronegativityPauling": 1.36,
"electronicConfiguration": "Rn 5f4 6d1 7s2",
"elementColor": [0.0, 0.5, 1.0],
"exactMass": 237.0481734,
"family": "Other_Metal",
"group": 7,
"ionization": 6.2657,
"mass": 237.0,
"meltingpoint": 912.0,
"mostCommonIsotope": "Np236",
"mostCommonIsotopeMass": 236.04657,
"name": "Neptunium",
"nameOrigin": "Named after the planet Neptune.",
"outshellElectrons": 5,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.55,
"radiusVDW": 2.0,
"symbol": "Np",
"valences": []
}, {
"atomicNumber": 94,
"boilingpoint": 3505.0,
"discoverers": ["Glenn T. Seaborg", "E. M. McMillan", "J. W. Kennedy", "A.C. Wahl"],
"discoveryDate": "1940",
"electronegativityPauling": 1.28,
"electronicConfiguration": "Rn 5f6 7s2",
"elementColor": [0.0, 0.42, 1.0],
"exactMass": 244.064204,
"family": "Other_Metal",
"group": 8,
"ionization": 6.026,
"mass": 244.0,
"meltingpoint": 913.0,
"mostCommonIsotope": "Pu238",
"mostCommonIsotopeMass": 238.0495599,
"name": "Plutonium",
"nameOrigin": "Named after the planet Pluto.",
"outshellElectrons": 6,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.53,
"radiusVDW": 2.0,
"symbol": "Pu",
"valences": []
}, {
"atomicNumber": 95,
"boilingpoint": 2880.0,
"discoverers": ["Glenn T. Seaborg", "L. O. Morgan", "R. A. James", "A. Ghiors"],
"discoveryDate": "1945",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f7 7s2",
"elementColor": [0.33, 0.36, 0.95],
"exactMass": 243.0613811,
"family": "Other_Metal",
"group": 8,
"ionization": 5.9738,
"mass": 243.0,
"meltingpoint": 1449.0,
"mostCommonIsotope": "Am241",
"mostCommonIsotopeMass": 241.0568291,
"name": "Americium",
"nameOrigin": "Named after America.",
"outshellElectrons": 7,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.07,
"radiusVDW": 2.0,
"symbol": "Am",
"valences": []
}, {
"atomicNumber": 96,
"boilingpoint": 3383.0,
"discoverers": ["Glenn T. Seaborg", "R. A. James", "A. Ghiors"],
"discoveryDate": "1944",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f7 6d1 7s2",
"elementColor": [0.47, 0.36, 0.89],
"exactMass": 247.070354,
"family": "Other_Metal",
"group": 8,
"ionization": 5.9914,
"mass": 247.0,
"meltingpoint": 1620.0,
"mostCommonIsotope": "Cm243",
"mostCommonIsotopeMass": 243.0613891,
"name": "Curium",
"nameOrigin": "Named after Marie Curie.",
"outshellElectrons": 8,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Cm",
"valences": []
}, {
"atomicNumber": 97,
"boilingpoint": 983.0,
"discoverers": ["Glenn T. Seaborg", "A. Ghiors", "S. G. Thompson"],
"discoveryDate": "1949",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f9 7s2",
"elementColor": [0.54, 0.31, 0.89],
"exactMass": 247.070307,
"family": "Other_Metal",
"group": 1,
"ionization": 6.1979,
"mass": 247.0,
"meltingpoint": 1258.0,
"mostCommonIsotope": "Bk247",
"mostCommonIsotopeMass": 247.070307,
"name": "Berkelium",
"nameOrigin": "Named after the town Berkeley where it was discovered.",
"outshellElectrons": 9,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Bk",
"valences": []
}, {
"atomicNumber": 98,
"boilingpoint": 1173.0,
"discoverers": ["Glenn T. Seaborg", "A. Ghiors", "S. G. Thompson"],
"discoveryDate": "1950",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f10 7s2",
"elementColor": [0.63, 0.21, 0.83],
"exactMass": 251.079587,
"family": "Other_Metal",
"group": 2,
"ionization": 6.2817,
"mass": 251.0,
"meltingpoint": 1172.0,
"mostCommonIsotope": "Cf249",
"mostCommonIsotopeMass": 249.0748535,
"name": "Californium",
"nameOrigin": "Named after the US-State of California.",
"outshellElectrons": 10,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Cf",
"valences": []
}, {
"atomicNumber": 99,
"discoverers": ["Glenn T. Seaborg", "et al."],
"discoveryDate": "1952",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f11 7s2",
"elementColor": [0.7, 0.12, 0.83],
"exactMass": 252.08298,
"family": "Other_Metal",
"group": 3,
"ionization": 6.42,
"mass": 252.0,
"meltingpoint": 1130.0,
"mostCommonIsotope": "Es252",
"mostCommonIsotopeMass": 252.08298,
"name": "Einsteinium",
"nameOrigin": "Named after the scientist Albert Einstein.",
"outshellElectrons": 11,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Es",
"valences": []
}, {
"atomicNumber": 100,
"discoverers": ["Glenn T. Seaborg", "et al."],
"discoveryDate": "1953",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f12 7s2",
"elementColor": [0.7, 0.12, 0.73],
"exactMass": 257.095105,
"family": "Other_Metal",
"group": 4,
"ionization": 6.5,
"mass": 257.0,
"meltingpoint": 1800.0,
"mostCommonIsotope": "Fm257",
"mostCommonIsotopeMass": 257.095105,
"name": "Fermium",
"nameOrigin": "Named after the scientist Enrico Fermi.",
"outshellElectrons": 12,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Fm",
"valences": []
}, {
"atomicNumber": 101,
"discoverers": ["Glenn T. Seaborg", "Albert Ghiorso", "Bernard Harvey", "Gregory Choppin", "Stanley G. Thompson"],
"discoveryDate": "1955",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f13 7s2",
"elementColor": [0.7, 0.05, 0.65],
"exactMass": 258.098431,
"family": "Other_Metal",
"group": 5,
"ionization": 6.58,
"mass": 258.0,
"meltingpoint": 1100.0,
"mostCommonIsotope": "Md258",
"mostCommonIsotopeMass": 258.098431,
"name": "Mendelevium",
"nameOrigin": "Named after the scientist D.I. Mendeleev.",
"outshellElectrons": 13,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Md",
"valences": []
}, {
"atomicNumber": 102,
"discoveryDate": "1958",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f14 7s2",
"elementColor": [0.74, 0.05, 0.53],
"exactMass": 259.10103,
"family": "Other_Metal",
"group": 6,
"ionization": 6.65,
"mass": 259.0,
"meltingpoint": 1100.0,
"mostCommonIsotope": "No259",
"mostCommonIsotopeMass": 259.10103,
"name": "Nobelium",
"nameOrigin": "Named after the scientist Alfred Nobel.",
"outshellElectrons": 14,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "No",
"valences": []
}, {
"atomicNumber": 103,
"discoverers": ["Albert Ghiorso", "Torbjorn Sikkeland", "Almon Larsh", "Robert M. Latimer"],
"discoveryDate": "1961",
"electronicConfiguration": "Rn 5f14 7s2 7p1",
"elementColor": [0.78, 0.0, 0.4],
"exactMass": 262.10963,
"family": "Other_Metal",
"group": 7,
"ionization": 4.9,
"mass": 262.0,
"meltingpoint": 1900.0,
"mostCommonIsotope": "Lr262",
"mostCommonIsotopeMass": 262.10963,
"name": "Lawrencium",
"nameOrigin": "Named after the scientist Ernest Orlando Lawrence.",
"outshellElectrons": 15,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Lr",
"valences": []
}, {
"atomicNumber": 104,
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1964",
"electronicConfiguration": "Rn 5f14 6d2 7s2",
"elementColor": [0.8, 0.0, 0.35],
"exactMass": 261.10877,
"family": "Transition",
"group": 4,
"ionization": 6.0,
"mass": 267.0,
"mostCommonIsotope": "Rf267",
"mostCommonIsotopeMass": 267.12153,
"name": "Rutherfordium",
"nameOrigin": "Named after the scientist Ernest Rutherford",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Rf",
"valences": []
}, {
"atomicNumber": 105,
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1967",
"electronicConfiguration": "Rn 5f14 6d3 7s2",
"elementColor": [0.82, 0.0, 0.31],
"exactMass": 262.11408,
"family": "Transition",
"group": 5,
"mass": 268.0,
"mostCommonIsotope": "Db268",
"mostCommonIsotopeMass": 268.12545,
"name": "Dubnium",
"nameOrigin": "Named after the science-town Dubna in Russia",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Db",
"valences": []
}, {
"atomicNumber": 106,
"discoverers": ["Albert Ghiorso", "et al."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1974",
"elementColor": [0.85, 0.0, 0.27],
"exactMass": 263.11832,
"family": "Transition",
"group": 6,
"mass": 271.0,
"mostCommonIsotope": "Sg271",
"mostCommonIsotopeMass": 271.13347,
"name": "Seaborgium",
"nameOrigin": "Named after the scientist G. Theodore Seaborg.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Sg",
"valences": []
}, {
"atomicNumber": 107,
"discoverers": ["Peter Armbruster", "Gottfried M\u00fcnzenber", "et al."],
"discoveryCountry": "ru",
"discoveryDate": "1981",
"elementColor": [0.88, 0.0, 0.22],
"exactMass": 264.1246,
"family": "Transition",
"group": 7,
"mass": 272.0,
"mostCommonIsotope": "Bh270",
"mostCommonIsotopeMass": 270.13362,
"name": "Bohrium",
"nameOrigin": "Named after the scientist Niels Bohr.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Bh",
"valences": []
}, {
"atomicNumber": 108,
"discoverers": ["Peter Armbruster", "Gottfried M\u00fcnzenber", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1984",
"elementColor": [0.9, 0.0, 0.18],
"exactMass": 265.13009,
"family": "Transition",
"group": 8,
"mass": 270.0,
"mostCommonIsotope": "Hs269",
"mostCommonIsotopeMass": 269.13406,
"name": "Hassium",
"nameOrigin": "Latin 'hassia' for the German county Hessen. In Hessen a lot elements have been discovered.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Hs",
"valences": []
}, {
"atomicNumber": 109,
"discoverers": ["Peter Armbruster", "Gottfried M\u00fcnzenber", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1982",
"elementColor": [0.91, 0.0, 0.15],
"exactMass": 268.13873,
"family": "Transition",
"group": 8,
"mass": 276.0,
"mostCommonIsotope": "Mt278",
"mostCommonIsotopeMass": 278.15481,
"name": "Meitnerium",
"nameOrigin": "Named after the scientist Lise Meitner.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Mt",
"valences": []
}, {
"atomicNumber": 110,
"discoverers": ["S. Hofmann", "V. Ninov", "F. P. Hessberger", "P. Armbruster", "H. Folger", "G. M\u00fcnzenberg",
"H. J. Sch\u00f6tt", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1994",
"elementColor": [0.92, 0.0, 0.14],
"exactMass": 271.14606,
"family": "Transition",
"group": 8,
"mass": 281.0,
"mostCommonIsotope": "Ds281",
"mostCommonIsotopeMass": 281.16206,
"name": "Darmstadtium",
"nameOrigin": "Named after the German city Darmstadt where many elements have been discovered.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Ds",
"valences": []
}, {
"atomicNumber": 111,
"discoverers": ["S. Hofmann", "V. Ninov", "F. P. Hessberger", "P. Armbruster", "H. Folger", "G. M\u00fcnzenberg",
"et al."],
"discoveryCountry": "de",
"discoveryDate": "1994",
"elementColor": [0.93, 0.0, 0.13],
"exactMass": 272.15362,
"family": "Transition",
"group": 1,
"mass": 280.0,
"mostCommonIsotope": "Rg281",
"mostCommonIsotopeMass": 281.16537,
"name": "Roentgenium",
"nameOrigin": "Named after Wilhelm Conrad R\u00f6ntgen.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Rg",
"valences": []
}, {
"atomicNumber": 112,
"discoverers": "First created at the Gesellschaft f\u00fcr Schwerionenforschung",
"discoveryCountry": "de",
"discoveryDate": "1996",
"elementColor": [0.94, 0.0, 0.12],
"exactMass": 285.17411,
"family": "Transition",
"mass": 285.0,
"mostCommonIsotope": "Cn285",
"mostCommonIsotopeMass": 285.17411,
"name": "Copernicium",
"nameOrigin": "Historically known as eka-mercury. Ununbium is a temporary IUPAC systematic element name.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Cn",
"valences": []
}, {
"atomicNumber": 113,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2003",
"elementColor": [0.95, 0.0, 0.11],
"exactMass": 284.17808,
"family": "Other_Metal",
"mass": 284.0,
"name": "Ununtrium",
"nameOrigin": "Historically known as eka-thallium. Ununtrium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uut"
}, {
"atomicNumber": 114,
"discoverers": "Joint Institute for Nuclear Research",
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1998",
"elementColor": [0.96, 0.0, 0.1],
"exactMass": 289.18728,
"family": "Other_Metal",
"mass": 289.0,
"name": "Ununquadium",
"nameOrigin": "Historically known as eka-lead. Ununquadium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuq"
}, {
"atomicNumber": 115,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2004",
"elementColor": [0.97, 0.0, 0.09],
"exactMass": 288.19249,
"family": "Other_Metal",
"mass": 288.0,
"name": "Ununpentium",
"nameOrigin": "Historically known as eka-bismuth. Ununpentium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uup"
}, {
"atomicNumber": 116,
"discoverers": "Joint Institute for Nuclear Research",
"discoveryCountry": "ru",
"discoveryDate": "2000",
"elementColor": [0.98, 0.0, 0.08],
"exactMass": 292.19979,
"family": "Other_Metal",
"mass": 293.0,
"name": "Ununhexium",
"nameOrigin": "Historically known as eka-polonium. Ununhexium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuh"
}, {
"atomicNumber": 117,
"discoveryDate": "0",
"elementColor": [0.99, 0.0, 0.07],
"family": "Halogen",
"name": "Ununseptium",
"nameOrigin": "Temporary symbol and name. Can also be referred to as eka-astatine.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uus"
}, {
"atomicNumber": 118,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2002",
"elementColor": [1.0, 0.0, 0.06],
"family": "Noblegas",
"mass": 294.0,
"name": "Ununoctium",
"nameOrigin": "Historically known as eka-radon, eka-emanation before 1960. Ununoctium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuo"
}]
} | 195986 | define ->
{
"atoms": [{
"atomicNumber": 0,
"elementColor": [0.07, 0.5, 0.7],
"exactMass": 0.0,
"mass": 0.0,
"mostCommonIsotope": "Xx0",
"mostCommonIsotopeMass": 0.0,
"name": "<NAME>",
"outshellElectrons": 0,
"rB0": 0.0,
"radiusCovalent": 0.0,
"radiusVDW": 0.0,
"symbol": "Xx",
"valences": []
}, {
"atomicNumber": 1,
"boilingpoint": 20.28,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1766",
"electronAffinity": 0.75420375,
"electronegativityPauling": 2.2,
"electronicConfiguration": "1s1",
"elementColor": [1.0, 1.0, 1.0],
"exactMass": 1.007825032,
"family": "Non-Metal",
"group": 1,
"ionization": 13.5984,
"mass": 1.00794,
"meltingpoint": 14.01,
"mostCommonIsotope": "H1",
"mostCommonIsotopeMass": 1.007825032,
"name": "<NAME>",
"nameOrigin": "Greek 'hydro' and 'gennao' for 'forms water'",
"outshellElectrons": 1,
"period": 1,
"periodTableBlock": "s",
"rB0": 0.33,
"radiusCovalent": 0.37,
"radiusVDW": 1.2,
"symbol": "H",
"valences": [1]
}, {
"atomicNumber": 2,
"boilingpoint": 4.216,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": ["se", "uk"],
"discoveryDate": "1895",
"electronAffinity": 0.0,
"electronicConfiguration": "1s2",
"elementColor": [0.85, 1.0, 1.0],
"exactMass": 4.002603254,
"family": "Noblegas",
"group": 8,
"ionization": 24.5874,
"mass": 4.002602,
"meltingpoint": 0.95,
"mostCommonIsotope": "He4",
"mostCommonIsotopeMass": 4.002603254,
"name": "<NAME>",
"nameOrigin": "The Greek word for the sun was 'helios'",
"outshellElectrons": 2,
"period": 1,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.32,
"radiusVDW": 1.4,
"symbol": "He",
"valences": [0]
}, {
"atomicNumber": 3,
"boilingpoint": 1615.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1817",
"electronAffinity": 0.618049,
"electronegativityPauling": 0.98,
"electronicConfiguration": "He 2s1",
"elementColor": [0.8, 0.5, 1.0],
"exactMass": 7.01600455,
"family": "Alkali_Earth",
"group": 1,
"ionization": 5.3917,
"mass": 6.941,
"meltingpoint": 453.7,
"mostCommonIsotope": "Li7",
"mostCommonIsotopeMass": 7.01600455,
"name": "<NAME>",
"nameOrigin": "Greek 'lithos' means 'stone'",
"outshellElectrons": 1,
"period": 2,
"periodTableBlock": "s",
"rB0": 1.23,
"radiusCovalent": 1.34,
"radiusVDW": 2.2,
"symbol": "Li",
"valences": [1]
}, {
"atomicNumber": 4,
"boilingpoint": 3243.0,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1797",
"electronAffinity": 0.0,
"electronegativityPauling": 1.57,
"electronicConfiguration": "He 2s2",
"elementColor": [0.76, 1.0, 0.0],
"exactMass": 9.0121822,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 9.3227,
"mass": 9.012182,
"meltingpoint": 1560.0,
"mostCommonIsotope": "Be9",
"mostCommonIsotopeMass": 9.0121822,
"name": "<NAME>",
"nameOrigin": "Greek 'ber<NAME>los' for 'light-green stone'",
"outshellElectrons": 2,
"period": 2,
"periodTableBlock": "s",
"rB0": 0.9,
"radiusCovalent": 0.9,
"radiusVDW": 1.9,
"symbol": "Be",
"valences": [2]
}, {
"atomicNumber": 5,
"boilingpoint": 4275.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": ["uk", "fr"],
"discoveryDate": "1808",
"electronAffinity": 0.279723,
"electronegativityPauling": 2.04,
"electronicConfiguration": "He 2s2 2p1",
"elementColor": [1.0, 0.71, 0.71],
"exactMass": 11.0093054,
"family": "Metalloids",
"group": 3,
"ionization": 8.298,
"mass": 10.811,
"meltingpoint": 2365.0,
"mostCommonIsotope": "B11",
"mostCommonIsotopeMass": 11.0093054,
"name": "<NAME>",
"nameOrigin": "Bor<NAME> means 'Bor(ax) + (carb)on'. It is found in borax and behaves a lot like carbon",
"outshellElectrons": 3,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.82,
"radiusCovalent": 0.82,
"radiusVDW": 1.8,
"symbol": "B",
"valences": [3]
}, {
"atomicNumber": 6,
"boilingpoint": 5100.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.262118,
"electronegativityPauling": 2.55,
"electronicConfiguration": "He 2s2 2p2",
"elementColor": [0.5, 0.5, 0.5],
"exactMass": 12.0,
"family": "Non-Metal",
"group": 4,
"ionization": 11.2603,
"mass": 12.0107,
"meltingpoint": 3825.0,
"mostCommonIsotope": "C12",
"mostCommonIsotopeMass": 12.0,
"name": "<NAME>",
"nameOrigin": "Latin 'carboneum' for carbon",
"outshellElectrons": 4,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.77,
"radiusCovalent": 0.77,
"radiusVDW": 1.7,
"symbol": "C",
"valences": [4]
}, {
"atomicNumber": 7,
"boilingpoint": 77.344,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1772",
"electronAffinity": -0.07,
"electronegativityPauling": 3.04,
"electronicConfiguration": "He 2s2 2p3",
"elementColor": [0.05, 0.05, 1.0],
"exactMass": 14.003074,
"family": "Non-Metal",
"group": 5,
"ionization": 14.5341,
"mass": 14.0067,
"meltingpoint": 63.15,
"mostCommonIsotope": "N14",
"mostCommonIsotopeMass": 14.003074,
"name": "Nitrogen",
"nameOrigin": "Latin 'nitrogenium' ('forms saltpeter')",
"outshellElectrons": 5,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.75,
"radiusVDW": 1.6,
"symbol": "N",
"valences": [3]
}, {
"atomicNumber": 8,
"boilingpoint": 90.188,
"discoverers": "<NAME>",
"discoveryCountry": ["se", "uk"],
"discoveryDate": "1774",
"electronAffinity": 1.461112,
"electronegativityPauling": 3.44,
"electronicConfiguration": "He 2s2 2p4",
"elementColor": [1.0, 0.05, 0.05],
"exactMass": 15.99491462,
"family": "Non-Metal",
"group": 6,
"ionization": 13.6181,
"mass": 15.9994,
"meltingpoint": 54.8,
"mostCommonIsotope": "O16",
"mostCommonIsotopeMass": 15.99491462,
"name": "Oxygen",
"nameOrigin": "Latin 'oxygenium' (forms acids)",
"outshellElectrons": 6,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.66,
"radiusCovalent": 0.73,
"radiusVDW": 1.55,
"symbol": "O",
"valences": [2]
}, {
"atomicNumber": 9,
"boilingpoint": 85.0,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1886",
"electronAffinity": 3.4011887,
"electronegativityPauling": 3.98,
"electronicConfiguration": "He 2s2 2p5",
"elementColor": [0.7, 1.0, 1.0],
"exactMass": 18.99840322,
"family": "Halogen",
"group": 7,
"ionization": 17.4228,
"mass": 18.9984032,
"meltingpoint": 53.55,
"mostCommonIsotope": "F19",
"mostCommonIsotopeMass": 18.99840322,
"name": "Fluorine",
"nameOrigin": "Latin 'fluere' ('floats')",
"outshellElectrons": 7,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.611,
"radiusCovalent": 0.71,
"radiusVDW": 1.5,
"symbol": "F",
"valences": [1]
}, {
"atomicNumber": 10,
"boilingpoint": 27.1,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronicConfiguration": "He 2s2 2p6",
"elementColor": [0.7, 0.89, 0.96],
"exactMass": 19.99244018,
"family": "Noblegas",
"group": 8,
"ionization": 21.5645,
"mass": 20.1797,
"meltingpoint": 24.55,
"mostCommonIsotope": "Ne20",
"mostCommonIsotopeMass": 19.99244018,
"name": "<NAME>",
"nameOrigin": "Greek 'neo'. meaning 'new'",
"outshellElectrons": 8,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.69,
"radiusVDW": 1.54,
"symbol": "Ne",
"valences": [0]
}, {
"atomicNumber": 11,
"boilingpoint": 1156.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1807",
"electronAffinity": 0.547926,
"electronegativityPauling": 0.93,
"electronicConfiguration": "Ne 3s1",
"elementColor": [0.67, 0.36, 0.95],
"exactMass": 22.98976928,
"family": "Alkali_Earth",
"group": 1,
"ionization": 5.1391,
"mass": 22.98976928,
"meltingpoint": 371.0,
"mostCommonIsotope": "Na23",
"mostCommonIsotopeMass": 22.98976928,
"name": "Sodium",
"nameOrigin": "Arabic 'natrun' for 'soda'",
"outshellElectrons": 1,
"period": 3,
"periodTableBlock": "s",
"rB0": 1.54,
"radiusCovalent": 1.54,
"radiusVDW": 2.4,
"symbol": "Na",
"valences": [1]
}, {
"atomicNumber": 12,
"boilingpoint": 1380.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.0,
"electronegativityPauling": 1.31,
"electronicConfiguration": "Ne 3s2",
"elementColor": [0.54, 1.0, 0.0],
"exactMass": 23.9850417,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 7.6462,
"mass": 24.305,
"meltingpoint": 922.0,
"mostCommonIsotope": "Mg24",
"mostCommonIsotopeMass": 23.9850417,
"name": "<NAME>agnesium",
"nameOrigin": "Named after the city of Magnesia",
"outshellElectrons": 2,
"period": 3,
"periodTableBlock": "s",
"rB0": 1.36,
"radiusCovalent": 1.3,
"radiusVDW": 2.2,
"symbol": "Mg",
"valences": [2]
}, {
"atomicNumber": 13,
"boilingpoint": 2740.0,
"discoverers": "<NAME>",
"discoveryCountry": "dk",
"discoveryDate": "1825",
"electronAffinity": 0.43283,
"electronegativityPauling": 1.61,
"electronicConfiguration": "Ne 3s2 3p1",
"elementColor": [0.75, 0.65, 0.65],
"exactMass": 26.98153863,
"family": "Other_Metal",
"group": 3,
"ionization": 5.9858,
"mass": 26.9815386,
"meltingpoint": 933.5,
"mostCommonIsotope": "Al27",
"mostCommonIsotopeMass": 26.98153863,
"name": "Aluminium",
"nameOrigin": "Latin 'alumen'",
"outshellElectrons": 3,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.18,
"radiusCovalent": 1.18,
"radiusVDW": 2.1,
"symbol": "Al",
"valences": [6]
}, {
"atomicNumber": 14,
"boilingpoint": 2630.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1823",
"electronAffinity": 1.389521,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Ne 3s2 3p2",
"elementColor": [0.5, 0.6, 0.6],
"exactMass": 27.97692653,
"family": "Metalloids",
"group": 4,
"ionization": 8.1517,
"mass": 28.0855,
"meltingpoint": 1683.0,
"mostCommonIsotope": "Si28",
"mostCommonIsotopeMass": 27.97692653,
"name": "<NAME>",
"nameOrigin": "Latin 'silex'",
"outshellElectrons": 4,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.937,
"radiusCovalent": 1.11,
"radiusVDW": 2.1,
"symbol": "Si",
"valences": [4, 6]
}, {
"atomicNumber": 15,
"boilingpoint": 553.0,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1669",
"electronAffinity": 0.7465,
"electronegativityPauling": 2.19,
"electronicConfiguration": "Ne 3s2 3p3",
"elementColor": [1.0, 0.5, 0.0],
"exactMass": 30.97376163,
"family": "Non-Metal",
"group": 5,
"ionization": 10.4867,
"mass": 30.973762,
"meltingpoint": 317.3,
"mostCommonIsotope": "P31",
"mostCommonIsotopeMass": 30.97376163,
"name": "<NAME>",
"nameOrigin": "Greek 'phosphoros' for 'carries light'",
"outshellElectrons": 5,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.89,
"radiusCovalent": 1.06,
"radiusVDW": 1.95,
"symbol": "P",
"valences": [3, 5, 7]
}, {
"atomicNumber": 16,
"boilingpoint": 717.82,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 2.0771029,
"electronegativityPauling": 2.58,
"electronicConfiguration": "Ne 3s2 3p4",
"elementColor": [1.0, 1.0, 0.19],
"exactMass": 31.972071,
"family": "Non-Metal",
"group": 6,
"ionization": 10.36,
"mass": 32.065,
"meltingpoint": 392.2,
"mostCommonIsotope": "S32",
"mostCommonIsotopeMass": 31.972071,
"name": "<NAME>",
"nameOrigin": "In sanskrit 'sweb' means 'to sleep'",
"outshellElectrons": 6,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.04,
"radiusCovalent": 1.02,
"radiusVDW": 1.8,
"symbol": "S",
"valences": [2, 4, 6]
}, {
"atomicNumber": 17,
"boilingpoint": 239.18,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1774",
"electronAffinity": 3.612724,
"electronegativityPauling": 3.16,
"electronicConfiguration": "Ne 3s2 3p5",
"elementColor": [0.12, 0.94, 0.12],
"exactMass": 34.96885268,
"family": "Halogen",
"group": 7,
"ionization": 12.9676,
"mass": 35.453,
"meltingpoint": 172.17,
"mostCommonIsotope": "Cl35",
"mostCommonIsotopeMass": 34.96885268,
"name": "<NAME>",
"nameOrigin": "Greek 'chloros' for 'yellow-green'",
"outshellElectrons": 7,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.997,
"radiusCovalent": 0.99,
"radiusVDW": 1.8,
"symbol": "Cl",
"valences": [1]
}, {
"atomicNumber": 18,
"boilingpoint": 87.45,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "uk",
"discoveryDate": "1894",
"electronAffinity": 0.0,
"electronicConfiguration": "Ne 3s2 3p6",
"elementColor": [0.5, 0.82, 0.89],
"exactMass": 39.96238312,
"family": "Noblegas",
"group": 8,
"ionization": 15.7596,
"mass": 39.948,
"meltingpoint": 83.95,
"mostCommonIsotope": "Ar40",
"mostCommonIsotopeMass": 39.96238312,
"name": "<NAME>",
"nameOrigin": "Greek 'aergon' for 'inactive'",
"outshellElectrons": 8,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.74,
"radiusCovalent": 0.97,
"radiusVDW": 1.88,
"symbol": "Ar",
"valences": [0]
}, {
"atomicNumber": 19,
"boilingpoint": 1033.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1807",
"electronAffinity": 0.501459,
"electronegativityPauling": 0.82,
"electronicConfiguration": "Ar 4s1",
"elementColor": [0.56, 0.25, 0.83],
"exactMass": 38.96370668,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.3407,
"mass": 39.0983,
"meltingpoint": 336.8,
"mostCommonIsotope": "K39",
"mostCommonIsotopeMass": 38.96370668,
"name": "<NAME>",
"nameOrigin": "Arabic 'al qaliy' for potash",
"outshellElectrons": 1,
"period": 4,
"periodTableBlock": "s",
"rB0": 2.03,
"radiusCovalent": 1.96,
"radiusVDW": 2.8,
"symbol": "K",
"valences": [1]
}, {
"atomicNumber": 20,
"boilingpoint": 1757.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.02455,
"electronegativityPauling": 1.0,
"electronicConfiguration": "Ar 4s2",
"elementColor": [0.24, 1.0, 0.0],
"exactMass": 39.96259098,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 6.1132,
"mass": 40.078,
"meltingpoint": 1112.0,
"mostCommonIsotope": "Ca40",
"mostCommonIsotopeMass": 39.96259098,
"name": "<NAME>",
"nameOrigin": "Latin 'calx' for 'lime'",
"outshellElectrons": 2,
"period": 4,
"periodTableBlock": "s",
"rB0": 1.74,
"radiusCovalent": 1.74,
"radiusVDW": 2.4,
"symbol": "Ca",
"valences": [2]
}, {
"atomicNumber": 21,
"boilingpoint": 3109.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1879",
"electronAffinity": 0.188,
"electronegativityPauling": 1.36,
"electronicConfiguration": "Ar 3d1 4s2",
"elementColor": [0.9, 0.9, 0.9],
"exactMass": 44.9559119,
"family": "Transition",
"group": 3,
"ionization": 6.5615,
"mass": 44.955912,
"meltingpoint": 1814.0,
"mostCommonIsotope": "Sc45",
"mostCommonIsotopeMass": 44.9559119,
"name": "<NAME>",
"nameOrigin": "Named because it was found in Scandinavia",
"outshellElectrons": 3,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.44,
"radiusCovalent": 1.44,
"radiusVDW": 2.3,
"symbol": "Sc",
"valences": []
}, {
"atomicNumber": 22,
"boilingpoint": 3560.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1791",
"electronAffinity": 0.084,
"electronegativityPauling": 1.54,
"electronicConfiguration": "Ar 3d2 4s2",
"elementColor": [0.75, 0.76, 0.78],
"exactMass": 47.9479463,
"family": "Transition",
"group": 4,
"ionization": 6.8281,
"mass": 47.867,
"meltingpoint": 1935.0,
"mostCommonIsotope": "Ti48",
"mostCommonIsotopeMass": 47.9479463,
"name": "<NAME>",
"nameOrigin": "The Titans were giants in Greek mythology",
"outshellElectrons": 4,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.32,
"radiusCovalent": 1.36,
"radiusVDW": 2.15,
"symbol": "Ti",
"valences": []
}, {
"atomicNumber": 23,
"boilingpoint": 3650.0,
"discoverers": "<NAME>\u00f6<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1830",
"electronAffinity": 0.525,
"electronegativityPauling": 1.63,
"electronicConfiguration": "Ar 3d3 4s2",
"elementColor": [0.65, 0.65, 0.67],
"exactMass": 50.9439595,
"family": "Transition",
"group": 5,
"ionization": 6.7462,
"mass": 50.9415,
"meltingpoint": 2163.0,
"mostCommonIsotope": "V50",
"mostCommonIsotopeMass": 49.9471585,
"name": "<NAME>",
"nameOrigin": "'<NAME>' is another name for the <NAME>ordic goddess <NAME>",
"outshellElectrons": 5,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.22,
"radiusCovalent": 1.25,
"radiusVDW": 2.05,
"symbol": "V",
"valences": []
}, {
"atomicNumber": 24,
"boilingpoint": 2945.0,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1797",
"electronAffinity": 0.67584,
"electronegativityPauling": 1.66,
"electronicConfiguration": "Ar 3d5 4s1",
"elementColor": [0.54, 0.6, 0.78],
"exactMass": 51.9405075,
"family": "Transition",
"group": 6,
"ionization": 6.7665,
"mass": 51.9961,
"meltingpoint": 2130.0,
"mostCommonIsotope": "Cr52",
"mostCommonIsotopeMass": 51.9405075,
"name": "<NAME>",
"nameOrigin": "Greek 'chroma' means 'color'",
"outshellElectrons": 6,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.18,
"radiusCovalent": 1.27,
"radiusVDW": 2.05,
"symbol": "Cr",
"valences": []
}, {
"atomicNumber": 25,
"boilingpoint": 2235.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1774",
"electronAffinity": 0.0,
"electronegativityPauling": 1.55,
"electronicConfiguration": "Ar 3d5 4s2",
"elementColor": [0.61, 0.48, 0.78],
"exactMass": 54.9380451,
"family": "Transition",
"group": 7,
"ionization": 7.434,
"mass": 54.938045,
"meltingpoint": 1518.0,
"mostCommonIsotope": "Mn55",
"mostCommonIsotopeMass": 54.9380451,
"name": "<NAME>ang<NAME>",
"nameOrigin": "It was discovered near a town named Magnesia in black earth. Thus, it was named '<NAME>ia <NAME>', or for short, Manganese.",
"outshellElectrons": 7,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.39,
"radiusVDW": 2.05,
"symbol": "Mn",
"valences": []
}, {
"atomicNumber": 26,
"boilingpoint": 3023.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.151,
"electronegativityPauling": 1.83,
"electronicConfiguration": "Ar 3d6 4s2",
"elementColor": [0.5, 0.48, 0.78],
"exactMass": 55.9349375,
"family": "Transition",
"group": 8,
"ionization": 7.9024,
"mass": 55.845,
"meltingpoint": 1808.0,
"mostCommonIsotope": "Fe56",
"mostCommonIsotopeMass": 55.9349375,
"name": "<NAME>",
"nameOrigin": "Latin 'ferrum'",
"outshellElectrons": 8,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.25,
"radiusVDW": 2.05,
"symbol": "Fe",
"valences": []
}, {
"atomicNumber": 27,
"boilingpoint": 3143.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1737",
"electronAffinity": 0.6633,
"electronegativityPauling": 1.88,
"electronicConfiguration": "Ar 3d7 4s2",
"elementColor": [0.44, 0.48, 0.78],
"exactMass": 58.933195,
"family": "Transition",
"group": 8,
"ionization": 7.881,
"mass": 58.933195,
"meltingpoint": 1768.0,
"mostCommonIsotope": "Co59",
"mostCommonIsotopeMass": 58.933195,
"name": "<NAME>",
"nameOrigin": "Named after the German word '<NAME>' for 'goblin'",
"outshellElectrons": 9,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.16,
"radiusCovalent": 1.26,
"radiusVDW": 2.0,
"symbol": "Co",
"valences": []
}, {
"atomicNumber": 28,
"boilingpoint": 3005.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1751",
"electronAffinity": 1.15716,
"electronegativityPauling": 1.91,
"electronicConfiguration": "Ar 3d8 4s2",
"elementColor": [0.36, 0.48, 0.76],
"exactMass": 57.9353429,
"family": "Transition",
"group": 8,
"ionization": 7.6398,
"mass": 58.6934,
"meltingpoint": 1726.0,
"mostCommonIsotope": "Ni58",
"mostCommonIsotopeMass": 57.9353429,
"name": "<NAME>",
"nameOrigin": "'<NAME>' was the name of a mountain goblin",
"outshellElectrons": 10,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.15,
"radiusCovalent": 1.21,
"radiusVDW": 2.0,
"symbol": "Ni",
"valences": []
}, {
"atomicNumber": 29,
"boilingpoint": 2840.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.23578,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Ar 3d10 4s1",
"elementColor": [1.0, 0.48, 0.38],
"exactMass": 62.9295975,
"family": "Transition",
"group": 1,
"ionization": 7.7264,
"mass": 63.546,
"meltingpoint": 1356.6,
"mostCommonIsotope": "Cu63",
"mostCommonIsotopeMass": 62.9295975,
"name": "<NAME>",
"nameOrigin": "Greek 'cuprum' for Cypres",
"outshellElectrons": 11,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.38,
"radiusVDW": 2.0,
"symbol": "Cu",
"valences": []
}, {
"atomicNumber": 30,
"boilingpoint": 1180.0,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1746",
"electronAffinity": 0.0,
"electronegativityPauling": 1.65,
"electronicConfiguration": "Ar 3d10 4s2",
"elementColor": [0.49, 0.5, 0.69],
"exactMass": 63.9291422,
"family": "Transition",
"group": 2,
"ionization": 9.3942,
"mass": 65.38,
"meltingpoint": 692.73,
"mostCommonIsotope": "Zn64",
"mostCommonIsotopeMass": 63.9291422,
"name": "<NAME>",
"nameOrigin": "German 'zinking' for 'rough', because zinc ore is very rough",
"outshellElectrons": 2,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.31,
"radiusVDW": 2.1,
"symbol": "Zn",
"valences": []
}, {
"atomicNumber": 31,
"boilingpoint": 2478.0,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1875",
"electronAffinity": 0.41,
"electronegativityPauling": 1.81,
"electronicConfiguration": "Ar 3d10 4s2 4p1",
"elementColor": [0.76, 0.56, 0.56],
"exactMass": 68.9255736,
"family": "Other_Metal",
"group": 3,
"ionization": 5.9993,
"mass": 69.723,
"meltingpoint": 302.92,
"mostCommonIsotope": "Ga69",
"mostCommonIsotopeMass": 68.9255736,
"name": "<NAME>",
"nameOrigin": "'<NAME>' is an old name for France",
"outshellElectrons": 3,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.26,
"radiusCovalent": 1.26,
"radiusVDW": 2.1,
"symbol": "Ga",
"valences": [3]
}, {
"atomicNumber": 32,
"boilingpoint": 3107.0,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1886",
"electronAffinity": 1.232712,
"electronegativityPauling": 2.01,
"electronicConfiguration": "Ar 3d10 4s2 4p2",
"elementColor": [0.4, 0.56, 0.56],
"exactMass": 73.9211778,
"family": "Metalloids",
"group": 4,
"ionization": 7.8994,
"mass": 72.64,
"meltingpoint": 1211.5,
"mostCommonIsotope": "Ge74",
"mostCommonIsotopeMass": 73.9211778,
"name": "<NAME>",
"nameOrigin": "Latin 'germania' is an old name for Germany",
"outshellElectrons": 4,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.188,
"radiusCovalent": 1.22,
"radiusVDW": 2.1,
"symbol": "Ge",
"valences": [4]
}, {
"atomicNumber": 33,
"boilingpoint": 876.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.814,
"electronegativityPauling": 2.18,
"electronicConfiguration": "Ar 3d10 4s2 4p3",
"elementColor": [0.74, 0.5, 0.89],
"exactMass": 74.9215965,
"family": "Metalloids",
"group": 5,
"ionization": 9.7886,
"mass": 74.9216,
"meltingpoint": 1090.0,
"mostCommonIsotope": "As75",
"mostCommonIsotopeMass": 74.9215965,
"name": "<NAME>",
"nameOrigin": "Greek 'arsenikos' for 'male' or 'bold'",
"outshellElectrons": 5,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.2,
"radiusCovalent": 1.19,
"radiusVDW": 2.05,
"symbol": "As",
"valences": [3, 5]
}, {
"atomicNumber": 34,
"boilingpoint": 958.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1817",
"electronAffinity": 2.02067,
"electronegativityPauling": 2.55,
"electronicConfiguration": "Ar 3d10 4s2 4p4",
"elementColor": [1.0, 0.63, 0.0],
"exactMass": 79.9165213,
"family": "Non-Metal",
"group": 6,
"ionization": 9.7524,
"mass": 78.96,
"meltingpoint": 494.0,
"mostCommonIsotope": "Se80",
"mostCommonIsotopeMass": 79.9165213,
"name": "<NAME>",
"nameOrigin": "Greek 'selena' for 'moon'",
"outshellElectrons": 6,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.17,
"radiusCovalent": 1.16,
"radiusVDW": 1.9,
"symbol": "Se",
"valences": [2, 4, 6]
}, {
"atomicNumber": 35,
"boilingpoint": 331.85,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1826",
"electronAffinity": 3.363588,
"electronegativityPauling": 2.96,
"electronicConfiguration": "Ar 3d10 4s2 4p5",
"elementColor": [0.65, 0.16, 0.16],
"exactMass": 78.9183371,
"family": "Halogen",
"group": 7,
"ionization": 11.8138,
"mass": 79.904,
"meltingpoint": 265.95,
"mostCommonIsotope": "Br79",
"mostCommonIsotopeMass": 78.9183371,
"name": "<NAME>",
"nameOrigin": "Greek 'bromos' for 'smells badly'",
"outshellElectrons": 7,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.167,
"radiusCovalent": 1.14,
"radiusVDW": 1.9,
"symbol": "Br",
"valences": [1]
}, {
"atomicNumber": 36,
"boilingpoint": 120.85,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronegativityPauling": 3.0,
"electronicConfiguration": "Ar 3d10 4s2 4p6",
"elementColor": [0.36, 0.72, 0.82],
"exactMass": 83.911507,
"family": "Noblegas",
"group": 8,
"ionization": 13.9996,
"mass": 83.798,
"meltingpoint": 116.0,
"mostCommonIsotope": "Kr84",
"mostCommonIsotopeMass": 83.911507,
"name": "<NAME>",
"nameOrigin": "Greek 'kryptos' for 'hidden'",
"outshellElectrons": 8,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.91,
"radiusCovalent": 1.1,
"radiusVDW": 2.02,
"symbol": "Kr",
"valences": [0]
}, {
"atomicNumber": 37,
"boilingpoint": 961.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "de",
"discoveryDate": "1861",
"electronAffinity": 0.485916,
"electronegativityPauling": 0.82,
"electronicConfiguration": "Kr 5s1",
"elementColor": [0.44, 0.18, 0.69],
"exactMass": 84.91178974,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.1771,
"mass": 85.4678,
"meltingpoint": 312.63,
"mostCommonIsotope": "Rb85",
"mostCommonIsotopeMass": 84.91178974,
"name": "<NAME>",
"nameOrigin": "Latin 'rubidus' for 'dark red'",
"outshellElectrons": 1,
"period": 5,
"periodTableBlock": "s",
"rB0": 2.16,
"radiusCovalent": 2.11,
"radiusVDW": 2.9,
"symbol": "Rb",
"valences": [1]
}, {
"atomicNumber": 38,
"boilingpoint": 1655.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1790",
"electronAffinity": 0.05206,
"electronegativityPauling": 0.95,
"electronicConfiguration": "Kr 5s2",
"elementColor": [0.0, 1.0, 0.0],
"exactMass": 87.9056121,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.6949,
"mass": 87.62,
"meltingpoint": 1042.0,
"mostCommonIsotope": "Sr88",
"mostCommonIsotopeMass": 87.9056121,
"name": "<NAME>",
"nameOrigin": "Named after the mineral Strontianit",
"outshellElectrons": 2,
"period": 5,
"periodTableBlock": "s",
"rB0": 1.91,
"radiusCovalent": 1.92,
"radiusVDW": 2.55,
"symbol": "Sr",
"valences": [2]
}, {
"atomicNumber": 39,
"boilingpoint": 3611.0,
"discoverers": "<NAME>",
"discoveryCountry": "fi",
"discoveryDate": "1794",
"electronAffinity": 0.307,
"electronegativityPauling": 1.22,
"electronicConfiguration": "Kr 4d1 5s2",
"elementColor": [0.58, 1.0, 1.0],
"exactMass": 88.9058483,
"family": "Transition",
"group": 3,
"ionization": 6.2173,
"mass": 88.90585,
"meltingpoint": 1795.0,
"mostCommonIsotope": "Y89",
"mostCommonIsotopeMass": 88.9058483,
"name": "<NAME>",
"nameOrigin": "Named after the small town of Ytterby near Stockholm in Sweden. Terbium. Ytterbium and Gadolinium are also named after this town.",
"outshellElectrons": 3,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.62,
"radiusCovalent": 1.62,
"radiusVDW": 2.4,
"symbol": "Y",
"valences": []
}, {
"atomicNumber": 40,
"boilingpoint": 4682.0,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1789",
"electronAffinity": 0.426,
"electronegativityPauling": 1.33,
"electronicConfiguration": "Kr 4d2 5s2",
"elementColor": [0.58, 0.88, 0.88],
"exactMass": 89.9047044,
"family": "Transition",
"group": 4,
"ionization": 6.6339,
"mass": 91.224,
"meltingpoint": 2128.0,
"mostCommonIsotope": "Zr90",
"mostCommonIsotopeMass": 89.9047044,
"name": "<NAME>",
"nameOrigin": "Named after the mineral zircon",
"outshellElectrons": 4,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.45,
"radiusCovalent": 1.48,
"radiusVDW": 2.3,
"symbol": "Zr",
"valences": []
}, {
"atomicNumber": 41,
"boilingpoint": 5015.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1801",
"electronAffinity": 0.893,
"electronegativityPauling": 1.6,
"electronicConfiguration": "Kr 4d4",
"elementColor": [0.45, 0.76, 0.79],
"exactMass": 92.9063781,
"family": "Transition",
"group": 5,
"ionization": 6.7589,
"mass": 92.90638,
"meltingpoint": 2742.0,
"mostCommonIsotope": "Nb93",
"mostCommonIsotopeMass": 92.9063781,
"name": "<NAME>",
"nameOrigin": "Named after <NAME>, the daughter of the Greek god <NAME>.",
"outshellElectrons": 5,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.37,
"radiusVDW": 2.15,
"symbol": "Nb",
"valences": []
}, {
"atomicNumber": 42,
"boilingpoint": 4912.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1778",
"electronAffinity": 0.7472,
"electronegativityPauling": 2.16,
"electronicConfiguration": "Kr 4d5 5s1",
"elementColor": [0.33, 0.71, 0.71],
"exactMass": 97.9054082,
"family": "Transition",
"group": 6,
"ionization": 7.0924,
"mass": 95.96,
"meltingpoint": 2896.0,
"mostCommonIsotope": "Mo98",
"mostCommonIsotopeMass": 97.9054082,
"name": "<NAME>",
"nameOrigin": "This name has Greek roots. It means 'like Platinum' - it was difficult to distinguish Molybdenum from Platinum.",
"outshellElectrons": 6,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.45,
"radiusVDW": 2.1,
"symbol": "Mo",
"valences": []
}, {
"atomicNumber": 43,
"boilingpoint": 4538.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "it",
"discoveryDate": "1937",
"electronAffinity": 0.55,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Kr 4d6 5s1",
"elementColor": [0.23, 0.62, 0.62],
"exactMass": 97.907216,
"family": "Transition",
"group": 7,
"ionization": 7.28,
"mass": 98.0,
"meltingpoint": 2477.0,
"mostCommonIsotope": "Tc97",
"mostCommonIsotopeMass": 96.906365,
"name": "<NAME>",
"nameOrigin": "Greek 'technetos' for artificial",
"outshellElectrons": 7,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.27,
"radiusCovalent": 1.56,
"radiusVDW": 2.05,
"symbol": "Tc",
"valences": []
}, {
"atomicNumber": 44,
"boilingpoint": 4425.0,
"discoverers": "<NAME>",
"discoveryCountry": "ru",
"discoveryDate": "1844",
"electronAffinity": 1.04638,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Kr 4d7 5s1",
"elementColor": [0.14, 0.56, 0.56],
"exactMass": 101.9043493,
"family": "Transition",
"group": 8,
"ionization": 7.3605,
"mass": 101.07,
"meltingpoint": 2610.0,
"mostCommonIsotope": "Ru102",
"mostCommonIsotopeMass": 101.9043493,
"name": "<NAME>",
"nameOrigin": "<NAME> is the old name of <NAME>ussia",
"outshellElectrons": 8,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.26,
"radiusVDW": 2.05,
"symbol": "Ru",
"valences": []
}, {
"atomicNumber": 45,
"boilingpoint": 3970.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1803",
"electronAffinity": 1.14289,
"electronegativityPauling": 2.28,
"electronicConfiguration": "Kr 4d8 5s1",
"elementColor": [0.04, 0.49, 0.55],
"exactMass": 102.905504,
"family": "Transition",
"group": 8,
"ionization": 7.4589,
"mass": 102.9055,
"meltingpoint": 2236.0,
"mostCommonIsotope": "Rh103",
"mostCommonIsotopeMass": 102.905504,
"name": "<NAME>",
"nameOrigin": "Greek 'rhodeos' means 'red like a rose'",
"outshellElectrons": 9,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.35,
"radiusVDW": 2.0,
"symbol": "Rh",
"valences": []
}, {
"atomicNumber": 46,
"boilingpoint": 3240.0,
"discoveryCountry": "uk",
"discoveryDate": "1803",
"electronAffinity": 0.56214,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Kr 4d10",
"elementColor": [0.0, 0.41, 0.52],
"exactMass": 105.903486,
"family": "Transition",
"group": 8,
"ionization": 8.3369,
"mass": 106.42,
"meltingpoint": 1825.0,
"mostCommonIsotope": "Pd106",
"mostCommonIsotopeMass": 105.903486,
"name": "<NAME>",
"nameOrigin": "Named after the asteroid Pallas",
"outshellElectrons": 10,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.28,
"radiusCovalent": 1.31,
"radiusVDW": 2.05,
"symbol": "Pd",
"valences": []
}, {
"atomicNumber": 47,
"boilingpoint": 2436.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.30447,
"electronegativityPauling": 1.93,
"electronicConfiguration": "Kr 4d10 5s1",
"elementColor": [0.88, 0.88, 1.0],
"exactMass": 106.905097,
"family": "Transition",
"group": 1,
"ionization": 7.5762,
"mass": 107.8682,
"meltingpoint": 1235.1,
"mostCommonIsotope": "Ag107",
"mostCommonIsotopeMass": 106.905097,
"name": "<NAME>",
"nameOrigin": "Latin 'argentum' for silver",
"outshellElectrons": 11,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.53,
"radiusVDW": 2.1,
"symbol": "Ag",
"valences": []
}, {
"atomicNumber": 48,
"boilingpoint": 1040.0,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1817",
"electronAffinity": 0.0,
"electronegativityPauling": 1.69,
"electronicConfiguration": "Kr 4d10 5s2",
"elementColor": [1.0, 0.85, 0.56],
"exactMass": 113.9033585,
"family": "Transition",
"group": 2,
"ionization": 8.9938,
"mass": 112.411,
"meltingpoint": 594.26,
"mostCommonIsotope": "Cd114",
"mostCommonIsotopeMass": 113.9033585,
"name": "<NAME>",
"nameOrigin": "Greek 'kadmia' ('Galmei' = Zinc carbonate)",
"outshellElectrons": 2,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.48,
"radiusCovalent": 1.48,
"radiusVDW": 2.2,
"symbol": "Cd",
"valences": []
}, {
"atomicNumber": 49,
"boilingpoint": 2350.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "de",
"discoveryDate": "1863",
"electronAffinity": 0.404,
"electronegativityPauling": 1.78,
"electronicConfiguration": "Kr 4d10 5s2 5p1",
"elementColor": [0.65, 0.46, 0.45],
"exactMass": 114.903878,
"family": "Other_Metal",
"group": 3,
"ionization": 5.7864,
"mass": 114.818,
"meltingpoint": 429.78,
"mostCommonIsotope": "In115",
"mostCommonIsotopeMass": 114.903878,
"name": "<NAME>",
"nameOrigin": "Named after '<NAME>' because of its blue spectrum",
"outshellElectrons": 3,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.44,
"radiusCovalent": 1.44,
"radiusVDW": 2.2,
"symbol": "In",
"valences": [3]
}, {
"atomicNumber": 50,
"boilingpoint": 2876.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.112066,
"electronegativityPauling": 1.96,
"electronicConfiguration": "Kr 4d10 5s2 5p2",
"elementColor": [0.4, 0.5, 0.5],
"exactMass": 119.9021947,
"family": "Other_Metal",
"group": 4,
"ionization": 7.3439,
"mass": 118.71,
"meltingpoint": 505.12,
"mostCommonIsotope": "Sn120",
"mostCommonIsotopeMass": 119.9021947,
"name": "<NAME>",
"nameOrigin": "Latin '<NAME>annum' for tin",
"outshellElectrons": 4,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.385,
"radiusCovalent": 1.41,
"radiusVDW": 2.25,
"symbol": "Sn",
"valences": [4]
}, {
"atomicNumber": 51,
"boilingpoint": 1860.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.047401,
"electronegativityPauling": 2.05,
"electronicConfiguration": "Kr 4d10 5s2 5p3",
"elementColor": [0.62, 0.39, 0.71],
"exactMass": 120.9038157,
"family": "Metalloids",
"group": 5,
"ionization": 8.6084,
"mass": 121.76,
"meltingpoint": 903.91,
"mostCommonIsotope": "Sb121",
"mostCommonIsotopeMass": 120.9038157,
"name": "<NAME>",
"nameOrigin": "Arabic 'anthos ammonos' for 'blossom of the god Ammon'",
"outshellElectrons": 5,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.4,
"radiusCovalent": 1.38,
"radiusVDW": 2.2,
"symbol": "Sb",
"valences": [3, 5]
}, {
"atomicNumber": 52,
"boilingpoint": 1261.0,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1782",
"electronAffinity": 1.970875,
"electronegativityPauling": 2.1,
"electronicConfiguration": "Kr 4d10 5s2 5p4",
"elementColor": [0.83, 0.48, 0.0],
"exactMass": 129.9062244,
"family": "Metalloids",
"group": 6,
"ionization": 9.0096,
"mass": 127.6,
"meltingpoint": 722.72,
"mostCommonIsotope": "Te130",
"mostCommonIsotopeMass": 129.9062244,
"name": "<NAME>",
"nameOrigin": "Latin 'tellus' or 'telluris' for 'Planet Earth'",
"outshellElectrons": 6,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.378,
"radiusCovalent": 1.35,
"radiusVDW": 2.1,
"symbol": "Te",
"valences": [2]
}, {
"atomicNumber": 53,
"boilingpoint": 457.5,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1811",
"electronAffinity": 3.059038,
"electronegativityPauling": 2.66,
"electronicConfiguration": "Kr 4d10 5s2 5p5",
"elementColor": [0.58, 0.0, 0.58],
"exactMass": 126.904473,
"family": "Halogen",
"group": 7,
"ionization": 10.4513,
"mass": 126.90447,
"meltingpoint": 386.7,
"mostCommonIsotope": "I127",
"mostCommonIsotopeMass": 126.904473,
"name": "<NAME>",
"nameOrigin": "Greek 'ioeides' for 'violet'.",
"outshellElectrons": 7,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.387,
"radiusCovalent": 1.33,
"radiusVDW": 2.1,
"symbol": "I",
"valences": [1, 2, 5]
}, {
"atomicNumber": 54,
"boilingpoint": 165.1,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronegativityPauling": 2.6,
"electronicConfiguration": "Kr 4d10 5s2 5p6",
"elementColor": [0.26, 0.62, 0.69],
"exactMass": 131.9041535,
"family": "Noblegas",
"group": 8,
"ionization": 12.1298,
"mass": 131.293,
"meltingpoint": 161.39,
"mostCommonIsotope": "Xe132",
"mostCommonIsotopeMass": 131.9041535,
"name": "<NAME>",
"nameOrigin": "Greek 'xenos' for 'foreigner'",
"outshellElectrons": 8,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.98,
"radiusCovalent": 1.3,
"radiusVDW": 2.16,
"symbol": "Xe",
"valences": [0, 2]
}, {
"atomicNumber": 55,
"boilingpoint": 944.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "de",
"discoveryDate": "1860",
"electronAffinity": 0.471626,
"electronegativityPauling": 0.79,
"electronicConfiguration": "Xe 6s1",
"elementColor": [0.34, 0.09, 0.56],
"exactMass": 132.9054519,
"family": "Alkali_Earth",
"group": 1,
"ionization": 3.8939,
"mass": 132.9054519,
"meltingpoint": 301.54,
"mostCommonIsotope": "Cs133",
"mostCommonIsotopeMass": 132.9054519,
"name": "<NAME>",
"nameOrigin": "Latin 'caesius' for 'heaven blue'.",
"outshellElectrons": 1,
"period": 6,
"periodTableBlock": "s",
"rB0": 2.35,
"radiusCovalent": 2.25,
"radiusVDW": 3.0,
"symbol": "Cs",
"valences": [1]
}, {
"atomicNumber": 56,
"boilingpoint": 2078.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.14462,
"electronegativityPauling": 0.89,
"electronicConfiguration": "Xe 6s2",
"elementColor": [0.0, 0.79, 0.0],
"exactMass": 137.9052472,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.2117,
"mass": 137.327,
"meltingpoint": 1002.0,
"mostCommonIsotope": "Ba138",
"mostCommonIsotopeMass": 137.9052472,
"name": "<NAME>",
"nameOrigin": "Greek 'barys' for 'heavy'",
"outshellElectrons": 2,
"period": 6,
"periodTableBlock": "s",
"rB0": 1.98,
"radiusCovalent": 1.98,
"radiusVDW": 2.7,
"symbol": "Ba",
"valences": [2]
}, {
"atomicNumber": 57,
"boilingpoint": 3737.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1839",
"electronAffinity": 0.47,
"electronegativityPauling": 1.1,
"electronicConfiguration": "Xe 5d1 6s2",
"elementColor": [0.44, 0.83, 1.0],
"exactMass": 138.9063533,
"family": "Rare_Earth",
"group": 3,
"ionization": 5.5769,
"mass": 138.90547,
"meltingpoint": 1191.0,
"mostCommonIsotope": "La139",
"mostCommonIsotopeMass": 138.9063533,
"name": "<NAME>thanum",
"nameOrigin": "Greek 'lanthanein' for 'hidden'. The Lanthanoids are also called the 'rare earth' elements.",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.69,
"radiusCovalent": 1.69,
"radiusVDW": 2.5,
"symbol": "La",
"valences": []
}, {
"atomicNumber": 58,
"boilingpoint": 3715.0,
"discoverers": ["<NAME>\u00f6<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1803",
"electronAffinity": 0.5,
"electronegativityPauling": 1.12,
"electronicConfiguration": "Xe 4f1 5d1 6s2",
"elementColor": [1.0, 1.0, 0.78],
"exactMass": 139.9054387,
"family": "Rare_Earth",
"group": 4,
"ionization": 5.5387,
"mass": 140.116,
"meltingpoint": 1071.0,
"mostCommonIsotope": "Ce140",
"mostCommonIsotopeMass": 139.9054387,
"name": "<NAME>",
"nameOrigin": "Named after the planetoid Ceres",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.83,
"radiusVDW": 2.48,
"symbol": "Ce",
"valences": []
}, {
"atomicNumber": 59,
"boilingpoint": 3785.0,
"discoverers": "<NAME>",
"discoveryDate": "1885",
"electronAffinity": 0.5,
"electronegativityPauling": 1.13,
"electronicConfiguration": "Xe 4f3 6s2",
"elementColor": [0.85, 1.0, 0.78],
"exactMass": 140.9076528,
"family": "Rare_Earth",
"group": 5,
"ionization": 5.473,
"mass": 140.90765,
"meltingpoint": 1204.0,
"mostCommonIsotope": "Pr141",
"mostCommonIsotopeMass": 140.9076528,
"name": "<NAME>",
"nameOrigin": "Greek 'prasinos didymos' for 'green twin'",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.82,
"radiusVDW": 2.47,
"symbol": "Pr",
"valences": []
}, {
"atomicNumber": 60,
"boilingpoint": 3347.0,
"discoverers": "<NAME>",
"discoveryDate": "1885",
"electronAffinity": 0.5,
"electronegativityPauling": 1.14,
"electronicConfiguration": "Xe 4f4 6s2",
"elementColor": [0.78, 1.0, 0.78],
"exactMass": 141.9077233,
"family": "Rare_Earth",
"group": 6,
"ionization": 5.525,
"mass": 144.242,
"meltingpoint": 1294.0,
"mostCommonIsotope": "Nd142",
"mostCommonIsotopeMass": 141.9077233,
"name": "<NAME>odymium",
"nameOrigin": "Greek 'neos didymos' for 'new twin'",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.81,
"radiusVDW": 2.45,
"symbol": "Nd",
"valences": []
}, {
"atomicNumber": 61,
"boilingpoint": 3273.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1945",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f5 6s2",
"elementColor": [0.64, 1.0, 0.78],
"exactMass": 144.912749,
"family": "Rare_Earth",
"group": 7,
"ionization": 5.582,
"mass": 145.0,
"meltingpoint": 1315.0,
"mostCommonIsotope": "Pm145",
"mostCommonIsotopeMass": 144.912749,
"name": "<NAME>",
"nameOrigin": "Named after the Greek Prometheus. Prometheus stole the fire from the gods and gave it to mankind.",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.8,
"radiusVDW": 2.43,
"symbol": "Pm",
"valences": []
}, {
"atomicNumber": 62,
"boilingpoint": 2067.0,
"discoverers": "<NAME>",
"discoveryDate": "1879",
"electronAffinity": 0.5,
"electronegativityPauling": 1.17,
"electronicConfiguration": "Xe 4f6 6s2",
"elementColor": [0.56, 1.0, 0.78],
"exactMass": 151.9197324,
"family": "Rare_Earth",
"group": 8,
"ionization": 5.6437,
"mass": 150.36,
"meltingpoint": 1347.0,
"mostCommonIsotope": "Sm152",
"mostCommonIsotopeMass": 151.9197324,
"name": "<NAME>",
"nameOrigin": "Named after the mineral <NAME>",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.8,
"radiusVDW": 2.42,
"symbol": "Sm",
"valences": []
}, {
"atomicNumber": 63,
"boilingpoint": 1800.0,
"discoverers": "<NAME>",
"discoveryDate": "1901",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f7 6s2",
"elementColor": [0.38, 1.0, 0.78],
"exactMass": 152.9212303,
"family": "Rare_Earth",
"group": 8,
"ionization": 5.6704,
"mass": 151.964,
"meltingpoint": 1095.0,
"mostCommonIsotope": "Eu153",
"mostCommonIsotopeMass": 152.9212303,
"name": "<NAME>",
"nameOrigin": "Named after Europe",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.99,
"radiusVDW": 2.4,
"symbol": "Eu",
"valences": []
}, {
"atomicNumber": 64,
"boilingpoint": 3545.0,
"discoverers": "<NAME>",
"discoveryDate": "1880",
"electronAffinity": 0.5,
"electronegativityPauling": 1.2,
"electronicConfiguration": "Xe 4f7 5d1 6s2",
"elementColor": [0.27, 1.0, 0.78],
"exactMass": 157.9241039,
"family": "Rare_Earth",
"group": 8,
"ionization": 6.1498,
"mass": 157.25,
"meltingpoint": 1585.0,
"mostCommonIsotope": "Gd158",
"mostCommonIsotopeMass": 157.9241039,
"name": "<NAME>",
"nameOrigin": "Named after the Finnish chemist <NAME>",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.79,
"radiusVDW": 2.38,
"symbol": "Gd",
"valences": []
}, {
"atomicNumber": 65,
"boilingpoint": 3500.0,
"discoverers": "<NAME>",
"discoveryDate": "1843",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f9 6s2",
"elementColor": [0.19, 1.0, 0.78],
"exactMass": 158.9253468,
"family": "Rare_Earth",
"group": 1,
"ionization": 5.8638,
"mass": 158.92535,
"meltingpoint": 1629.0,
"mostCommonIsotope": "Tb159",
"mostCommonIsotopeMass": 158.9253468,
"name": "<NAME>",
"nameOrigin": "Named after the Swedish town of Ytterby",
"outshellElectrons": 9,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.76,
"radiusVDW": 2.37,
"symbol": "Tb",
"valences": []
}, {
"atomicNumber": 66,
"boilingpoint": 2840.0,
"discoverers": "<NAME>",
"discoveryDate": "1886",
"electronAffinity": 0.5,
"electronegativityPauling": 1.22,
"electronicConfiguration": "Xe 4f10 6s2",
"elementColor": [0.12, 1.0, 0.78],
"exactMass": 163.9291748,
"family": "Rare_Earth",
"group": 2,
"ionization": 5.9389,
"mass": 162.5,
"meltingpoint": 1685.0,
"mostCommonIsotope": "Dy164",
"mostCommonIsotopeMass": 163.9291748,
"name": "<NAME>",
"nameOrigin": "Greek 'dysprositor' for 'difficult to reach'",
"outshellElectrons": 10,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.75,
"radiusVDW": 2.35,
"symbol": "Dy",
"valences": []
}, {
"atomicNumber": 67,
"boilingpoint": 2968.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryDate": "1878",
"electronAffinity": 0.5,
"electronegativityPauling": 1.23,
"electronicConfiguration": "Xe 4f11 6s2",
"elementColor": [0.0, 1.0, 0.61],
"exactMass": 164.9303221,
"family": "Rare_Earth",
"group": 3,
"ionization": 6.0215,
"mass": 164.93032,
"meltingpoint": 1747.0,
"mostCommonIsotope": "Ho165",
"mostCommonIsotopeMass": 164.9303221,
"name": "<NAME>",
"nameOrigin": "Latin 'holmia' for the old name of Stockholm",
"outshellElectrons": 11,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.74,
"radiusVDW": 2.33,
"symbol": "Ho",
"valences": []
}, {
"atomicNumber": 68,
"boilingpoint": 3140.0,
"discoverers": "<NAME>",
"discoveryDate": "1843",
"electronAffinity": 0.5,
"electronegativityPauling": 1.24,
"electronicConfiguration": "Xe 4f12 6s2",
"elementColor": [0.0, 0.9, 0.46],
"exactMass": 165.9302931,
"family": "Rare_Earth",
"group": 4,
"ionization": 6.1077,
"mass": 167.259,
"meltingpoint": 1802.0,
"mostCommonIsotope": "Er166",
"mostCommonIsotopeMass": 165.9302931,
"name": "<NAME>",
"nameOrigin": "Named ofter the Swedish town of Ytterby. Terbium and Ytterbium are also named after this town.",
"outshellElectrons": 12,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.73,
"radiusVDW": 2.32,
"symbol": "Er",
"valences": []
}, {
"atomicNumber": 69,
"boilingpoint": 2223.0,
"discoverers": "<NAME>",
"discoveryDate": "1879",
"electronAffinity": 0.5,
"electronegativityPauling": 1.25,
"electronicConfiguration": "Xe 4f13 6s2",
"elementColor": [0.0, 0.83, 0.32],
"exactMass": 168.9342133,
"family": "Rare_Earth",
"group": 5,
"ionization": 6.1843,
"mass": 168.93421,
"meltingpoint": 1818.0,
"mostCommonIsotope": "Tm169",
"mostCommonIsotopeMass": 168.9342133,
"name": "<NAME>",
"nameOrigin": "Named after the old name of Scandinavia, '<NAME>'.",
"outshellElectrons": 13,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.72,
"radiusVDW": 2.3,
"symbol": "Tm",
"valences": []
}, {
"atomicNumber": 70,
"boilingpoint": 1469.0,
"discoverers": "<NAME>",
"discoveryDate": "1878",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f14 6s2",
"elementColor": [0.0, 0.75, 0.22],
"exactMass": 173.9388621,
"family": "Rare_Earth",
"group": 6,
"ionization": 6.2542,
"mass": 173.054,
"meltingpoint": 1092.0,
"mostCommonIsotope": "Yb174",
"mostCommonIsotopeMass": 173.9388621,
"name": "<NAME>",
"nameOrigin": "Like <NAME> and <NAME>ium, this is named after the Swedish town of <NAME>by.",
"outshellElectrons": 14,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.94,
"radiusVDW": 2.28,
"symbol": "Yb",
"valences": []
}, {
"atomicNumber": 71,
"boilingpoint": 3668.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryDate": "1907",
"electronAffinity": 0.5,
"electronegativityPauling": 1.27,
"electronicConfiguration": "Xe 4f14 5d1 6s2",
"elementColor": [0.0, 0.67, 0.14],
"exactMass": 174.9407718,
"family": "Rare_Earth",
"group": 7,
"ionization": 5.4259,
"mass": 174.9668,
"meltingpoint": 1936.0,
"mostCommonIsotope": "Lu175",
"mostCommonIsotopeMass": 174.9407718,
"name": "<NAME>",
"nameOrigin": "Named after the Roman name '<NAME>' for Paris",
"outshellElectrons": 15,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.72,
"radiusCovalent": 1.6,
"radiusVDW": 2.27,
"symbol": "Lu",
"valences": []
}, {
"atomicNumber": 72,
"boilingpoint": 4875.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "dk",
"discoveryDate": "1923",
"electronAffinity": 0.0,
"electronegativityPauling": 1.3,
"electronicConfiguration": "Xe 4f14 5d2 6s2",
"elementColor": [0.3, 0.76, 1.0],
"exactMass": 179.94655,
"family": "Transition",
"group": 4,
"ionization": 6.8251,
"mass": 178.49,
"meltingpoint": 2504.0,
"mostCommonIsotope": "Hf180",
"mostCommonIsotopeMass": 179.94655,
"name": "<NAME>",
"nameOrigin": "'<NAME>' is the old name of Kopen<NAME> (Denmark)",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.44,
"radiusCovalent": 1.5,
"radiusVDW": 2.25,
"symbol": "Hf",
"valences": []
}, {
"atomicNumber": 73,
"boilingpoint": 5730.0,
"discoverers": "<NAME>",
"discoveryCountry": "se",
"discoveryDate": "1802",
"electronAffinity": 0.322,
"electronegativityPauling": 1.5,
"electronicConfiguration": "Xe 4f14 5d3 6s2",
"elementColor": [0.3, 0.65, 1.0],
"exactMass": 180.9479958,
"family": "Transition",
"group": 5,
"ionization": 7.5496,
"mass": 180.94788,
"meltingpoint": 3293.0,
"mostCommonIsotope": "Ta181",
"mostCommonIsotopeMass": 180.9479958,
"name": "<NAME>",
"nameOrigin": "Named after the Greek myth of <NAME>",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.38,
"radiusVDW": 2.2,
"symbol": "<NAME>",
"valences": []
}, {
"atomicNumber": 74,
"boilingpoint": 5825.0,
"discoverers": "<NAME>",
"discoveryCountry": "es",
"discoveryDate": "1783",
"electronAffinity": 0.815,
"electronegativityPauling": 2.36,
"electronicConfiguration": "Xe 4f14 5d4 6s2",
"elementColor": [0.13, 0.58, 0.84],
"exactMass": 183.9509312,
"family": "Transition",
"group": 6,
"ionization": 7.864,
"mass": 183.84,
"meltingpoint": 3695.0,
"mostCommonIsotope": "W184",
"mostCommonIsotopeMass": 183.9509312,
"name": "<NAME>",
"nameOrigin": "'tung sten' means 'heavy stone' in Swedish. The old name (and thus the symbol 'W') was <NAME>ol<NAME>, named after a mineral.",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.46,
"radiusVDW": 2.1,
"symbol": "W",
"valences": []
}, {
"atomicNumber": 75,
"boilingpoint": 5870.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryCountry": "de",
"discoveryDate": "1925",
"electronAffinity": 0.15,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Xe 4f14 5d5 6s2",
"elementColor": [0.15, 0.49, 0.67],
"exactMass": 186.9557531,
"family": "Transition",
"group": 7,
"ionization": 7.8335,
"mass": 186.207,
"meltingpoint": 3455.0,
"mostCommonIsotope": "Re187",
"mostCommonIsotopeMass": 186.9557531,
"name": "<NAME>",
"nameOrigin": "Named after the German river Rhine (latin 'Rhenium').",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.28,
"radiusCovalent": 1.59,
"radiusVDW": 2.05,
"symbol": "Re",
"valences": []
}, {
"atomicNumber": 76,
"boilingpoint": 5300.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1804",
"electronAffinity": 1.0778,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d6 6s2",
"elementColor": [0.15, 0.4, 0.59],
"exactMass": 191.9614807,
"family": "Transition",
"group": 8,
"ionization": 8.4382,
"mass": 190.23,
"meltingpoint": 3300.0,
"mostCommonIsotope": "Os192",
"mostCommonIsotopeMass": 191.9614807,
"name": "<NAME>",
"nameOrigin": "Greek for 'smell'. Its oxides smell strongly like radishes.",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.26,
"radiusCovalent": 1.28,
"radiusVDW": 2.0,
"symbol": "Os",
"valences": []
}, {
"atomicNumber": 77,
"boilingpoint": 4700.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1804",
"electronAffinity": 1.56436,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d7 6s2",
"elementColor": [0.09, 0.33, 0.53],
"exactMass": 192.9629264,
"family": "Transition",
"group": 8,
"ionization": 8.967,
"mass": 192.217,
"meltingpoint": 2720.0,
"mostCommonIsotope": "Ir193",
"mostCommonIsotopeMass": 192.9629264,
"name": "<NAME>",
"nameOrigin": "Greek 'iris' for 'rainbow'",
"outshellElectrons": 9,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.27,
"radiusCovalent": 1.37,
"radiusVDW": 2.0,
"symbol": "Ir",
"valences": []
}, {
"atomicNumber": 78,
"boilingpoint": 4100.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1735",
"electronAffinity": 2.1251,
"electronegativityPauling": 2.28,
"electronicConfiguration": "Xe 4f14 5d9 6s1",
"elementColor": [0.96, 0.93, 0.82],
"exactMass": 194.9647911,
"family": "Transition",
"group": 8,
"ionization": 8.9588,
"mass": 195.084,
"meltingpoint": 2042.1,
"mostCommonIsotope": "Pt195",
"mostCommonIsotopeMass": 194.9647911,
"name": "<NAME>",
"nameOrigin": "Spanish 'platina' means 'small silver'",
"outshellElectrons": 10,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.28,
"radiusVDW": 2.05,
"symbol": "Pt",
"valences": []
}, {
"atomicNumber": 79,
"boilingpoint": 3130.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 2.30861,
"electronegativityPauling": 2.54,
"electronicConfiguration": "Xe 4f14 5d10 6s1",
"elementColor": [0.8, 0.82, 0.12],
"exactMass": 196.9665687,
"family": "Transition",
"group": 1,
"ionization": 9.2255,
"mass": 196.966569,
"meltingpoint": 1337.58,
"mostCommonIsotope": "Au197",
"mostCommonIsotopeMass": 196.9665687,
"name": "<NAME>",
"nameOrigin": "Latin 'aurum'. Named after <NAME>urora, the goddess of sunrise",
"outshellElectrons": 11,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.44,
"radiusVDW": 2.1,
"symbol": "Au",
"valences": []
}, {
"atomicNumber": 80,
"boilingpoint": 629.88,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.0,
"electronegativityPauling": 2.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2",
"elementColor": [0.71, 0.71, 0.76],
"exactMass": 201.970643,
"family": "Transition",
"group": 2,
"ionization": 10.4375,
"mass": 200.59,
"meltingpoint": 234.31,
"mostCommonIsotope": "Hg202",
"mostCommonIsotopeMass": 201.970643,
"name": "<NAME>",
"nameOrigin": "Graeco-Latin 'hydrargyrum' for 'liquid silver'",
"outshellElectrons": 2,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.49,
"radiusCovalent": 1.49,
"radiusVDW": 2.05,
"symbol": "Hg",
"valences": []
}, {
"atomicNumber": 81,
"boilingpoint": 1746.0,
"discoverers": "<NAME>",
"discoveryCountry": "uk",
"discoveryDate": "1861",
"electronAffinity": 0.377,
"electronegativityPauling": 1.62,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p1",
"elementColor": [0.65, 0.33, 0.3],
"exactMass": 204.9744275,
"family": "Other_Metal",
"group": 3,
"ionization": 6.1082,
"mass": 204.3833,
"meltingpoint": 577.0,
"mostCommonIsotope": "Tl205",
"mostCommonIsotopeMass": 204.9744275,
"name": "<NAME>",
"nameOrigin": "Greek 'tallos' for 'young twig'",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.48,
"radiusCovalent": 1.48,
"radiusVDW": 2.2,
"symbol": "Tl",
"valences": [3]
}, {
"atomicNumber": 82,
"boilingpoint": 2023.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.364,
"electronegativityPauling": 2.33,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p2",
"elementColor": [0.34, 0.35, 0.38],
"exactMass": 207.9766521,
"family": "Other_Metal",
"group": 4,
"ionization": 7.4167,
"mass": 207.2,
"meltingpoint": 600.65,
"mostCommonIsotope": "Pb208",
"mostCommonIsotopeMass": 207.9766521,
"name": "<NAME>",
"nameOrigin": "Latin 'plumbum' for <NAME>",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.48,
"radiusCovalent": 1.47,
"radiusVDW": 2.3,
"symbol": "Pb",
"valences": [4]
}, {
"atomicNumber": 83,
"boilingpoint": 1837.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.942363,
"electronegativityPauling": 2.02,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p3",
"elementColor": [0.62, 0.31, 0.71],
"exactMass": 208.9803987,
"family": "Other_Metal",
"group": 5,
"ionization": 7.2855,
"mass": 208.9804,
"meltingpoint": 544.59,
"mostCommonIsotope": "Bi209",
"mostCommonIsotopeMass": 208.9803987,
"name": "<NAME>",
"nameOrigin": "The old name of <NAME> is '<NAME>', which stood for 'white mass'.",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.45,
"radiusCovalent": 1.46,
"radiusVDW": 2.3,
"symbol": "Bi",
"valences": [3]
}, {
"atomicNumber": 84,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "fr",
"discoveryDate": "1898",
"electronAffinity": 1.9,
"electronegativityPauling": 2.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p4",
"elementColor": [0.67, 0.36, 0.0],
"exactMass": 208.9824304,
"family": "Metalloids",
"group": 6,
"ionization": 8.414,
"mass": 209.0,
"meltingpoint": 527.0,
"mostCommonIsotope": "Po209",
"mostCommonIsotopeMass": 208.9824304,
"name": "<NAME>",
"nameOrigin": "Named after Poland to honor <NAME>",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.46,
"radiusVDW": 2.0,
"symbol": "Po",
"valences": [2]
}, {
"atomicNumber": 85,
"boilingpoint": 610.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryCountry": "us",
"discoveryDate": "1940",
"electronAffinity": 2.8,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p5",
"elementColor": [0.46, 0.31, 0.27],
"exactMass": 209.987148,
"family": "Halogen",
"group": 7,
"ionization": 0.0,
"mass": 210.0,
"meltingpoint": 575.0,
"mostCommonIsotope": "At210",
"mostCommonIsotopeMass": 209.987148,
"name": "<NAME>",
"nameOrigin": "Greek 'astator' for 'changing'",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.45,
"radiusVDW": 2.0,
"symbol": "At",
"valences": [1]
}, {
"atomicNumber": 86,
"boilingpoint": 211.4,
"discoverers": "<NAME>",
"discoveryCountry": "de",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p6",
"elementColor": [0.26, 0.51, 0.59],
"exactMass": 222.0175777,
"family": "Noblegas",
"group": 8,
"ionization": 10.7485,
"mass": 222.0,
"meltingpoint": 202.0,
"mostCommonIsotope": "Rn211",
"mostCommonIsotopeMass": 210.990601,
"name": "<NAME>",
"nameOrigin": "Named after Radium. It ends with 'on' to make it clear that it is a noble gas.",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "p",
"rB0": 2.4,
"radiusCovalent": 1.45,
"radiusVDW": 2.0,
"symbol": "Rn",
"valences": [0]
}, {
"atomicNumber": 87,
"boilingpoint": 950.0,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1939",
"electronegativityPauling": 0.7,
"electronicConfiguration": "Rn 7s1",
"elementColor": [0.26, 0.0, 0.4],
"exactMass": 223.0197359,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.0727,
"mass": 223.0,
"meltingpoint": 300.0,
"mostCommonIsotope": "Fr223",
"mostCommonIsotopeMass": 223.0197359,
"name": "<NAME>",
"nameOrigin": "Named after France to honor Marguerite Perey",
"outshellElectrons": 1,
"period": 7,
"periodTableBlock": "s",
"rB0": 2.0,
"radiusVDW": 2.0,
"symbol": "Fr",
"valences": [1]
}, {
"atomicNumber": 88,
"boilingpoint": 1413.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryCountry": "fr",
"discoveryDate": "1898",
"electronegativityPauling": 0.9,
"electronicConfiguration": "Rn 7s2",
"elementColor": [0.0, 0.49, 0.0],
"exactMass": 226.0254098,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.2784,
"mass": 226.0,
"meltingpoint": 973.0,
"mostCommonIsotope": "Ra223",
"mostCommonIsotopeMass": 223.0185022,
"name": "<NAME>",
"nameOrigin": "Latin 'radius' for 'beam', as it is radioactive",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "s",
"rB0": 1.9,
"radiusVDW": 2.0,
"symbol": "Ra",
"valences": [2]
}, {
"atomicNumber": 89,
"boilingpoint": 3470.0,
"discoverers": "<NAME>",
"discoveryCountry": "fr",
"discoveryDate": "1899",
"electronegativityPauling": 1.1,
"electronicConfiguration": "Rn 6d1 7s2",
"elementColor": [0.44, 0.67, 0.98],
"exactMass": 227.0277521,
"family": "Other_Metal",
"group": 3,
"ionization": 5.17,
"mass": 227.0,
"meltingpoint": 1324.0,
"mostCommonIsotope": "Ac227",
"mostCommonIsotopeMass": 227.0277521,
"name": "<NAME>",
"nameOrigin": "Greek 'aktis' for 'beam' - actinium is radioactive",
"outshellElectrons": 3,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.88,
"radiusVDW": 2.0,
"symbol": "Ac",
"valences": []
}, {
"atomicNumber": 90,
"boilingpoint": 5060.0,
"discoverers": "<NAME>",
"discoveryDate": "1828",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 6d2 7s2",
"elementColor": [0.0, 0.73, 1.0],
"exactMass": 232.0380553,
"family": "Other_Metal",
"group": 4,
"ionization": 6.3067,
"mass": 232.03806,
"meltingpoint": 2028.0,
"mostCommonIsotope": "Th232",
"mostCommonIsotopeMass": 232.0380553,
"name": "<NAME>",
"nameOrigin": "Named after the German god of thunder: <NAME>",
"outshellElectrons": 4,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.79,
"radiusVDW": 2.4,
"symbol": "Th",
"valences": []
}, {
"atomicNumber": 91,
"boilingpoint": 4300.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1917",
"electronegativityPauling": 1.5,
"electronicConfiguration": "Rn 5f2 6d1 7s2",
"elementColor": [0.0, 0.63, 1.0],
"exactMass": 231.035884,
"family": "Other_Metal",
"group": 5,
"ionization": 5.89,
"mass": 231.03588,
"meltingpoint": 1845.0,
"mostCommonIsotope": "Pa231",
"mostCommonIsotopeMass": 231.035884,
"name": "Protactinium",
"nameOrigin": "Greek 'protos' for 'ancester'. Protactinium is before Actinium in the periodic table.",
"outshellElectrons": 3,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.61,
"radiusVDW": 2.0,
"symbol": "Pa",
"valences": []
}, {
"atomicNumber": 92,
"boilingpoint": 4407.0,
"discoverers": "<NAME>",
"discoveryDate": "1789",
"electronegativityPauling": 1.38,
"electronicConfiguration": "Rn 5f3 6d1 7s2",
"elementColor": [0.0, 0.56, 1.0],
"exactMass": 238.0507882,
"family": "Other_Metal",
"group": 6,
"ionization": 6.1941,
"mass": 238.02891,
"meltingpoint": 1408.0,
"mostCommonIsotope": "U238",
"mostCommonIsotopeMass": 238.0507882,
"name": "<NAME>",
"nameOrigin": "Greek 'ouranos' for 'heaven'. Named after the planet Uranus.",
"outshellElectrons": 4,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.58,
"radiusVDW": 2.3,
"symbol": "U",
"valences": []
}, {
"atomicNumber": 93,
"boilingpoint": 4175.0,
"discoverers": ["<NAME>", "<NAME>"],
"discoveryDate": "1940",
"electronegativityPauling": 1.36,
"electronicConfiguration": "Rn 5f4 6d1 7s2",
"elementColor": [0.0, 0.5, 1.0],
"exactMass": 237.0481734,
"family": "Other_Metal",
"group": 7,
"ionization": 6.2657,
"mass": 237.0,
"meltingpoint": 912.0,
"mostCommonIsotope": "Np236",
"mostCommonIsotopeMass": 236.04657,
"name": "<NAME>",
"nameOrigin": "Named after the planet Neptune.",
"outshellElectrons": 5,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.55,
"radiusVDW": 2.0,
"symbol": "Np",
"valences": []
}, {
"atomicNumber": 94,
"boilingpoint": 3505.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1940",
"electronegativityPauling": 1.28,
"electronicConfiguration": "Rn 5f6 7s2",
"elementColor": [0.0, 0.42, 1.0],
"exactMass": 244.064204,
"family": "Other_Metal",
"group": 8,
"ionization": 6.026,
"mass": 244.0,
"meltingpoint": 913.0,
"mostCommonIsotope": "Pu238",
"mostCommonIsotopeMass": 238.0495599,
"name": "<NAME>utonium",
"nameOrigin": "Named after the planet Pluto.",
"outshellElectrons": 6,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.53,
"radiusVDW": 2.0,
"symbol": "Pu",
"valences": []
}, {
"atomicNumber": 95,
"boilingpoint": 2880.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1945",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f7 7s2",
"elementColor": [0.33, 0.36, 0.95],
"exactMass": 243.0613811,
"family": "Other_Metal",
"group": 8,
"ionization": 5.9738,
"mass": 243.0,
"meltingpoint": 1449.0,
"mostCommonIsotope": "Am241",
"mostCommonIsotopeMass": 241.0568291,
"name": "<NAME>icium",
"nameOrigin": "Named after America.",
"outshellElectrons": 7,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.07,
"radiusVDW": 2.0,
"symbol": "Am",
"valences": []
}, {
"atomicNumber": 96,
"boilingpoint": 3383.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1944",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f7 6d1 7s2",
"elementColor": [0.47, 0.36, 0.89],
"exactMass": 247.070354,
"family": "Other_Metal",
"group": 8,
"ionization": 5.9914,
"mass": 247.0,
"meltingpoint": 1620.0,
"mostCommonIsotope": "Cm243",
"mostCommonIsotopeMass": 243.0613891,
"name": "<NAME>",
"nameOrigin": "Named after <NAME>.",
"outshellElectrons": 8,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Cm",
"valences": []
}, {
"atomicNumber": 97,
"boilingpoint": 983.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1949",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f9 7s2",
"elementColor": [0.54, 0.31, 0.89],
"exactMass": 247.070307,
"family": "Other_Metal",
"group": 1,
"ionization": 6.1979,
"mass": 247.0,
"meltingpoint": 1258.0,
"mostCommonIsotope": "Bk247",
"mostCommonIsotopeMass": 247.070307,
"name": "<NAME>",
"nameOrigin": "Named after the town Berkeley where it was discovered.",
"outshellElectrons": 9,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Bk",
"valences": []
}, {
"atomicNumber": 98,
"boilingpoint": 1173.0,
"discoverers": ["<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1950",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f10 7s2",
"elementColor": [0.63, 0.21, 0.83],
"exactMass": 251.079587,
"family": "Other_Metal",
"group": 2,
"ionization": 6.2817,
"mass": 251.0,
"meltingpoint": 1172.0,
"mostCommonIsotope": "Cf249",
"mostCommonIsotopeMass": 249.0748535,
"name": "<NAME>",
"nameOrigin": "Named after the US-State of California.",
"outshellElectrons": 10,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Cf",
"valences": []
}, {
"atomicNumber": 99,
"discoverers": ["<NAME>", "et al."],
"discoveryDate": "1952",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f11 7s2",
"elementColor": [0.7, 0.12, 0.83],
"exactMass": 252.08298,
"family": "Other_Metal",
"group": 3,
"ionization": 6.42,
"mass": 252.0,
"meltingpoint": 1130.0,
"mostCommonIsotope": "Es252",
"mostCommonIsotopeMass": 252.08298,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 11,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Es",
"valences": []
}, {
"atomicNumber": 100,
"discoverers": ["<NAME>", "et al."],
"discoveryDate": "1953",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f12 7s2",
"elementColor": [0.7, 0.12, 0.73],
"exactMass": 257.095105,
"family": "Other_Metal",
"group": 4,
"ionization": 6.5,
"mass": 257.0,
"meltingpoint": 1800.0,
"mostCommonIsotope": "Fm257",
"mostCommonIsotopeMass": 257.095105,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 12,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Fm",
"valences": []
}, {
"atomicNumber": 101,
"discoverers": ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1955",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f13 7s2",
"elementColor": [0.7, 0.05, 0.65],
"exactMass": 258.098431,
"family": "Other_Metal",
"group": 5,
"ionization": 6.58,
"mass": 258.0,
"meltingpoint": 1100.0,
"mostCommonIsotope": "Md258",
"mostCommonIsotopeMass": 258.098431,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 13,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Md",
"valences": []
}, {
"atomicNumber": 102,
"discoveryDate": "1958",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f14 7s2",
"elementColor": [0.74, 0.05, 0.53],
"exactMass": 259.10103,
"family": "Other_Metal",
"group": 6,
"ionization": 6.65,
"mass": 259.0,
"meltingpoint": 1100.0,
"mostCommonIsotope": "No259",
"mostCommonIsotopeMass": 259.10103,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 14,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "No",
"valences": []
}, {
"atomicNumber": 103,
"discoverers": ["<NAME>", "<NAME>", "<NAME>", "<NAME>"],
"discoveryDate": "1961",
"electronicConfiguration": "Rn 5f14 7s2 7p1",
"elementColor": [0.78, 0.0, 0.4],
"exactMass": 262.10963,
"family": "Other_Metal",
"group": 7,
"ionization": 4.9,
"mass": 262.0,
"meltingpoint": 1900.0,
"mostCommonIsotope": "Lr262",
"mostCommonIsotopeMass": 262.10963,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 15,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Lr",
"valences": []
}, {
"atomicNumber": 104,
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1964",
"electronicConfiguration": "Rn 5f14 6d2 7s2",
"elementColor": [0.8, 0.0, 0.35],
"exactMass": 261.10877,
"family": "Transition",
"group": 4,
"ionization": 6.0,
"mass": 267.0,
"mostCommonIsotope": "Rf267",
"mostCommonIsotopeMass": 267.12153,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Rf",
"valences": []
}, {
"atomicNumber": 105,
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1967",
"electronicConfiguration": "Rn 5f14 6d3 7s2",
"elementColor": [0.82, 0.0, 0.31],
"exactMass": 262.11408,
"family": "Transition",
"group": 5,
"mass": 268.0,
"mostCommonIsotope": "Db268",
"mostCommonIsotopeMass": 268.12545,
"name": "<NAME>",
"nameOrigin": "Named after the science-town Dubna in Russia",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Db",
"valences": []
}, {
"atomicNumber": 106,
"discoverers": ["<NAME>", "et al."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1974",
"elementColor": [0.85, 0.0, 0.27],
"exactMass": 263.11832,
"family": "Transition",
"group": 6,
"mass": 271.0,
"mostCommonIsotope": "Sg271",
"mostCommonIsotopeMass": 271.13347,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Sg",
"valences": []
}, {
"atomicNumber": 107,
"discoverers": ["<NAME>", "<NAME>\u00fc<NAME>", "et al."],
"discoveryCountry": "ru",
"discoveryDate": "1981",
"elementColor": [0.88, 0.0, 0.22],
"exactMass": 264.1246,
"family": "Transition",
"group": 7,
"mass": 272.0,
"mostCommonIsotope": "Bh270",
"mostCommonIsotopeMass": 270.13362,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Bh",
"valences": []
}, {
"atomicNumber": 108,
"discoverers": ["<NAME>", "<NAME>\u00fc<NAME>", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1984",
"elementColor": [0.9, 0.0, 0.18],
"exactMass": 265.13009,
"family": "Transition",
"group": 8,
"mass": 270.0,
"mostCommonIsotope": "Hs269",
"mostCommonIsotopeMass": 269.13406,
"name": "<NAME>",
"nameOrigin": "Latin 'hassia' for the German county Hessen. In Hessen a lot elements have been discovered.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Hs",
"valences": []
}, {
"atomicNumber": 109,
"discoverers": ["<NAME>", "<NAME>\u00fcn<NAME>", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1982",
"elementColor": [0.91, 0.0, 0.15],
"exactMass": 268.13873,
"family": "Transition",
"group": 8,
"mass": 276.0,
"mostCommonIsotope": "Mt278",
"mostCommonIsotopeMass": 278.15481,
"name": "<NAME>",
"nameOrigin": "Named after the scientist <NAME>.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Mt",
"valences": []
}, {
"atomicNumber": 110,
"discoverers": ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>\u00fc<NAME>",
"<NAME>\u00f6<NAME>", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1994",
"elementColor": [0.92, 0.0, 0.14],
"exactMass": 271.14606,
"family": "Transition",
"group": 8,
"mass": 281.0,
"mostCommonIsotope": "Ds281",
"mostCommonIsotopeMass": 281.16206,
"name": "<NAME>",
"nameOrigin": "Named after the German city Darmstadt where many elements have been discovered.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Ds",
"valences": []
}, {
"atomicNumber": 111,
"discoverers": ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>00fc<NAME>",
"et al."],
"discoveryCountry": "de",
"discoveryDate": "1994",
"elementColor": [0.93, 0.0, 0.13],
"exactMass": 272.15362,
"family": "Transition",
"group": 1,
"mass": 280.0,
"mostCommonIsotope": "Rg281",
"mostCommonIsotopeMass": 281.16537,
"name": "<NAME>",
"nameOrigin": "Named after <NAME>\u00f6<NAME>.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Rg",
"valences": []
}, {
"atomicNumber": 112,
"discoverers": "First created at the Gesellschaft f\u00fcr Schwerionenforschung",
"discoveryCountry": "de",
"discoveryDate": "1996",
"elementColor": [0.94, 0.0, 0.12],
"exactMass": 285.17411,
"family": "Transition",
"mass": 285.0,
"mostCommonIsotope": "Cn285",
"mostCommonIsotopeMass": 285.17411,
"name": "<NAME>",
"nameOrigin": "Historically known as eka-mercury. Ununbium is a temporary IUPAC systematic element name.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Cn",
"valences": []
}, {
"atomicNumber": 113,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2003",
"elementColor": [0.95, 0.0, 0.11],
"exactMass": 284.17808,
"family": "Other_Metal",
"mass": 284.0,
"name": "<NAME>",
"nameOrigin": "Historically known as eka-thallium. Ununtrium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uut"
}, {
"atomicNumber": 114,
"discoverers": "Joint Institute for Nuclear Research",
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1998",
"elementColor": [0.96, 0.0, 0.1],
"exactMass": 289.18728,
"family": "Other_Metal",
"mass": 289.0,
"name": "<NAME>",
"nameOrigin": "Historically known as eka-lead. Ununquadium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuq"
}, {
"atomicNumber": 115,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2004",
"elementColor": [0.97, 0.0, 0.09],
"exactMass": 288.19249,
"family": "Other_Metal",
"mass": 288.0,
"name": "<NAME>",
"nameOrigin": "Historically known as eka-bismuth. Ununpentium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uup"
}, {
"atomicNumber": 116,
"discoverers": "Joint Institute for Nuclear Research",
"discoveryCountry": "ru",
"discoveryDate": "2000",
"elementColor": [0.98, 0.0, 0.08],
"exactMass": 292.19979,
"family": "Other_Metal",
"mass": 293.0,
"name": "<NAME>",
"nameOrigin": "Historically known as eka-polonium. Ununhexium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuh"
}, {
"atomicNumber": 117,
"discoveryDate": "0",
"elementColor": [0.99, 0.0, 0.07],
"family": "Halogen",
"name": "<NAME>",
"nameOrigin": "Temporary symbol and name. Can also be referred to as eka-astatine.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uus"
}, {
"atomicNumber": 118,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2002",
"elementColor": [1.0, 0.0, 0.06],
"family": "Noblegas",
"mass": 294.0,
"name": "<NAME>",
"nameOrigin": "Historically known as eka-radon, eka-emanation before 1960. Ununoctium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuo"
}]
} | true | define ->
{
"atoms": [{
"atomicNumber": 0,
"elementColor": [0.07, 0.5, 0.7],
"exactMass": 0.0,
"mass": 0.0,
"mostCommonIsotope": "Xx0",
"mostCommonIsotopeMass": 0.0,
"name": "PI:NAME:<NAME>END_PI",
"outshellElectrons": 0,
"rB0": 0.0,
"radiusCovalent": 0.0,
"radiusVDW": 0.0,
"symbol": "Xx",
"valences": []
}, {
"atomicNumber": 1,
"boilingpoint": 20.28,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1766",
"electronAffinity": 0.75420375,
"electronegativityPauling": 2.2,
"electronicConfiguration": "1s1",
"elementColor": [1.0, 1.0, 1.0],
"exactMass": 1.007825032,
"family": "Non-Metal",
"group": 1,
"ionization": 13.5984,
"mass": 1.00794,
"meltingpoint": 14.01,
"mostCommonIsotope": "H1",
"mostCommonIsotopeMass": 1.007825032,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'hydro' and 'gennao' for 'forms water'",
"outshellElectrons": 1,
"period": 1,
"periodTableBlock": "s",
"rB0": 0.33,
"radiusCovalent": 0.37,
"radiusVDW": 1.2,
"symbol": "H",
"valences": [1]
}, {
"atomicNumber": 2,
"boilingpoint": 4.216,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": ["se", "uk"],
"discoveryDate": "1895",
"electronAffinity": 0.0,
"electronicConfiguration": "1s2",
"elementColor": [0.85, 1.0, 1.0],
"exactMass": 4.002603254,
"family": "Noblegas",
"group": 8,
"ionization": 24.5874,
"mass": 4.002602,
"meltingpoint": 0.95,
"mostCommonIsotope": "He4",
"mostCommonIsotopeMass": 4.002603254,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "The Greek word for the sun was 'helios'",
"outshellElectrons": 2,
"period": 1,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.32,
"radiusVDW": 1.4,
"symbol": "He",
"valences": [0]
}, {
"atomicNumber": 3,
"boilingpoint": 1615.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1817",
"electronAffinity": 0.618049,
"electronegativityPauling": 0.98,
"electronicConfiguration": "He 2s1",
"elementColor": [0.8, 0.5, 1.0],
"exactMass": 7.01600455,
"family": "Alkali_Earth",
"group": 1,
"ionization": 5.3917,
"mass": 6.941,
"meltingpoint": 453.7,
"mostCommonIsotope": "Li7",
"mostCommonIsotopeMass": 7.01600455,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'lithos' means 'stone'",
"outshellElectrons": 1,
"period": 2,
"periodTableBlock": "s",
"rB0": 1.23,
"radiusCovalent": 1.34,
"radiusVDW": 2.2,
"symbol": "Li",
"valences": [1]
}, {
"atomicNumber": 4,
"boilingpoint": 3243.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1797",
"electronAffinity": 0.0,
"electronegativityPauling": 1.57,
"electronicConfiguration": "He 2s2",
"elementColor": [0.76, 1.0, 0.0],
"exactMass": 9.0121822,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 9.3227,
"mass": 9.012182,
"meltingpoint": 1560.0,
"mostCommonIsotope": "Be9",
"mostCommonIsotopeMass": 9.0121822,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'berPI:NAME:<NAME>END_PIlos' for 'light-green stone'",
"outshellElectrons": 2,
"period": 2,
"periodTableBlock": "s",
"rB0": 0.9,
"radiusCovalent": 0.9,
"radiusVDW": 1.9,
"symbol": "Be",
"valences": [2]
}, {
"atomicNumber": 5,
"boilingpoint": 4275.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": ["uk", "fr"],
"discoveryDate": "1808",
"electronAffinity": 0.279723,
"electronegativityPauling": 2.04,
"electronicConfiguration": "He 2s2 2p1",
"elementColor": [1.0, 0.71, 0.71],
"exactMass": 11.0093054,
"family": "Metalloids",
"group": 3,
"ionization": 8.298,
"mass": 10.811,
"meltingpoint": 2365.0,
"mostCommonIsotope": "B11",
"mostCommonIsotopeMass": 11.0093054,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "BorPI:NAME:<NAME>END_PI means 'Bor(ax) + (carb)on'. It is found in borax and behaves a lot like carbon",
"outshellElectrons": 3,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.82,
"radiusCovalent": 0.82,
"radiusVDW": 1.8,
"symbol": "B",
"valences": [3]
}, {
"atomicNumber": 6,
"boilingpoint": 5100.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.262118,
"electronegativityPauling": 2.55,
"electronicConfiguration": "He 2s2 2p2",
"elementColor": [0.5, 0.5, 0.5],
"exactMass": 12.0,
"family": "Non-Metal",
"group": 4,
"ionization": 11.2603,
"mass": 12.0107,
"meltingpoint": 3825.0,
"mostCommonIsotope": "C12",
"mostCommonIsotopeMass": 12.0,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'carboneum' for carbon",
"outshellElectrons": 4,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.77,
"radiusCovalent": 0.77,
"radiusVDW": 1.7,
"symbol": "C",
"valences": [4]
}, {
"atomicNumber": 7,
"boilingpoint": 77.344,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1772",
"electronAffinity": -0.07,
"electronegativityPauling": 3.04,
"electronicConfiguration": "He 2s2 2p3",
"elementColor": [0.05, 0.05, 1.0],
"exactMass": 14.003074,
"family": "Non-Metal",
"group": 5,
"ionization": 14.5341,
"mass": 14.0067,
"meltingpoint": 63.15,
"mostCommonIsotope": "N14",
"mostCommonIsotopeMass": 14.003074,
"name": "Nitrogen",
"nameOrigin": "Latin 'nitrogenium' ('forms saltpeter')",
"outshellElectrons": 5,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.75,
"radiusVDW": 1.6,
"symbol": "N",
"valences": [3]
}, {
"atomicNumber": 8,
"boilingpoint": 90.188,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": ["se", "uk"],
"discoveryDate": "1774",
"electronAffinity": 1.461112,
"electronegativityPauling": 3.44,
"electronicConfiguration": "He 2s2 2p4",
"elementColor": [1.0, 0.05, 0.05],
"exactMass": 15.99491462,
"family": "Non-Metal",
"group": 6,
"ionization": 13.6181,
"mass": 15.9994,
"meltingpoint": 54.8,
"mostCommonIsotope": "O16",
"mostCommonIsotopeMass": 15.99491462,
"name": "Oxygen",
"nameOrigin": "Latin 'oxygenium' (forms acids)",
"outshellElectrons": 6,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.66,
"radiusCovalent": 0.73,
"radiusVDW": 1.55,
"symbol": "O",
"valences": [2]
}, {
"atomicNumber": 9,
"boilingpoint": 85.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1886",
"electronAffinity": 3.4011887,
"electronegativityPauling": 3.98,
"electronicConfiguration": "He 2s2 2p5",
"elementColor": [0.7, 1.0, 1.0],
"exactMass": 18.99840322,
"family": "Halogen",
"group": 7,
"ionization": 17.4228,
"mass": 18.9984032,
"meltingpoint": 53.55,
"mostCommonIsotope": "F19",
"mostCommonIsotopeMass": 18.99840322,
"name": "Fluorine",
"nameOrigin": "Latin 'fluere' ('floats')",
"outshellElectrons": 7,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.611,
"radiusCovalent": 0.71,
"radiusVDW": 1.5,
"symbol": "F",
"valences": [1]
}, {
"atomicNumber": 10,
"boilingpoint": 27.1,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronicConfiguration": "He 2s2 2p6",
"elementColor": [0.7, 0.89, 0.96],
"exactMass": 19.99244018,
"family": "Noblegas",
"group": 8,
"ionization": 21.5645,
"mass": 20.1797,
"meltingpoint": 24.55,
"mostCommonIsotope": "Ne20",
"mostCommonIsotopeMass": 19.99244018,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'neo'. meaning 'new'",
"outshellElectrons": 8,
"period": 2,
"periodTableBlock": "p",
"rB0": 0.7,
"radiusCovalent": 0.69,
"radiusVDW": 1.54,
"symbol": "Ne",
"valences": [0]
}, {
"atomicNumber": 11,
"boilingpoint": 1156.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1807",
"electronAffinity": 0.547926,
"electronegativityPauling": 0.93,
"electronicConfiguration": "Ne 3s1",
"elementColor": [0.67, 0.36, 0.95],
"exactMass": 22.98976928,
"family": "Alkali_Earth",
"group": 1,
"ionization": 5.1391,
"mass": 22.98976928,
"meltingpoint": 371.0,
"mostCommonIsotope": "Na23",
"mostCommonIsotopeMass": 22.98976928,
"name": "Sodium",
"nameOrigin": "Arabic 'natrun' for 'soda'",
"outshellElectrons": 1,
"period": 3,
"periodTableBlock": "s",
"rB0": 1.54,
"radiusCovalent": 1.54,
"radiusVDW": 2.4,
"symbol": "Na",
"valences": [1]
}, {
"atomicNumber": 12,
"boilingpoint": 1380.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.0,
"electronegativityPauling": 1.31,
"electronicConfiguration": "Ne 3s2",
"elementColor": [0.54, 1.0, 0.0],
"exactMass": 23.9850417,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 7.6462,
"mass": 24.305,
"meltingpoint": 922.0,
"mostCommonIsotope": "Mg24",
"mostCommonIsotopeMass": 23.9850417,
"name": "PI:NAME:<NAME>END_PIagnesium",
"nameOrigin": "Named after the city of Magnesia",
"outshellElectrons": 2,
"period": 3,
"periodTableBlock": "s",
"rB0": 1.36,
"radiusCovalent": 1.3,
"radiusVDW": 2.2,
"symbol": "Mg",
"valences": [2]
}, {
"atomicNumber": 13,
"boilingpoint": 2740.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "dk",
"discoveryDate": "1825",
"electronAffinity": 0.43283,
"electronegativityPauling": 1.61,
"electronicConfiguration": "Ne 3s2 3p1",
"elementColor": [0.75, 0.65, 0.65],
"exactMass": 26.98153863,
"family": "Other_Metal",
"group": 3,
"ionization": 5.9858,
"mass": 26.9815386,
"meltingpoint": 933.5,
"mostCommonIsotope": "Al27",
"mostCommonIsotopeMass": 26.98153863,
"name": "Aluminium",
"nameOrigin": "Latin 'alumen'",
"outshellElectrons": 3,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.18,
"radiusCovalent": 1.18,
"radiusVDW": 2.1,
"symbol": "Al",
"valences": [6]
}, {
"atomicNumber": 14,
"boilingpoint": 2630.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1823",
"electronAffinity": 1.389521,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Ne 3s2 3p2",
"elementColor": [0.5, 0.6, 0.6],
"exactMass": 27.97692653,
"family": "Metalloids",
"group": 4,
"ionization": 8.1517,
"mass": 28.0855,
"meltingpoint": 1683.0,
"mostCommonIsotope": "Si28",
"mostCommonIsotopeMass": 27.97692653,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'silex'",
"outshellElectrons": 4,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.937,
"radiusCovalent": 1.11,
"radiusVDW": 2.1,
"symbol": "Si",
"valences": [4, 6]
}, {
"atomicNumber": 15,
"boilingpoint": 553.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1669",
"electronAffinity": 0.7465,
"electronegativityPauling": 2.19,
"electronicConfiguration": "Ne 3s2 3p3",
"elementColor": [1.0, 0.5, 0.0],
"exactMass": 30.97376163,
"family": "Non-Metal",
"group": 5,
"ionization": 10.4867,
"mass": 30.973762,
"meltingpoint": 317.3,
"mostCommonIsotope": "P31",
"mostCommonIsotopeMass": 30.97376163,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'phosphoros' for 'carries light'",
"outshellElectrons": 5,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.89,
"radiusCovalent": 1.06,
"radiusVDW": 1.95,
"symbol": "P",
"valences": [3, 5, 7]
}, {
"atomicNumber": 16,
"boilingpoint": 717.82,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 2.0771029,
"electronegativityPauling": 2.58,
"electronicConfiguration": "Ne 3s2 3p4",
"elementColor": [1.0, 1.0, 0.19],
"exactMass": 31.972071,
"family": "Non-Metal",
"group": 6,
"ionization": 10.36,
"mass": 32.065,
"meltingpoint": 392.2,
"mostCommonIsotope": "S32",
"mostCommonIsotopeMass": 31.972071,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "In sanskrit 'sweb' means 'to sleep'",
"outshellElectrons": 6,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.04,
"radiusCovalent": 1.02,
"radiusVDW": 1.8,
"symbol": "S",
"valences": [2, 4, 6]
}, {
"atomicNumber": 17,
"boilingpoint": 239.18,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1774",
"electronAffinity": 3.612724,
"electronegativityPauling": 3.16,
"electronicConfiguration": "Ne 3s2 3p5",
"elementColor": [0.12, 0.94, 0.12],
"exactMass": 34.96885268,
"family": "Halogen",
"group": 7,
"ionization": 12.9676,
"mass": 35.453,
"meltingpoint": 172.17,
"mostCommonIsotope": "Cl35",
"mostCommonIsotopeMass": 34.96885268,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'chloros' for 'yellow-green'",
"outshellElectrons": 7,
"period": 3,
"periodTableBlock": "p",
"rB0": 0.997,
"radiusCovalent": 0.99,
"radiusVDW": 1.8,
"symbol": "Cl",
"valences": [1]
}, {
"atomicNumber": 18,
"boilingpoint": 87.45,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "uk",
"discoveryDate": "1894",
"electronAffinity": 0.0,
"electronicConfiguration": "Ne 3s2 3p6",
"elementColor": [0.5, 0.82, 0.89],
"exactMass": 39.96238312,
"family": "Noblegas",
"group": 8,
"ionization": 15.7596,
"mass": 39.948,
"meltingpoint": 83.95,
"mostCommonIsotope": "Ar40",
"mostCommonIsotopeMass": 39.96238312,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'aergon' for 'inactive'",
"outshellElectrons": 8,
"period": 3,
"periodTableBlock": "p",
"rB0": 1.74,
"radiusCovalent": 0.97,
"radiusVDW": 1.88,
"symbol": "Ar",
"valences": [0]
}, {
"atomicNumber": 19,
"boilingpoint": 1033.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1807",
"electronAffinity": 0.501459,
"electronegativityPauling": 0.82,
"electronicConfiguration": "Ar 4s1",
"elementColor": [0.56, 0.25, 0.83],
"exactMass": 38.96370668,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.3407,
"mass": 39.0983,
"meltingpoint": 336.8,
"mostCommonIsotope": "K39",
"mostCommonIsotopeMass": 38.96370668,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Arabic 'al qaliy' for potash",
"outshellElectrons": 1,
"period": 4,
"periodTableBlock": "s",
"rB0": 2.03,
"radiusCovalent": 1.96,
"radiusVDW": 2.8,
"symbol": "K",
"valences": [1]
}, {
"atomicNumber": 20,
"boilingpoint": 1757.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.02455,
"electronegativityPauling": 1.0,
"electronicConfiguration": "Ar 4s2",
"elementColor": [0.24, 1.0, 0.0],
"exactMass": 39.96259098,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 6.1132,
"mass": 40.078,
"meltingpoint": 1112.0,
"mostCommonIsotope": "Ca40",
"mostCommonIsotopeMass": 39.96259098,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'calx' for 'lime'",
"outshellElectrons": 2,
"period": 4,
"periodTableBlock": "s",
"rB0": 1.74,
"radiusCovalent": 1.74,
"radiusVDW": 2.4,
"symbol": "Ca",
"valences": [2]
}, {
"atomicNumber": 21,
"boilingpoint": 3109.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1879",
"electronAffinity": 0.188,
"electronegativityPauling": 1.36,
"electronicConfiguration": "Ar 3d1 4s2",
"elementColor": [0.9, 0.9, 0.9],
"exactMass": 44.9559119,
"family": "Transition",
"group": 3,
"ionization": 6.5615,
"mass": 44.955912,
"meltingpoint": 1814.0,
"mostCommonIsotope": "Sc45",
"mostCommonIsotopeMass": 44.9559119,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named because it was found in Scandinavia",
"outshellElectrons": 3,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.44,
"radiusCovalent": 1.44,
"radiusVDW": 2.3,
"symbol": "Sc",
"valences": []
}, {
"atomicNumber": 22,
"boilingpoint": 3560.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1791",
"electronAffinity": 0.084,
"electronegativityPauling": 1.54,
"electronicConfiguration": "Ar 3d2 4s2",
"elementColor": [0.75, 0.76, 0.78],
"exactMass": 47.9479463,
"family": "Transition",
"group": 4,
"ionization": 6.8281,
"mass": 47.867,
"meltingpoint": 1935.0,
"mostCommonIsotope": "Ti48",
"mostCommonIsotopeMass": 47.9479463,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "The Titans were giants in Greek mythology",
"outshellElectrons": 4,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.32,
"radiusCovalent": 1.36,
"radiusVDW": 2.15,
"symbol": "Ti",
"valences": []
}, {
"atomicNumber": 23,
"boilingpoint": 3650.0,
"discoverers": "PI:NAME:<NAME>END_PI\u00f6PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1830",
"electronAffinity": 0.525,
"electronegativityPauling": 1.63,
"electronicConfiguration": "Ar 3d3 4s2",
"elementColor": [0.65, 0.65, 0.67],
"exactMass": 50.9439595,
"family": "Transition",
"group": 5,
"ionization": 6.7462,
"mass": 50.9415,
"meltingpoint": 2163.0,
"mostCommonIsotope": "V50",
"mostCommonIsotopeMass": 49.9471585,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "'PI:NAME:<NAME>END_PI' is another name for the PI:NAME:<NAME>END_PIordic goddess PI:NAME:<NAME>END_PI",
"outshellElectrons": 5,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.22,
"radiusCovalent": 1.25,
"radiusVDW": 2.05,
"symbol": "V",
"valences": []
}, {
"atomicNumber": 24,
"boilingpoint": 2945.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1797",
"electronAffinity": 0.67584,
"electronegativityPauling": 1.66,
"electronicConfiguration": "Ar 3d5 4s1",
"elementColor": [0.54, 0.6, 0.78],
"exactMass": 51.9405075,
"family": "Transition",
"group": 6,
"ionization": 6.7665,
"mass": 51.9961,
"meltingpoint": 2130.0,
"mostCommonIsotope": "Cr52",
"mostCommonIsotopeMass": 51.9405075,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'chroma' means 'color'",
"outshellElectrons": 6,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.18,
"radiusCovalent": 1.27,
"radiusVDW": 2.05,
"symbol": "Cr",
"valences": []
}, {
"atomicNumber": 25,
"boilingpoint": 2235.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1774",
"electronAffinity": 0.0,
"electronegativityPauling": 1.55,
"electronicConfiguration": "Ar 3d5 4s2",
"elementColor": [0.61, 0.48, 0.78],
"exactMass": 54.9380451,
"family": "Transition",
"group": 7,
"ionization": 7.434,
"mass": 54.938045,
"meltingpoint": 1518.0,
"mostCommonIsotope": "Mn55",
"mostCommonIsotopeMass": 54.9380451,
"name": "PI:NAME:<NAME>END_PIangPI:NAME:<NAME>END_PI",
"nameOrigin": "It was discovered near a town named Magnesia in black earth. Thus, it was named 'PI:NAME:<NAME>END_PIia PI:NAME:<NAME>END_PI', or for short, Manganese.",
"outshellElectrons": 7,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.39,
"radiusVDW": 2.05,
"symbol": "Mn",
"valences": []
}, {
"atomicNumber": 26,
"boilingpoint": 3023.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.151,
"electronegativityPauling": 1.83,
"electronicConfiguration": "Ar 3d6 4s2",
"elementColor": [0.5, 0.48, 0.78],
"exactMass": 55.9349375,
"family": "Transition",
"group": 8,
"ionization": 7.9024,
"mass": 55.845,
"meltingpoint": 1808.0,
"mostCommonIsotope": "Fe56",
"mostCommonIsotopeMass": 55.9349375,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'ferrum'",
"outshellElectrons": 8,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.25,
"radiusVDW": 2.05,
"symbol": "Fe",
"valences": []
}, {
"atomicNumber": 27,
"boilingpoint": 3143.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1737",
"electronAffinity": 0.6633,
"electronegativityPauling": 1.88,
"electronicConfiguration": "Ar 3d7 4s2",
"elementColor": [0.44, 0.48, 0.78],
"exactMass": 58.933195,
"family": "Transition",
"group": 8,
"ionization": 7.881,
"mass": 58.933195,
"meltingpoint": 1768.0,
"mostCommonIsotope": "Co59",
"mostCommonIsotopeMass": 58.933195,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the German word 'PI:NAME:<NAME>END_PI' for 'goblin'",
"outshellElectrons": 9,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.16,
"radiusCovalent": 1.26,
"radiusVDW": 2.0,
"symbol": "Co",
"valences": []
}, {
"atomicNumber": 28,
"boilingpoint": 3005.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1751",
"electronAffinity": 1.15716,
"electronegativityPauling": 1.91,
"electronicConfiguration": "Ar 3d8 4s2",
"elementColor": [0.36, 0.48, 0.76],
"exactMass": 57.9353429,
"family": "Transition",
"group": 8,
"ionization": 7.6398,
"mass": 58.6934,
"meltingpoint": 1726.0,
"mostCommonIsotope": "Ni58",
"mostCommonIsotopeMass": 57.9353429,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "'PI:NAME:<NAME>END_PI' was the name of a mountain goblin",
"outshellElectrons": 10,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.15,
"radiusCovalent": 1.21,
"radiusVDW": 2.0,
"symbol": "Ni",
"valences": []
}, {
"atomicNumber": 29,
"boilingpoint": 2840.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.23578,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Ar 3d10 4s1",
"elementColor": [1.0, 0.48, 0.38],
"exactMass": 62.9295975,
"family": "Transition",
"group": 1,
"ionization": 7.7264,
"mass": 63.546,
"meltingpoint": 1356.6,
"mostCommonIsotope": "Cu63",
"mostCommonIsotopeMass": 62.9295975,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'cuprum' for Cypres",
"outshellElectrons": 11,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.17,
"radiusCovalent": 1.38,
"radiusVDW": 2.0,
"symbol": "Cu",
"valences": []
}, {
"atomicNumber": 30,
"boilingpoint": 1180.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1746",
"electronAffinity": 0.0,
"electronegativityPauling": 1.65,
"electronicConfiguration": "Ar 3d10 4s2",
"elementColor": [0.49, 0.5, 0.69],
"exactMass": 63.9291422,
"family": "Transition",
"group": 2,
"ionization": 9.3942,
"mass": 65.38,
"meltingpoint": 692.73,
"mostCommonIsotope": "Zn64",
"mostCommonIsotopeMass": 63.9291422,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "German 'zinking' for 'rough', because zinc ore is very rough",
"outshellElectrons": 2,
"period": 4,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.31,
"radiusVDW": 2.1,
"symbol": "Zn",
"valences": []
}, {
"atomicNumber": 31,
"boilingpoint": 2478.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1875",
"electronAffinity": 0.41,
"electronegativityPauling": 1.81,
"electronicConfiguration": "Ar 3d10 4s2 4p1",
"elementColor": [0.76, 0.56, 0.56],
"exactMass": 68.9255736,
"family": "Other_Metal",
"group": 3,
"ionization": 5.9993,
"mass": 69.723,
"meltingpoint": 302.92,
"mostCommonIsotope": "Ga69",
"mostCommonIsotopeMass": 68.9255736,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "'PI:NAME:<NAME>END_PI' is an old name for France",
"outshellElectrons": 3,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.26,
"radiusCovalent": 1.26,
"radiusVDW": 2.1,
"symbol": "Ga",
"valences": [3]
}, {
"atomicNumber": 32,
"boilingpoint": 3107.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1886",
"electronAffinity": 1.232712,
"electronegativityPauling": 2.01,
"electronicConfiguration": "Ar 3d10 4s2 4p2",
"elementColor": [0.4, 0.56, 0.56],
"exactMass": 73.9211778,
"family": "Metalloids",
"group": 4,
"ionization": 7.8994,
"mass": 72.64,
"meltingpoint": 1211.5,
"mostCommonIsotope": "Ge74",
"mostCommonIsotopeMass": 73.9211778,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'germania' is an old name for Germany",
"outshellElectrons": 4,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.188,
"radiusCovalent": 1.22,
"radiusVDW": 2.1,
"symbol": "Ge",
"valences": [4]
}, {
"atomicNumber": 33,
"boilingpoint": 876.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.814,
"electronegativityPauling": 2.18,
"electronicConfiguration": "Ar 3d10 4s2 4p3",
"elementColor": [0.74, 0.5, 0.89],
"exactMass": 74.9215965,
"family": "Metalloids",
"group": 5,
"ionization": 9.7886,
"mass": 74.9216,
"meltingpoint": 1090.0,
"mostCommonIsotope": "As75",
"mostCommonIsotopeMass": 74.9215965,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'arsenikos' for 'male' or 'bold'",
"outshellElectrons": 5,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.2,
"radiusCovalent": 1.19,
"radiusVDW": 2.05,
"symbol": "As",
"valences": [3, 5]
}, {
"atomicNumber": 34,
"boilingpoint": 958.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1817",
"electronAffinity": 2.02067,
"electronegativityPauling": 2.55,
"electronicConfiguration": "Ar 3d10 4s2 4p4",
"elementColor": [1.0, 0.63, 0.0],
"exactMass": 79.9165213,
"family": "Non-Metal",
"group": 6,
"ionization": 9.7524,
"mass": 78.96,
"meltingpoint": 494.0,
"mostCommonIsotope": "Se80",
"mostCommonIsotopeMass": 79.9165213,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'selena' for 'moon'",
"outshellElectrons": 6,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.17,
"radiusCovalent": 1.16,
"radiusVDW": 1.9,
"symbol": "Se",
"valences": [2, 4, 6]
}, {
"atomicNumber": 35,
"boilingpoint": 331.85,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1826",
"electronAffinity": 3.363588,
"electronegativityPauling": 2.96,
"electronicConfiguration": "Ar 3d10 4s2 4p5",
"elementColor": [0.65, 0.16, 0.16],
"exactMass": 78.9183371,
"family": "Halogen",
"group": 7,
"ionization": 11.8138,
"mass": 79.904,
"meltingpoint": 265.95,
"mostCommonIsotope": "Br79",
"mostCommonIsotopeMass": 78.9183371,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'bromos' for 'smells badly'",
"outshellElectrons": 7,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.167,
"radiusCovalent": 1.14,
"radiusVDW": 1.9,
"symbol": "Br",
"valences": [1]
}, {
"atomicNumber": 36,
"boilingpoint": 120.85,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronegativityPauling": 3.0,
"electronicConfiguration": "Ar 3d10 4s2 4p6",
"elementColor": [0.36, 0.72, 0.82],
"exactMass": 83.911507,
"family": "Noblegas",
"group": 8,
"ionization": 13.9996,
"mass": 83.798,
"meltingpoint": 116.0,
"mostCommonIsotope": "Kr84",
"mostCommonIsotopeMass": 83.911507,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'kryptos' for 'hidden'",
"outshellElectrons": 8,
"period": 4,
"periodTableBlock": "p",
"rB0": 1.91,
"radiusCovalent": 1.1,
"radiusVDW": 2.02,
"symbol": "Kr",
"valences": [0]
}, {
"atomicNumber": 37,
"boilingpoint": 961.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "de",
"discoveryDate": "1861",
"electronAffinity": 0.485916,
"electronegativityPauling": 0.82,
"electronicConfiguration": "Kr 5s1",
"elementColor": [0.44, 0.18, 0.69],
"exactMass": 84.91178974,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.1771,
"mass": 85.4678,
"meltingpoint": 312.63,
"mostCommonIsotope": "Rb85",
"mostCommonIsotopeMass": 84.91178974,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'rubidus' for 'dark red'",
"outshellElectrons": 1,
"period": 5,
"periodTableBlock": "s",
"rB0": 2.16,
"radiusCovalent": 2.11,
"radiusVDW": 2.9,
"symbol": "Rb",
"valences": [1]
}, {
"atomicNumber": 38,
"boilingpoint": 1655.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1790",
"electronAffinity": 0.05206,
"electronegativityPauling": 0.95,
"electronicConfiguration": "Kr 5s2",
"elementColor": [0.0, 1.0, 0.0],
"exactMass": 87.9056121,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.6949,
"mass": 87.62,
"meltingpoint": 1042.0,
"mostCommonIsotope": "Sr88",
"mostCommonIsotopeMass": 87.9056121,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the mineral Strontianit",
"outshellElectrons": 2,
"period": 5,
"periodTableBlock": "s",
"rB0": 1.91,
"radiusCovalent": 1.92,
"radiusVDW": 2.55,
"symbol": "Sr",
"valences": [2]
}, {
"atomicNumber": 39,
"boilingpoint": 3611.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fi",
"discoveryDate": "1794",
"electronAffinity": 0.307,
"electronegativityPauling": 1.22,
"electronicConfiguration": "Kr 4d1 5s2",
"elementColor": [0.58, 1.0, 1.0],
"exactMass": 88.9058483,
"family": "Transition",
"group": 3,
"ionization": 6.2173,
"mass": 88.90585,
"meltingpoint": 1795.0,
"mostCommonIsotope": "Y89",
"mostCommonIsotopeMass": 88.9058483,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the small town of Ytterby near Stockholm in Sweden. Terbium. Ytterbium and Gadolinium are also named after this town.",
"outshellElectrons": 3,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.62,
"radiusCovalent": 1.62,
"radiusVDW": 2.4,
"symbol": "Y",
"valences": []
}, {
"atomicNumber": 40,
"boilingpoint": 4682.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1789",
"electronAffinity": 0.426,
"electronegativityPauling": 1.33,
"electronicConfiguration": "Kr 4d2 5s2",
"elementColor": [0.58, 0.88, 0.88],
"exactMass": 89.9047044,
"family": "Transition",
"group": 4,
"ionization": 6.6339,
"mass": 91.224,
"meltingpoint": 2128.0,
"mostCommonIsotope": "Zr90",
"mostCommonIsotopeMass": 89.9047044,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the mineral zircon",
"outshellElectrons": 4,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.45,
"radiusCovalent": 1.48,
"radiusVDW": 2.3,
"symbol": "Zr",
"valences": []
}, {
"atomicNumber": 41,
"boilingpoint": 5015.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1801",
"electronAffinity": 0.893,
"electronegativityPauling": 1.6,
"electronicConfiguration": "Kr 4d4",
"elementColor": [0.45, 0.76, 0.79],
"exactMass": 92.9063781,
"family": "Transition",
"group": 5,
"ionization": 6.7589,
"mass": 92.90638,
"meltingpoint": 2742.0,
"mostCommonIsotope": "Nb93",
"mostCommonIsotopeMass": 92.9063781,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after PI:NAME:<NAME>END_PI, the daughter of the Greek god PI:NAME:<NAME>END_PI.",
"outshellElectrons": 5,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.37,
"radiusVDW": 2.15,
"symbol": "Nb",
"valences": []
}, {
"atomicNumber": 42,
"boilingpoint": 4912.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1778",
"electronAffinity": 0.7472,
"electronegativityPauling": 2.16,
"electronicConfiguration": "Kr 4d5 5s1",
"elementColor": [0.33, 0.71, 0.71],
"exactMass": 97.9054082,
"family": "Transition",
"group": 6,
"ionization": 7.0924,
"mass": 95.96,
"meltingpoint": 2896.0,
"mostCommonIsotope": "Mo98",
"mostCommonIsotopeMass": 97.9054082,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "This name has Greek roots. It means 'like Platinum' - it was difficult to distinguish Molybdenum from Platinum.",
"outshellElectrons": 6,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.45,
"radiusVDW": 2.1,
"symbol": "Mo",
"valences": []
}, {
"atomicNumber": 43,
"boilingpoint": 4538.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "it",
"discoveryDate": "1937",
"electronAffinity": 0.55,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Kr 4d6 5s1",
"elementColor": [0.23, 0.62, 0.62],
"exactMass": 97.907216,
"family": "Transition",
"group": 7,
"ionization": 7.28,
"mass": 98.0,
"meltingpoint": 2477.0,
"mostCommonIsotope": "Tc97",
"mostCommonIsotopeMass": 96.906365,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'technetos' for artificial",
"outshellElectrons": 7,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.27,
"radiusCovalent": 1.56,
"radiusVDW": 2.05,
"symbol": "Tc",
"valences": []
}, {
"atomicNumber": 44,
"boilingpoint": 4425.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "ru",
"discoveryDate": "1844",
"electronAffinity": 1.04638,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Kr 4d7 5s1",
"elementColor": [0.14, 0.56, 0.56],
"exactMass": 101.9043493,
"family": "Transition",
"group": 8,
"ionization": 7.3605,
"mass": 101.07,
"meltingpoint": 2610.0,
"mostCommonIsotope": "Ru102",
"mostCommonIsotopeMass": 101.9043493,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "PI:NAME:<NAME>END_PI is the old name of PI:NAME:<NAME>END_PIussia",
"outshellElectrons": 8,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.26,
"radiusVDW": 2.05,
"symbol": "Ru",
"valences": []
}, {
"atomicNumber": 45,
"boilingpoint": 3970.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1803",
"electronAffinity": 1.14289,
"electronegativityPauling": 2.28,
"electronicConfiguration": "Kr 4d8 5s1",
"elementColor": [0.04, 0.49, 0.55],
"exactMass": 102.905504,
"family": "Transition",
"group": 8,
"ionization": 7.4589,
"mass": 102.9055,
"meltingpoint": 2236.0,
"mostCommonIsotope": "Rh103",
"mostCommonIsotopeMass": 102.905504,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'rhodeos' means 'red like a rose'",
"outshellElectrons": 9,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.25,
"radiusCovalent": 1.35,
"radiusVDW": 2.0,
"symbol": "Rh",
"valences": []
}, {
"atomicNumber": 46,
"boilingpoint": 3240.0,
"discoveryCountry": "uk",
"discoveryDate": "1803",
"electronAffinity": 0.56214,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Kr 4d10",
"elementColor": [0.0, 0.41, 0.52],
"exactMass": 105.903486,
"family": "Transition",
"group": 8,
"ionization": 8.3369,
"mass": 106.42,
"meltingpoint": 1825.0,
"mostCommonIsotope": "Pd106",
"mostCommonIsotopeMass": 105.903486,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the asteroid Pallas",
"outshellElectrons": 10,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.28,
"radiusCovalent": 1.31,
"radiusVDW": 2.05,
"symbol": "Pd",
"valences": []
}, {
"atomicNumber": 47,
"boilingpoint": 2436.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.30447,
"electronegativityPauling": 1.93,
"electronicConfiguration": "Kr 4d10 5s1",
"elementColor": [0.88, 0.88, 1.0],
"exactMass": 106.905097,
"family": "Transition",
"group": 1,
"ionization": 7.5762,
"mass": 107.8682,
"meltingpoint": 1235.1,
"mostCommonIsotope": "Ag107",
"mostCommonIsotopeMass": 106.905097,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'argentum' for silver",
"outshellElectrons": 11,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.53,
"radiusVDW": 2.1,
"symbol": "Ag",
"valences": []
}, {
"atomicNumber": 48,
"boilingpoint": 1040.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1817",
"electronAffinity": 0.0,
"electronegativityPauling": 1.69,
"electronicConfiguration": "Kr 4d10 5s2",
"elementColor": [1.0, 0.85, 0.56],
"exactMass": 113.9033585,
"family": "Transition",
"group": 2,
"ionization": 8.9938,
"mass": 112.411,
"meltingpoint": 594.26,
"mostCommonIsotope": "Cd114",
"mostCommonIsotopeMass": 113.9033585,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'kadmia' ('Galmei' = Zinc carbonate)",
"outshellElectrons": 2,
"period": 5,
"periodTableBlock": "d",
"rB0": 1.48,
"radiusCovalent": 1.48,
"radiusVDW": 2.2,
"symbol": "Cd",
"valences": []
}, {
"atomicNumber": 49,
"boilingpoint": 2350.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "de",
"discoveryDate": "1863",
"electronAffinity": 0.404,
"electronegativityPauling": 1.78,
"electronicConfiguration": "Kr 4d10 5s2 5p1",
"elementColor": [0.65, 0.46, 0.45],
"exactMass": 114.903878,
"family": "Other_Metal",
"group": 3,
"ionization": 5.7864,
"mass": 114.818,
"meltingpoint": 429.78,
"mostCommonIsotope": "In115",
"mostCommonIsotopeMass": 114.903878,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after 'PI:NAME:<NAME>END_PI' because of its blue spectrum",
"outshellElectrons": 3,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.44,
"radiusCovalent": 1.44,
"radiusVDW": 2.2,
"symbol": "In",
"valences": [3]
}, {
"atomicNumber": 50,
"boilingpoint": 2876.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.112066,
"electronegativityPauling": 1.96,
"electronicConfiguration": "Kr 4d10 5s2 5p2",
"elementColor": [0.4, 0.5, 0.5],
"exactMass": 119.9021947,
"family": "Other_Metal",
"group": 4,
"ionization": 7.3439,
"mass": 118.71,
"meltingpoint": 505.12,
"mostCommonIsotope": "Sn120",
"mostCommonIsotopeMass": 119.9021947,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'PI:NAME:<NAME>END_PIannum' for tin",
"outshellElectrons": 4,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.385,
"radiusCovalent": 1.41,
"radiusVDW": 2.25,
"symbol": "Sn",
"valences": [4]
}, {
"atomicNumber": 51,
"boilingpoint": 1860.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 1.047401,
"electronegativityPauling": 2.05,
"electronicConfiguration": "Kr 4d10 5s2 5p3",
"elementColor": [0.62, 0.39, 0.71],
"exactMass": 120.9038157,
"family": "Metalloids",
"group": 5,
"ionization": 8.6084,
"mass": 121.76,
"meltingpoint": 903.91,
"mostCommonIsotope": "Sb121",
"mostCommonIsotopeMass": 120.9038157,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Arabic 'anthos ammonos' for 'blossom of the god Ammon'",
"outshellElectrons": 5,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.4,
"radiusCovalent": 1.38,
"radiusVDW": 2.2,
"symbol": "Sb",
"valences": [3, 5]
}, {
"atomicNumber": 52,
"boilingpoint": 1261.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1782",
"electronAffinity": 1.970875,
"electronegativityPauling": 2.1,
"electronicConfiguration": "Kr 4d10 5s2 5p4",
"elementColor": [0.83, 0.48, 0.0],
"exactMass": 129.9062244,
"family": "Metalloids",
"group": 6,
"ionization": 9.0096,
"mass": 127.6,
"meltingpoint": 722.72,
"mostCommonIsotope": "Te130",
"mostCommonIsotopeMass": 129.9062244,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'tellus' or 'telluris' for 'Planet Earth'",
"outshellElectrons": 6,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.378,
"radiusCovalent": 1.35,
"radiusVDW": 2.1,
"symbol": "Te",
"valences": [2]
}, {
"atomicNumber": 53,
"boilingpoint": 457.5,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1811",
"electronAffinity": 3.059038,
"electronegativityPauling": 2.66,
"electronicConfiguration": "Kr 4d10 5s2 5p5",
"elementColor": [0.58, 0.0, 0.58],
"exactMass": 126.904473,
"family": "Halogen",
"group": 7,
"ionization": 10.4513,
"mass": 126.90447,
"meltingpoint": 386.7,
"mostCommonIsotope": "I127",
"mostCommonIsotopeMass": 126.904473,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'ioeides' for 'violet'.",
"outshellElectrons": 7,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.387,
"radiusCovalent": 1.33,
"radiusVDW": 2.1,
"symbol": "I",
"valences": [1, 2, 5]
}, {
"atomicNumber": 54,
"boilingpoint": 165.1,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "uk",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronegativityPauling": 2.6,
"electronicConfiguration": "Kr 4d10 5s2 5p6",
"elementColor": [0.26, 0.62, 0.69],
"exactMass": 131.9041535,
"family": "Noblegas",
"group": 8,
"ionization": 12.1298,
"mass": 131.293,
"meltingpoint": 161.39,
"mostCommonIsotope": "Xe132",
"mostCommonIsotopeMass": 131.9041535,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'xenos' for 'foreigner'",
"outshellElectrons": 8,
"period": 5,
"periodTableBlock": "p",
"rB0": 1.98,
"radiusCovalent": 1.3,
"radiusVDW": 2.16,
"symbol": "Xe",
"valences": [0, 2]
}, {
"atomicNumber": 55,
"boilingpoint": 944.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "de",
"discoveryDate": "1860",
"electronAffinity": 0.471626,
"electronegativityPauling": 0.79,
"electronicConfiguration": "Xe 6s1",
"elementColor": [0.34, 0.09, 0.56],
"exactMass": 132.9054519,
"family": "Alkali_Earth",
"group": 1,
"ionization": 3.8939,
"mass": 132.9054519,
"meltingpoint": 301.54,
"mostCommonIsotope": "Cs133",
"mostCommonIsotopeMass": 132.9054519,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'caesius' for 'heaven blue'.",
"outshellElectrons": 1,
"period": 6,
"periodTableBlock": "s",
"rB0": 2.35,
"radiusCovalent": 2.25,
"radiusVDW": 3.0,
"symbol": "Cs",
"valences": [1]
}, {
"atomicNumber": 56,
"boilingpoint": 2078.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1808",
"electronAffinity": 0.14462,
"electronegativityPauling": 0.89,
"electronicConfiguration": "Xe 6s2",
"elementColor": [0.0, 0.79, 0.0],
"exactMass": 137.9052472,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.2117,
"mass": 137.327,
"meltingpoint": 1002.0,
"mostCommonIsotope": "Ba138",
"mostCommonIsotopeMass": 137.9052472,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'barys' for 'heavy'",
"outshellElectrons": 2,
"period": 6,
"periodTableBlock": "s",
"rB0": 1.98,
"radiusCovalent": 1.98,
"radiusVDW": 2.7,
"symbol": "Ba",
"valences": [2]
}, {
"atomicNumber": 57,
"boilingpoint": 3737.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1839",
"electronAffinity": 0.47,
"electronegativityPauling": 1.1,
"electronicConfiguration": "Xe 5d1 6s2",
"elementColor": [0.44, 0.83, 1.0],
"exactMass": 138.9063533,
"family": "Rare_Earth",
"group": 3,
"ionization": 5.5769,
"mass": 138.90547,
"meltingpoint": 1191.0,
"mostCommonIsotope": "La139",
"mostCommonIsotopeMass": 138.9063533,
"name": "PI:NAME:<NAME>END_PIthanum",
"nameOrigin": "Greek 'lanthanein' for 'hidden'. The Lanthanoids are also called the 'rare earth' elements.",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.69,
"radiusCovalent": 1.69,
"radiusVDW": 2.5,
"symbol": "La",
"valences": []
}, {
"atomicNumber": 58,
"boilingpoint": 3715.0,
"discoverers": ["PI:NAME:<NAME>END_PI\u00f6PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1803",
"electronAffinity": 0.5,
"electronegativityPauling": 1.12,
"electronicConfiguration": "Xe 4f1 5d1 6s2",
"elementColor": [1.0, 1.0, 0.78],
"exactMass": 139.9054387,
"family": "Rare_Earth",
"group": 4,
"ionization": 5.5387,
"mass": 140.116,
"meltingpoint": 1071.0,
"mostCommonIsotope": "Ce140",
"mostCommonIsotopeMass": 139.9054387,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the planetoid Ceres",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.83,
"radiusVDW": 2.48,
"symbol": "Ce",
"valences": []
}, {
"atomicNumber": 59,
"boilingpoint": 3785.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1885",
"electronAffinity": 0.5,
"electronegativityPauling": 1.13,
"electronicConfiguration": "Xe 4f3 6s2",
"elementColor": [0.85, 1.0, 0.78],
"exactMass": 140.9076528,
"family": "Rare_Earth",
"group": 5,
"ionization": 5.473,
"mass": 140.90765,
"meltingpoint": 1204.0,
"mostCommonIsotope": "Pr141",
"mostCommonIsotopeMass": 140.9076528,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'prasinos didymos' for 'green twin'",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.82,
"radiusVDW": 2.47,
"symbol": "Pr",
"valences": []
}, {
"atomicNumber": 60,
"boilingpoint": 3347.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1885",
"electronAffinity": 0.5,
"electronegativityPauling": 1.14,
"electronicConfiguration": "Xe 4f4 6s2",
"elementColor": [0.78, 1.0, 0.78],
"exactMass": 141.9077233,
"family": "Rare_Earth",
"group": 6,
"ionization": 5.525,
"mass": 144.242,
"meltingpoint": 1294.0,
"mostCommonIsotope": "Nd142",
"mostCommonIsotopeMass": 141.9077233,
"name": "PI:NAME:<NAME>END_PIodymium",
"nameOrigin": "Greek 'neos didymos' for 'new twin'",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.81,
"radiusVDW": 2.45,
"symbol": "Nd",
"valences": []
}, {
"atomicNumber": 61,
"boilingpoint": 3273.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1945",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f5 6s2",
"elementColor": [0.64, 1.0, 0.78],
"exactMass": 144.912749,
"family": "Rare_Earth",
"group": 7,
"ionization": 5.582,
"mass": 145.0,
"meltingpoint": 1315.0,
"mostCommonIsotope": "Pm145",
"mostCommonIsotopeMass": 144.912749,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the Greek Prometheus. Prometheus stole the fire from the gods and gave it to mankind.",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.8,
"radiusVDW": 2.43,
"symbol": "Pm",
"valences": []
}, {
"atomicNumber": 62,
"boilingpoint": 2067.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1879",
"electronAffinity": 0.5,
"electronegativityPauling": 1.17,
"electronicConfiguration": "Xe 4f6 6s2",
"elementColor": [0.56, 1.0, 0.78],
"exactMass": 151.9197324,
"family": "Rare_Earth",
"group": 8,
"ionization": 5.6437,
"mass": 150.36,
"meltingpoint": 1347.0,
"mostCommonIsotope": "Sm152",
"mostCommonIsotopeMass": 151.9197324,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the mineral PI:NAME:<NAME>END_PI",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.8,
"radiusVDW": 2.42,
"symbol": "Sm",
"valences": []
}, {
"atomicNumber": 63,
"boilingpoint": 1800.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1901",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f7 6s2",
"elementColor": [0.38, 1.0, 0.78],
"exactMass": 152.9212303,
"family": "Rare_Earth",
"group": 8,
"ionization": 5.6704,
"mass": 151.964,
"meltingpoint": 1095.0,
"mostCommonIsotope": "Eu153",
"mostCommonIsotopeMass": 152.9212303,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after Europe",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.99,
"radiusVDW": 2.4,
"symbol": "Eu",
"valences": []
}, {
"atomicNumber": 64,
"boilingpoint": 3545.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1880",
"electronAffinity": 0.5,
"electronegativityPauling": 1.2,
"electronicConfiguration": "Xe 4f7 5d1 6s2",
"elementColor": [0.27, 1.0, 0.78],
"exactMass": 157.9241039,
"family": "Rare_Earth",
"group": 8,
"ionization": 6.1498,
"mass": 157.25,
"meltingpoint": 1585.0,
"mostCommonIsotope": "Gd158",
"mostCommonIsotopeMass": 157.9241039,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the Finnish chemist PI:NAME:<NAME>END_PI",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.79,
"radiusVDW": 2.38,
"symbol": "Gd",
"valences": []
}, {
"atomicNumber": 65,
"boilingpoint": 3500.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1843",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f9 6s2",
"elementColor": [0.19, 1.0, 0.78],
"exactMass": 158.9253468,
"family": "Rare_Earth",
"group": 1,
"ionization": 5.8638,
"mass": 158.92535,
"meltingpoint": 1629.0,
"mostCommonIsotope": "Tb159",
"mostCommonIsotopeMass": 158.9253468,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the Swedish town of Ytterby",
"outshellElectrons": 9,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.76,
"radiusVDW": 2.37,
"symbol": "Tb",
"valences": []
}, {
"atomicNumber": 66,
"boilingpoint": 2840.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1886",
"electronAffinity": 0.5,
"electronegativityPauling": 1.22,
"electronicConfiguration": "Xe 4f10 6s2",
"elementColor": [0.12, 1.0, 0.78],
"exactMass": 163.9291748,
"family": "Rare_Earth",
"group": 2,
"ionization": 5.9389,
"mass": 162.5,
"meltingpoint": 1685.0,
"mostCommonIsotope": "Dy164",
"mostCommonIsotopeMass": 163.9291748,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'dysprositor' for 'difficult to reach'",
"outshellElectrons": 10,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.75,
"radiusVDW": 2.35,
"symbol": "Dy",
"valences": []
}, {
"atomicNumber": 67,
"boilingpoint": 2968.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1878",
"electronAffinity": 0.5,
"electronegativityPauling": 1.23,
"electronicConfiguration": "Xe 4f11 6s2",
"elementColor": [0.0, 1.0, 0.61],
"exactMass": 164.9303221,
"family": "Rare_Earth",
"group": 3,
"ionization": 6.0215,
"mass": 164.93032,
"meltingpoint": 1747.0,
"mostCommonIsotope": "Ho165",
"mostCommonIsotopeMass": 164.9303221,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'holmia' for the old name of Stockholm",
"outshellElectrons": 11,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.74,
"radiusVDW": 2.33,
"symbol": "Ho",
"valences": []
}, {
"atomicNumber": 68,
"boilingpoint": 3140.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1843",
"electronAffinity": 0.5,
"electronegativityPauling": 1.24,
"electronicConfiguration": "Xe 4f12 6s2",
"elementColor": [0.0, 0.9, 0.46],
"exactMass": 165.9302931,
"family": "Rare_Earth",
"group": 4,
"ionization": 6.1077,
"mass": 167.259,
"meltingpoint": 1802.0,
"mostCommonIsotope": "Er166",
"mostCommonIsotopeMass": 165.9302931,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named ofter the Swedish town of Ytterby. Terbium and Ytterbium are also named after this town.",
"outshellElectrons": 12,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.73,
"radiusVDW": 2.32,
"symbol": "Er",
"valences": []
}, {
"atomicNumber": 69,
"boilingpoint": 2223.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1879",
"electronAffinity": 0.5,
"electronegativityPauling": 1.25,
"electronicConfiguration": "Xe 4f13 6s2",
"elementColor": [0.0, 0.83, 0.32],
"exactMass": 168.9342133,
"family": "Rare_Earth",
"group": 5,
"ionization": 6.1843,
"mass": 168.93421,
"meltingpoint": 1818.0,
"mostCommonIsotope": "Tm169",
"mostCommonIsotopeMass": 168.9342133,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the old name of Scandinavia, 'PI:NAME:<NAME>END_PI'.",
"outshellElectrons": 13,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.72,
"radiusVDW": 2.3,
"symbol": "Tm",
"valences": []
}, {
"atomicNumber": 70,
"boilingpoint": 1469.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1878",
"electronAffinity": 0.5,
"electronicConfiguration": "Xe 4f14 6s2",
"elementColor": [0.0, 0.75, 0.22],
"exactMass": 173.9388621,
"family": "Rare_Earth",
"group": 6,
"ionization": 6.2542,
"mass": 173.054,
"meltingpoint": 1092.0,
"mostCommonIsotope": "Yb174",
"mostCommonIsotopeMass": 173.9388621,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Like PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PIium, this is named after the Swedish town of PI:NAME:<NAME>END_PIby.",
"outshellElectrons": 14,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.94,
"radiusVDW": 2.28,
"symbol": "Yb",
"valences": []
}, {
"atomicNumber": 71,
"boilingpoint": 3668.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1907",
"electronAffinity": 0.5,
"electronegativityPauling": 1.27,
"electronicConfiguration": "Xe 4f14 5d1 6s2",
"elementColor": [0.0, 0.67, 0.14],
"exactMass": 174.9407718,
"family": "Rare_Earth",
"group": 7,
"ionization": 5.4259,
"mass": 174.9668,
"meltingpoint": 1936.0,
"mostCommonIsotope": "Lu175",
"mostCommonIsotopeMass": 174.9407718,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the Roman name 'PI:NAME:<NAME>END_PI' for Paris",
"outshellElectrons": 15,
"period": 6,
"periodTableBlock": "f",
"rB0": 1.72,
"radiusCovalent": 1.6,
"radiusVDW": 2.27,
"symbol": "Lu",
"valences": []
}, {
"atomicNumber": 72,
"boilingpoint": 4875.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "dk",
"discoveryDate": "1923",
"electronAffinity": 0.0,
"electronegativityPauling": 1.3,
"electronicConfiguration": "Xe 4f14 5d2 6s2",
"elementColor": [0.3, 0.76, 1.0],
"exactMass": 179.94655,
"family": "Transition",
"group": 4,
"ionization": 6.8251,
"mass": 178.49,
"meltingpoint": 2504.0,
"mostCommonIsotope": "Hf180",
"mostCommonIsotopeMass": 179.94655,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "'PI:NAME:<NAME>END_PI' is the old name of KopenPI:NAME:<NAME>END_PI (Denmark)",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.44,
"radiusCovalent": 1.5,
"radiusVDW": 2.25,
"symbol": "Hf",
"valences": []
}, {
"atomicNumber": 73,
"boilingpoint": 5730.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "se",
"discoveryDate": "1802",
"electronAffinity": 0.322,
"electronegativityPauling": 1.5,
"electronicConfiguration": "Xe 4f14 5d3 6s2",
"elementColor": [0.3, 0.65, 1.0],
"exactMass": 180.9479958,
"family": "Transition",
"group": 5,
"ionization": 7.5496,
"mass": 180.94788,
"meltingpoint": 3293.0,
"mostCommonIsotope": "Ta181",
"mostCommonIsotopeMass": 180.9479958,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the Greek myth of PI:NAME:<NAME>END_PI",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.38,
"radiusVDW": 2.2,
"symbol": "PI:NAME:<NAME>END_PI",
"valences": []
}, {
"atomicNumber": 74,
"boilingpoint": 5825.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "es",
"discoveryDate": "1783",
"electronAffinity": 0.815,
"electronegativityPauling": 2.36,
"electronicConfiguration": "Xe 4f14 5d4 6s2",
"elementColor": [0.13, 0.58, 0.84],
"exactMass": 183.9509312,
"family": "Transition",
"group": 6,
"ionization": 7.864,
"mass": 183.84,
"meltingpoint": 3695.0,
"mostCommonIsotope": "W184",
"mostCommonIsotopeMass": 183.9509312,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "'tung sten' means 'heavy stone' in Swedish. The old name (and thus the symbol 'W') was PI:NAME:<NAME>END_PIolPI:NAME:<NAME>END_PI, named after a mineral.",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.46,
"radiusVDW": 2.1,
"symbol": "W",
"valences": []
}, {
"atomicNumber": 75,
"boilingpoint": 5870.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "de",
"discoveryDate": "1925",
"electronAffinity": 0.15,
"electronegativityPauling": 1.9,
"electronicConfiguration": "Xe 4f14 5d5 6s2",
"elementColor": [0.15, 0.49, 0.67],
"exactMass": 186.9557531,
"family": "Transition",
"group": 7,
"ionization": 7.8335,
"mass": 186.207,
"meltingpoint": 3455.0,
"mostCommonIsotope": "Re187",
"mostCommonIsotopeMass": 186.9557531,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the German river Rhine (latin 'Rhenium').",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.28,
"radiusCovalent": 1.59,
"radiusVDW": 2.05,
"symbol": "Re",
"valences": []
}, {
"atomicNumber": 76,
"boilingpoint": 5300.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1804",
"electronAffinity": 1.0778,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d6 6s2",
"elementColor": [0.15, 0.4, 0.59],
"exactMass": 191.9614807,
"family": "Transition",
"group": 8,
"ionization": 8.4382,
"mass": 190.23,
"meltingpoint": 3300.0,
"mostCommonIsotope": "Os192",
"mostCommonIsotopeMass": 191.9614807,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek for 'smell'. Its oxides smell strongly like radishes.",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.26,
"radiusCovalent": 1.28,
"radiusVDW": 2.0,
"symbol": "Os",
"valences": []
}, {
"atomicNumber": 77,
"boilingpoint": 4700.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1804",
"electronAffinity": 1.56436,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d7 6s2",
"elementColor": [0.09, 0.33, 0.53],
"exactMass": 192.9629264,
"family": "Transition",
"group": 8,
"ionization": 8.967,
"mass": 192.217,
"meltingpoint": 2720.0,
"mostCommonIsotope": "Ir193",
"mostCommonIsotopeMass": 192.9629264,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'iris' for 'rainbow'",
"outshellElectrons": 9,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.27,
"radiusCovalent": 1.37,
"radiusVDW": 2.0,
"symbol": "Ir",
"valences": []
}, {
"atomicNumber": 78,
"boilingpoint": 4100.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1735",
"electronAffinity": 2.1251,
"electronegativityPauling": 2.28,
"electronicConfiguration": "Xe 4f14 5d9 6s1",
"elementColor": [0.96, 0.93, 0.82],
"exactMass": 194.9647911,
"family": "Transition",
"group": 8,
"ionization": 8.9588,
"mass": 195.084,
"meltingpoint": 2042.1,
"mostCommonIsotope": "Pt195",
"mostCommonIsotopeMass": 194.9647911,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Spanish 'platina' means 'small silver'",
"outshellElectrons": 10,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.3,
"radiusCovalent": 1.28,
"radiusVDW": 2.05,
"symbol": "Pt",
"valences": []
}, {
"atomicNumber": 79,
"boilingpoint": 3130.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 2.30861,
"electronegativityPauling": 2.54,
"electronicConfiguration": "Xe 4f14 5d10 6s1",
"elementColor": [0.8, 0.82, 0.12],
"exactMass": 196.9665687,
"family": "Transition",
"group": 1,
"ionization": 9.2255,
"mass": 196.966569,
"meltingpoint": 1337.58,
"mostCommonIsotope": "Au197",
"mostCommonIsotopeMass": 196.9665687,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'aurum'. Named after PI:NAME:<NAME>END_PIurora, the goddess of sunrise",
"outshellElectrons": 11,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.34,
"radiusCovalent": 1.44,
"radiusVDW": 2.1,
"symbol": "Au",
"valences": []
}, {
"atomicNumber": 80,
"boilingpoint": 629.88,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.0,
"electronegativityPauling": 2.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2",
"elementColor": [0.71, 0.71, 0.76],
"exactMass": 201.970643,
"family": "Transition",
"group": 2,
"ionization": 10.4375,
"mass": 200.59,
"meltingpoint": 234.31,
"mostCommonIsotope": "Hg202",
"mostCommonIsotopeMass": 201.970643,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Graeco-Latin 'hydrargyrum' for 'liquid silver'",
"outshellElectrons": 2,
"period": 6,
"periodTableBlock": "d",
"rB0": 1.49,
"radiusCovalent": 1.49,
"radiusVDW": 2.05,
"symbol": "Hg",
"valences": []
}, {
"atomicNumber": 81,
"boilingpoint": 1746.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "uk",
"discoveryDate": "1861",
"electronAffinity": 0.377,
"electronegativityPauling": 1.62,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p1",
"elementColor": [0.65, 0.33, 0.3],
"exactMass": 204.9744275,
"family": "Other_Metal",
"group": 3,
"ionization": 6.1082,
"mass": 204.3833,
"meltingpoint": 577.0,
"mostCommonIsotope": "Tl205",
"mostCommonIsotopeMass": 204.9744275,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'tallos' for 'young twig'",
"outshellElectrons": 3,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.48,
"radiusCovalent": 1.48,
"radiusVDW": 2.2,
"symbol": "Tl",
"valences": [3]
}, {
"atomicNumber": 82,
"boilingpoint": 2023.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.364,
"electronegativityPauling": 2.33,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p2",
"elementColor": [0.34, 0.35, 0.38],
"exactMass": 207.9766521,
"family": "Other_Metal",
"group": 4,
"ionization": 7.4167,
"mass": 207.2,
"meltingpoint": 600.65,
"mostCommonIsotope": "Pb208",
"mostCommonIsotopeMass": 207.9766521,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'plumbum' for PI:NAME:<NAME>END_PI",
"outshellElectrons": 4,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.48,
"radiusCovalent": 1.47,
"radiusVDW": 2.3,
"symbol": "Pb",
"valences": [4]
}, {
"atomicNumber": 83,
"boilingpoint": 1837.0,
"discoveryCountry": "ancient",
"discoveryDate": "0",
"electronAffinity": 0.942363,
"electronegativityPauling": 2.02,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p3",
"elementColor": [0.62, 0.31, 0.71],
"exactMass": 208.9803987,
"family": "Other_Metal",
"group": 5,
"ionization": 7.2855,
"mass": 208.9804,
"meltingpoint": 544.59,
"mostCommonIsotope": "Bi209",
"mostCommonIsotopeMass": 208.9803987,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "The old name of PI:NAME:<NAME>END_PI is 'PI:NAME:<NAME>END_PI', which stood for 'white mass'.",
"outshellElectrons": 5,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.45,
"radiusCovalent": 1.46,
"radiusVDW": 2.3,
"symbol": "Bi",
"valences": [3]
}, {
"atomicNumber": 84,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "fr",
"discoveryDate": "1898",
"electronAffinity": 1.9,
"electronegativityPauling": 2.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p4",
"elementColor": [0.67, 0.36, 0.0],
"exactMass": 208.9824304,
"family": "Metalloids",
"group": 6,
"ionization": 8.414,
"mass": 209.0,
"meltingpoint": 527.0,
"mostCommonIsotope": "Po209",
"mostCommonIsotopeMass": 208.9824304,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after Poland to honor PI:NAME:<NAME>END_PI",
"outshellElectrons": 6,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.46,
"radiusVDW": 2.0,
"symbol": "Po",
"valences": [2]
}, {
"atomicNumber": 85,
"boilingpoint": 610.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "us",
"discoveryDate": "1940",
"electronAffinity": 2.8,
"electronegativityPauling": 2.2,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p5",
"elementColor": [0.46, 0.31, 0.27],
"exactMass": 209.987148,
"family": "Halogen",
"group": 7,
"ionization": 0.0,
"mass": 210.0,
"meltingpoint": 575.0,
"mostCommonIsotope": "At210",
"mostCommonIsotopeMass": 209.987148,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'astator' for 'changing'",
"outshellElectrons": 7,
"period": 6,
"periodTableBlock": "p",
"rB0": 1.45,
"radiusVDW": 2.0,
"symbol": "At",
"valences": [1]
}, {
"atomicNumber": 86,
"boilingpoint": 211.4,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "de",
"discoveryDate": "1898",
"electronAffinity": 0.0,
"electronicConfiguration": "Xe 4f14 5d10 6s2 6p6",
"elementColor": [0.26, 0.51, 0.59],
"exactMass": 222.0175777,
"family": "Noblegas",
"group": 8,
"ionization": 10.7485,
"mass": 222.0,
"meltingpoint": 202.0,
"mostCommonIsotope": "Rn211",
"mostCommonIsotopeMass": 210.990601,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after Radium. It ends with 'on' to make it clear that it is a noble gas.",
"outshellElectrons": 8,
"period": 6,
"periodTableBlock": "p",
"rB0": 2.4,
"radiusCovalent": 1.45,
"radiusVDW": 2.0,
"symbol": "Rn",
"valences": [0]
}, {
"atomicNumber": 87,
"boilingpoint": 950.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1939",
"electronegativityPauling": 0.7,
"electronicConfiguration": "Rn 7s1",
"elementColor": [0.26, 0.0, 0.4],
"exactMass": 223.0197359,
"family": "Alkali_Earth",
"group": 1,
"ionization": 4.0727,
"mass": 223.0,
"meltingpoint": 300.0,
"mostCommonIsotope": "Fr223",
"mostCommonIsotopeMass": 223.0197359,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after France to honor Marguerite Perey",
"outshellElectrons": 1,
"period": 7,
"periodTableBlock": "s",
"rB0": 2.0,
"radiusVDW": 2.0,
"symbol": "Fr",
"valences": [1]
}, {
"atomicNumber": 88,
"boilingpoint": 1413.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryCountry": "fr",
"discoveryDate": "1898",
"electronegativityPauling": 0.9,
"electronicConfiguration": "Rn 7s2",
"elementColor": [0.0, 0.49, 0.0],
"exactMass": 226.0254098,
"family": "Alkaline_Earth",
"group": 2,
"ionization": 5.2784,
"mass": 226.0,
"meltingpoint": 973.0,
"mostCommonIsotope": "Ra223",
"mostCommonIsotopeMass": 223.0185022,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'radius' for 'beam', as it is radioactive",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "s",
"rB0": 1.9,
"radiusVDW": 2.0,
"symbol": "Ra",
"valences": [2]
}, {
"atomicNumber": 89,
"boilingpoint": 3470.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryCountry": "fr",
"discoveryDate": "1899",
"electronegativityPauling": 1.1,
"electronicConfiguration": "Rn 6d1 7s2",
"elementColor": [0.44, 0.67, 0.98],
"exactMass": 227.0277521,
"family": "Other_Metal",
"group": 3,
"ionization": 5.17,
"mass": 227.0,
"meltingpoint": 1324.0,
"mostCommonIsotope": "Ac227",
"mostCommonIsotopeMass": 227.0277521,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'aktis' for 'beam' - actinium is radioactive",
"outshellElectrons": 3,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.88,
"radiusVDW": 2.0,
"symbol": "Ac",
"valences": []
}, {
"atomicNumber": 90,
"boilingpoint": 5060.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1828",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 6d2 7s2",
"elementColor": [0.0, 0.73, 1.0],
"exactMass": 232.0380553,
"family": "Other_Metal",
"group": 4,
"ionization": 6.3067,
"mass": 232.03806,
"meltingpoint": 2028.0,
"mostCommonIsotope": "Th232",
"mostCommonIsotopeMass": 232.0380553,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the German god of thunder: PI:NAME:<NAME>END_PI",
"outshellElectrons": 4,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.79,
"radiusVDW": 2.4,
"symbol": "Th",
"valences": []
}, {
"atomicNumber": 91,
"boilingpoint": 4300.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1917",
"electronegativityPauling": 1.5,
"electronicConfiguration": "Rn 5f2 6d1 7s2",
"elementColor": [0.0, 0.63, 1.0],
"exactMass": 231.035884,
"family": "Other_Metal",
"group": 5,
"ionization": 5.89,
"mass": 231.03588,
"meltingpoint": 1845.0,
"mostCommonIsotope": "Pa231",
"mostCommonIsotopeMass": 231.035884,
"name": "Protactinium",
"nameOrigin": "Greek 'protos' for 'ancester'. Protactinium is before Actinium in the periodic table.",
"outshellElectrons": 3,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.61,
"radiusVDW": 2.0,
"symbol": "Pa",
"valences": []
}, {
"atomicNumber": 92,
"boilingpoint": 4407.0,
"discoverers": "PI:NAME:<NAME>END_PI",
"discoveryDate": "1789",
"electronegativityPauling": 1.38,
"electronicConfiguration": "Rn 5f3 6d1 7s2",
"elementColor": [0.0, 0.56, 1.0],
"exactMass": 238.0507882,
"family": "Other_Metal",
"group": 6,
"ionization": 6.1941,
"mass": 238.02891,
"meltingpoint": 1408.0,
"mostCommonIsotope": "U238",
"mostCommonIsotopeMass": 238.0507882,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Greek 'ouranos' for 'heaven'. Named after the planet Uranus.",
"outshellElectrons": 4,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.58,
"radiusVDW": 2.3,
"symbol": "U",
"valences": []
}, {
"atomicNumber": 93,
"boilingpoint": 4175.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1940",
"electronegativityPauling": 1.36,
"electronicConfiguration": "Rn 5f4 6d1 7s2",
"elementColor": [0.0, 0.5, 1.0],
"exactMass": 237.0481734,
"family": "Other_Metal",
"group": 7,
"ionization": 6.2657,
"mass": 237.0,
"meltingpoint": 912.0,
"mostCommonIsotope": "Np236",
"mostCommonIsotopeMass": 236.04657,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the planet Neptune.",
"outshellElectrons": 5,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.55,
"radiusVDW": 2.0,
"symbol": "Np",
"valences": []
}, {
"atomicNumber": 94,
"boilingpoint": 3505.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1940",
"electronegativityPauling": 1.28,
"electronicConfiguration": "Rn 5f6 7s2",
"elementColor": [0.0, 0.42, 1.0],
"exactMass": 244.064204,
"family": "Other_Metal",
"group": 8,
"ionization": 6.026,
"mass": 244.0,
"meltingpoint": 913.0,
"mostCommonIsotope": "Pu238",
"mostCommonIsotopeMass": 238.0495599,
"name": "PI:NAME:<NAME>END_PIutonium",
"nameOrigin": "Named after the planet Pluto.",
"outshellElectrons": 6,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.53,
"radiusVDW": 2.0,
"symbol": "Pu",
"valences": []
}, {
"atomicNumber": 95,
"boilingpoint": 2880.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1945",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f7 7s2",
"elementColor": [0.33, 0.36, 0.95],
"exactMass": 243.0613811,
"family": "Other_Metal",
"group": 8,
"ionization": 5.9738,
"mass": 243.0,
"meltingpoint": 1449.0,
"mostCommonIsotope": "Am241",
"mostCommonIsotopeMass": 241.0568291,
"name": "PI:NAME:<NAME>END_PIicium",
"nameOrigin": "Named after America.",
"outshellElectrons": 7,
"period": 7,
"periodTableBlock": "f",
"rB0": 1.07,
"radiusVDW": 2.0,
"symbol": "Am",
"valences": []
}, {
"atomicNumber": 96,
"boilingpoint": 3383.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1944",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f7 6d1 7s2",
"elementColor": [0.47, 0.36, 0.89],
"exactMass": 247.070354,
"family": "Other_Metal",
"group": 8,
"ionization": 5.9914,
"mass": 247.0,
"meltingpoint": 1620.0,
"mostCommonIsotope": "Cm243",
"mostCommonIsotopeMass": 243.0613891,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after PI:NAME:<NAME>END_PI.",
"outshellElectrons": 8,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Cm",
"valences": []
}, {
"atomicNumber": 97,
"boilingpoint": 983.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1949",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f9 7s2",
"elementColor": [0.54, 0.31, 0.89],
"exactMass": 247.070307,
"family": "Other_Metal",
"group": 1,
"ionization": 6.1979,
"mass": 247.0,
"meltingpoint": 1258.0,
"mostCommonIsotope": "Bk247",
"mostCommonIsotopeMass": 247.070307,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the town Berkeley where it was discovered.",
"outshellElectrons": 9,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Bk",
"valences": []
}, {
"atomicNumber": 98,
"boilingpoint": 1173.0,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1950",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f10 7s2",
"elementColor": [0.63, 0.21, 0.83],
"exactMass": 251.079587,
"family": "Other_Metal",
"group": 2,
"ionization": 6.2817,
"mass": 251.0,
"meltingpoint": 1172.0,
"mostCommonIsotope": "Cf249",
"mostCommonIsotopeMass": 249.0748535,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the US-State of California.",
"outshellElectrons": 10,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Cf",
"valences": []
}, {
"atomicNumber": 99,
"discoverers": ["PI:NAME:<NAME>END_PI", "et al."],
"discoveryDate": "1952",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f11 7s2",
"elementColor": [0.7, 0.12, 0.83],
"exactMass": 252.08298,
"family": "Other_Metal",
"group": 3,
"ionization": 6.42,
"mass": 252.0,
"meltingpoint": 1130.0,
"mostCommonIsotope": "Es252",
"mostCommonIsotopeMass": 252.08298,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 11,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Es",
"valences": []
}, {
"atomicNumber": 100,
"discoverers": ["PI:NAME:<NAME>END_PI", "et al."],
"discoveryDate": "1953",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f12 7s2",
"elementColor": [0.7, 0.12, 0.73],
"exactMass": 257.095105,
"family": "Other_Metal",
"group": 4,
"ionization": 6.5,
"mass": 257.0,
"meltingpoint": 1800.0,
"mostCommonIsotope": "Fm257",
"mostCommonIsotopeMass": 257.095105,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 12,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Fm",
"valences": []
}, {
"atomicNumber": 101,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1955",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f13 7s2",
"elementColor": [0.7, 0.05, 0.65],
"exactMass": 258.098431,
"family": "Other_Metal",
"group": 5,
"ionization": 6.58,
"mass": 258.0,
"meltingpoint": 1100.0,
"mostCommonIsotope": "Md258",
"mostCommonIsotopeMass": 258.098431,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 13,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Md",
"valences": []
}, {
"atomicNumber": 102,
"discoveryDate": "1958",
"electronegativityPauling": 1.3,
"electronicConfiguration": "Rn 5f14 7s2",
"elementColor": [0.74, 0.05, 0.53],
"exactMass": 259.10103,
"family": "Other_Metal",
"group": 6,
"ionization": 6.65,
"mass": 259.0,
"meltingpoint": 1100.0,
"mostCommonIsotope": "No259",
"mostCommonIsotopeMass": 259.10103,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 14,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "No",
"valences": []
}, {
"atomicNumber": 103,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"],
"discoveryDate": "1961",
"electronicConfiguration": "Rn 5f14 7s2 7p1",
"elementColor": [0.78, 0.0, 0.4],
"exactMass": 262.10963,
"family": "Other_Metal",
"group": 7,
"ionization": 4.9,
"mass": 262.0,
"meltingpoint": 1900.0,
"mostCommonIsotope": "Lr262",
"mostCommonIsotopeMass": 262.10963,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 15,
"period": 7,
"periodTableBlock": "f",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Lr",
"valences": []
}, {
"atomicNumber": 104,
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1964",
"electronicConfiguration": "Rn 5f14 6d2 7s2",
"elementColor": [0.8, 0.0, 0.35],
"exactMass": 261.10877,
"family": "Transition",
"group": 4,
"ionization": 6.0,
"mass": 267.0,
"mostCommonIsotope": "Rf267",
"mostCommonIsotopeMass": 267.12153,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Rf",
"valences": []
}, {
"atomicNumber": 105,
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1967",
"electronicConfiguration": "Rn 5f14 6d3 7s2",
"elementColor": [0.82, 0.0, 0.31],
"exactMass": 262.11408,
"family": "Transition",
"group": 5,
"mass": 268.0,
"mostCommonIsotope": "Db268",
"mostCommonIsotopeMass": 268.12545,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the science-town Dubna in Russia",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Db",
"valences": []
}, {
"atomicNumber": 106,
"discoverers": ["PI:NAME:<NAME>END_PI", "et al."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1974",
"elementColor": [0.85, 0.0, 0.27],
"exactMass": 263.11832,
"family": "Transition",
"group": 6,
"mass": 271.0,
"mostCommonIsotope": "Sg271",
"mostCommonIsotopeMass": 271.13347,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Sg",
"valences": []
}, {
"atomicNumber": 107,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI\u00fcPI:NAME:<NAME>END_PI", "et al."],
"discoveryCountry": "ru",
"discoveryDate": "1981",
"elementColor": [0.88, 0.0, 0.22],
"exactMass": 264.1246,
"family": "Transition",
"group": 7,
"mass": 272.0,
"mostCommonIsotope": "Bh270",
"mostCommonIsotopeMass": 270.13362,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Bh",
"valences": []
}, {
"atomicNumber": 108,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI\u00fcPI:NAME:<NAME>END_PI", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1984",
"elementColor": [0.9, 0.0, 0.18],
"exactMass": 265.13009,
"family": "Transition",
"group": 8,
"mass": 270.0,
"mostCommonIsotope": "Hs269",
"mostCommonIsotopeMass": 269.13406,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Latin 'hassia' for the German county Hessen. In Hessen a lot elements have been discovered.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Hs",
"valences": []
}, {
"atomicNumber": 109,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI\u00fcnPI:NAME:<NAME>END_PI", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1982",
"elementColor": [0.91, 0.0, 0.15],
"exactMass": 268.13873,
"family": "Transition",
"group": 8,
"mass": 276.0,
"mostCommonIsotope": "Mt278",
"mostCommonIsotopeMass": 278.15481,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the scientist PI:NAME:<NAME>END_PI.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"radiusVDW": 2.0,
"symbol": "Mt",
"valences": []
}, {
"atomicNumber": 110,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI\u00fcPI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI\u00f6PI:NAME:<NAME>END_PI", "et al."],
"discoveryCountry": "de",
"discoveryDate": "1994",
"elementColor": [0.92, 0.0, 0.14],
"exactMass": 271.14606,
"family": "Transition",
"group": 8,
"mass": 281.0,
"mostCommonIsotope": "Ds281",
"mostCommonIsotopeMass": 281.16206,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after the German city Darmstadt where many elements have been discovered.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Ds",
"valences": []
}, {
"atomicNumber": 111,
"discoverers": ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI00fcPI:NAME:<NAME>END_PI",
"et al."],
"discoveryCountry": "de",
"discoveryDate": "1994",
"elementColor": [0.93, 0.0, 0.13],
"exactMass": 272.15362,
"family": "Transition",
"group": 1,
"mass": 280.0,
"mostCommonIsotope": "Rg281",
"mostCommonIsotopeMass": 281.16537,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Named after PI:NAME:<NAME>END_PI\u00f6PI:NAME:<NAME>END_PI.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Rg",
"valences": []
}, {
"atomicNumber": 112,
"discoverers": "First created at the Gesellschaft f\u00fcr Schwerionenforschung",
"discoveryCountry": "de",
"discoveryDate": "1996",
"elementColor": [0.94, 0.0, 0.12],
"exactMass": 285.17411,
"family": "Transition",
"mass": 285.0,
"mostCommonIsotope": "Cn285",
"mostCommonIsotopeMass": 285.17411,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Historically known as eka-mercury. Ununbium is a temporary IUPAC systematic element name.",
"outshellElectrons": 2,
"period": 7,
"periodTableBlock": "d",
"rB0": 0.0,
"symbol": "Cn",
"valences": []
}, {
"atomicNumber": 113,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2003",
"elementColor": [0.95, 0.0, 0.11],
"exactMass": 284.17808,
"family": "Other_Metal",
"mass": 284.0,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Historically known as eka-thallium. Ununtrium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uut"
}, {
"atomicNumber": 114,
"discoverers": "Joint Institute for Nuclear Research",
"discoveryCountry": ["ru", "us"],
"discoveryDate": "1998",
"elementColor": [0.96, 0.0, 0.1],
"exactMass": 289.18728,
"family": "Other_Metal",
"mass": 289.0,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Historically known as eka-lead. Ununquadium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuq"
}, {
"atomicNumber": 115,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2004",
"elementColor": [0.97, 0.0, 0.09],
"exactMass": 288.19249,
"family": "Other_Metal",
"mass": 288.0,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Historically known as eka-bismuth. Ununpentium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uup"
}, {
"atomicNumber": 116,
"discoverers": "Joint Institute for Nuclear Research",
"discoveryCountry": "ru",
"discoveryDate": "2000",
"elementColor": [0.98, 0.0, 0.08],
"exactMass": 292.19979,
"family": "Other_Metal",
"mass": 293.0,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Historically known as eka-polonium. Ununhexium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuh"
}, {
"atomicNumber": 117,
"discoveryDate": "0",
"elementColor": [0.99, 0.0, 0.07],
"family": "Halogen",
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Temporary symbol and name. Can also be referred to as eka-astatine.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uus"
}, {
"atomicNumber": 118,
"discoverers": ["Russian scientists at Dubna (JINR)",
"American scientists at the Lawrence Livermore National Laboratory."],
"discoveryCountry": ["ru", "us"],
"discoveryDate": "2002",
"elementColor": [1.0, 0.0, 0.06],
"family": "Noblegas",
"mass": 294.0,
"name": "PI:NAME:<NAME>END_PI",
"nameOrigin": "Historically known as eka-radon, eka-emanation before 1960. Ununoctium is a temporary IUPAC systematic element name.",
"period": 7,
"periodTableBlock": "p",
"symbol": "Uuo"
}]
} |
[
{
"context": "ttern as described\n\t\t\t<a href=\"https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc#",
"end": 1777,
"score": 0.9989570379257202,
"start": 1770,
"tag": "USERNAME",
"value": "arduino"
},
{
"context": "\t\t\t\t'buildFolder': @buildFolders[file]\n\t\t\t\t'name': name\n\t\t\t\t'workpath': workpath\n\t\t\t}\n\t\t\tcallback code, i",
"end": 6571,
"score": 0.7572063207626343,
"start": 6567,
"tag": "NAME",
"value": "name"
}
] | lib/arduino-upload.coffee | lorenzos/arduino-upload | 36 | {CompositeDisposable} = require 'atom'
{spawn} = require 'child_process'
String::strip = -> if String::trim? then @trim() else @replace /^\s+|\s+$/g, ""
fs = require 'fs'
path = require 'path'
OutputView = require './output-view'
SerialView = require './serial-view'
tmp = require 'tmp'
{ separator, getArduinoPath } = require './util'
Boards = require './boards'
try
serialport = require 'serialport'
catch e
serialport = null
try
usbDetect = require 'usb-detection'
catch e
usbDetect = null
boards = new Boards
output = null
serial = null
serialeditor = null
removeDir = (dir) ->
if fs.existsSync dir
for file in fs.readdirSync dir
path = dir + '/' + file
if fs.lstatSync(path).isDirectory()
removeDir path
else
fs.unlinkSync path
fs.rmdirSync dir
module.exports = ArduinoUpload =
config:
arduinoExecutablePath:
title: 'Arduino Executable Path'
description: '''The path to the Arduino IDE executable or debug executable
. This checks the default install location automatically.'''
type: 'string'
default: 'arduino'
autosave:
title: 'AutoSave'
description: '''Enables auto-saving before building, uploading, or
verifying. The serial monitor will be closed for this operation, but can
be made to reopen automatically.'''
type: 'string'
default: 'disabled'
enum: ['disabled', 'save', 'save+reopen']
baudRate:
title: 'BAUD Rate'
description: '''Sets the BAUD rate for the serial connection, if this is
changed the serial monitor will need to be reopened.'''
type: 'number'
default: '9600'
board:
title: 'Arduino board'
description: '''If kept blank, this will take the settings from the
Arduino IDE. The board uses the pattern as described
<a href="https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc#options">here</a>'''
type: 'string'
default: ''
lineEnding:
title: 'Default line ending in serial monitor'
description: '''
0 - No line ending<br>
1 - Newline<br>
2 - Carriage return<br>
3 - Both NL & CR'''
type: 'integer'
default: 1
minimum: 0
maximum: 3
vendorsArduino: {
0x2341: true # Arduino
0x2a03: true # Arduino M0 Pro (perhaps other devices?)
0x03eb: true # Atmel
# knockoff producers
0x0403: [ 0x6001 ] # FTDI
0x1a86: [ 0x7523 ] # QuinHeng
0x0403: [ 0x6001 ] # Future Technology Devices International, Ltd
0x10c4: [ 0xea60 ] # Silicon Labs CP210x USB to UART Bridge
}
vendorsProgrammer: {
0x03eb: [ 0x2141 ] # Atmel ICE debugger
0x1781: [ 0x0c9f ] # USBtinyISP Clones
}
buildFolders: []
activate: (state) ->
# Setup to use the new composite disposables API for registering commands
@subscriptions = new CompositeDisposable
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:verify': => @build false
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:build': => @build true
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:upload': => @upload()
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:serial-monitor': => @openserial()
output = new OutputView
atom.workspace.addBottomPanel(item:output)
output.hide()
boards.init()
boards.load()
atom.config.onDidChange 'arduino-upload.arduinoExecutablePath', ({newValue, oldValue}) =>
boards.load()
atom.config.onDidChange 'arduino-upload.board', ({newValue, oldValue}) =>
boards.set newValue
atom.workspace.observeActivePaneItem (editor) =>
if @isArduinoProject().isArduino
boards.show()
else
boards.hide()
deactivate: ->
for own s, f of @buildFolders
removeDir f
@subscriptions.dispose()
output?.remove()
boards.destroy()
@closeserial()
consumeStatusBar: (statusBar) ->
boards.init()
boards.setStatusBar statusBar
additionalArduinoOptions: (path, port = false) ->
options = ['-v']
if atom.config.get('arduino-upload.board') != ''
options = options.concat ['--board', atom.config.get('arduino-upload.board')]
if typeof port != 'boolean'
if port == 'PROGRAMMER'
options.push '--useprogrammer'
else if port != 'ARDUINO'
options = options.concat ['--port', port]
if not @buildFolders[path]
@buildFolders[path] = tmp.dirSync().name
options = options.concat ['--pref', 'build.path='+@buildFolders[path]]
return options
isArduinoProject: () ->
editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file?.getPath()?.split separator
file?.pop()
name = file?.pop()
file?.push name
workpath = file?.join separator
name += '.ino'
file?.push name
file = file?.join separator
isArduino = fs.existsSync file
return {isArduino, workpath, file, name}
_build: (options, callback, onerror, port = false) ->
serialWasOpen = false
autosaveConf = atom.config.get('arduino-upload.autosave')
if (autosaveConf == 'save') || (autosaveConf == 'save+reopen')
if (autosaveConf == 'save+reopen') && (serial != null)
serialWasOpen = true
@closeserial()
atom.commands.dispatch(atom.views.getView(atom.workspace.getActiveTextEditor()), 'window:save-all')
{isArduino, workpath, file, name} = @isArduinoProject()
if not isArduino
atom.notifications.addError "The file isn't part of an Arduino sketch!"
callback false
return
dispError = false
output.reset()
atom.notifications.addInfo 'Building...'
options = [file].concat(options).concat @additionalArduinoOptions file, port
stdoutput = spawn getArduinoPath(), options
error = false
stdoutput.on 'error', (err) =>
atom.notifications.addError "Can't find the Arduino IDE, please install it and set <i>Arduino Executable Path</i> in the settings! (" + err + ")"
callback false
error = true
stdoutput.stdout.on 'data', (data) =>
if data.toString().strip().indexOf('Sketch') == 0 || data.toString().strip().indexOf('Global') == 0
atom.notifications.addInfo data.toString()
stdoutput.stderr.on 'data', (data) =>
console.log data.toString()
overrideError = false
if onerror
overrideError = onerror(data)
if data.toString().strip() == "exit status 1"
console.log "ERROR OUTPUT OFF"
dispError = false
if dispError && !overrideError
console.log data.toString()
output.addLine data.toString(), @buildFolders[file], workpath
if -1 != data.toString().toLowerCase().indexOf "verifying"
console.log "ERROR OUTPUT ACTIVATED"
dispError = true
stdoutput.on 'close', (code) =>
if error
return
info = {
'buildFolder': @buildFolders[file]
'name': name
'workpath': workpath
}
callback code, info
output.finish()
if (autosaveConf == 'save+reopen') && (serialWasOpen)
@openserial()
build: (keep) ->
@_build ['--verify'], (code, info) =>
if code != false
if code != 0
atom.notifications.addError 'Build failed!'
else if keep
for ending in ['.eep', '.elf', '.hex', '.bin']
fs.createReadStream(info.buildFolder + separator + info.name + ending).pipe(fs.createWriteStream(info.workpath + separator + info.name + ending))
upload: ->
@getPort (port) =>
if port == ''
atom.notifications.addError 'No Arduino found!'
return
callback = (code, info) =>
if code != false
if code == 0
atom.notifications.addInfo 'Successfully uploaded sketch'
else
if uploading
atom.notifications.addError "Couldn't upload the sketch to the board, is it connected?"
else
atom.notifications.addError 'Build failed!'
if serial != null
@_openserialport port, false
uploading = false
onerror = (data) =>
s = data.toString().toLowerCase()
if (s.indexOf("avrdude:") != -1 || s.indexOf("uploading") == 0) && !uploading
uploading = true
atom.notifications.addInfo 'Uploading...'
return uploading
if serial == null
# no serial connection open to halt
@_build ['--upload'], callback, onerror, port
return
@serialNormalClose = false
serial.close (err) =>
@_build ['--upload'], callback, onerror, port
isArduino: (vid, pid, vendors = false) ->
if typeof vid == 'string'
vid = parseInt vid, 16
if typeof pid == 'string'
pid = parseInt pid, 16
if !vendors
vendors = @vendorsArduino
for own v, p of vendors
if vid == parseInt v
if p && typeof p == 'boolean'
return true
if -1 != p.indexOf pid
return true
return false
_getPort: (callback) ->
serialport.list().then (ports) =>
console.log ports
p = ''
for port in ports
if @isArduino(port.vendorId, port.productId)
p = port.path;
break
callback p
getPort: (callback) ->
if serialport == null and usbDetect == null
console.log 'NOTHING TO CHECK'
callback 'ARDUINO'
return
if usbDetect == null
console.log 'ONLY SERIALPORT'
@_getPort callback
return
usbDetect.find (err, ports) =>
for port in ports
if @isArduino port.vendorId, port.productId, @vendorsProgrammer
callback 'PROGRAMMER'
return
if serialport == null
callback 'ARDUINO'
return
@_getPort callback
serialNormalClose: true
_openserialport: (port, start = true)->
try
serialport serial = new serialport(port, {
baudRate: atom.config.get('arduino-upload.baudRate')
parser: serialport.parsers.raw
});
@serialNormalClose = true
serial.on 'open', (data) =>
if start
atom.notifications.addInfo 'Serial port opened'
serial.on 'data', (data) =>
serialeditor?.insertText data
serial.on 'close', (data) =>
if @serialNormalClose
@closeserial()
atom.notifications.addInfo 'Serial port closed'
serial.on 'error', (data) =>
console.log data
@closeserial()
atom.notifications.addInfo "Can't open serial port"
catch e
@closeserial()
atom.notifications.addError e.toString()
openserialport: ->
if serial!=null
atom.notifications.addInfo 'Serial port already open'
return
p = ''
@getPort (port) =>
if port == 'PROGRAMMER'
atom.notifications.addError "Can't use a programmer as serial monitor!"
@closeserial()
return
if port == '' or port == 'ARDUINO'
atom.notifications.addError 'No Arduino found!'
@closeserial()
return
@_openserialport(port)
openserial: ->
if serialport == null
atom.notifications.addInfo 'Serialport dependency not present!'
return
if serial!=null
return
serialeditor = new SerialView
serialeditor.open =>
serialeditor.onDidDestroy =>
@closeserial()
serialeditor.onSend (s) =>
serial?.write s
@openserialport()
closeserial: ->
serial?.close (err) ->
return
serial = null
serialeditor?.destroy()
serialeditor = null
| 16245 | {CompositeDisposable} = require 'atom'
{spawn} = require 'child_process'
String::strip = -> if String::trim? then @trim() else @replace /^\s+|\s+$/g, ""
fs = require 'fs'
path = require 'path'
OutputView = require './output-view'
SerialView = require './serial-view'
tmp = require 'tmp'
{ separator, getArduinoPath } = require './util'
Boards = require './boards'
try
serialport = require 'serialport'
catch e
serialport = null
try
usbDetect = require 'usb-detection'
catch e
usbDetect = null
boards = new Boards
output = null
serial = null
serialeditor = null
removeDir = (dir) ->
if fs.existsSync dir
for file in fs.readdirSync dir
path = dir + '/' + file
if fs.lstatSync(path).isDirectory()
removeDir path
else
fs.unlinkSync path
fs.rmdirSync dir
module.exports = ArduinoUpload =
config:
arduinoExecutablePath:
title: 'Arduino Executable Path'
description: '''The path to the Arduino IDE executable or debug executable
. This checks the default install location automatically.'''
type: 'string'
default: 'arduino'
autosave:
title: 'AutoSave'
description: '''Enables auto-saving before building, uploading, or
verifying. The serial monitor will be closed for this operation, but can
be made to reopen automatically.'''
type: 'string'
default: 'disabled'
enum: ['disabled', 'save', 'save+reopen']
baudRate:
title: 'BAUD Rate'
description: '''Sets the BAUD rate for the serial connection, if this is
changed the serial monitor will need to be reopened.'''
type: 'number'
default: '9600'
board:
title: 'Arduino board'
description: '''If kept blank, this will take the settings from the
Arduino IDE. The board uses the pattern as described
<a href="https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc#options">here</a>'''
type: 'string'
default: ''
lineEnding:
title: 'Default line ending in serial monitor'
description: '''
0 - No line ending<br>
1 - Newline<br>
2 - Carriage return<br>
3 - Both NL & CR'''
type: 'integer'
default: 1
minimum: 0
maximum: 3
vendorsArduino: {
0x2341: true # Arduino
0x2a03: true # Arduino M0 Pro (perhaps other devices?)
0x03eb: true # Atmel
# knockoff producers
0x0403: [ 0x6001 ] # FTDI
0x1a86: [ 0x7523 ] # QuinHeng
0x0403: [ 0x6001 ] # Future Technology Devices International, Ltd
0x10c4: [ 0xea60 ] # Silicon Labs CP210x USB to UART Bridge
}
vendorsProgrammer: {
0x03eb: [ 0x2141 ] # Atmel ICE debugger
0x1781: [ 0x0c9f ] # USBtinyISP Clones
}
buildFolders: []
activate: (state) ->
# Setup to use the new composite disposables API for registering commands
@subscriptions = new CompositeDisposable
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:verify': => @build false
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:build': => @build true
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:upload': => @upload()
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:serial-monitor': => @openserial()
output = new OutputView
atom.workspace.addBottomPanel(item:output)
output.hide()
boards.init()
boards.load()
atom.config.onDidChange 'arduino-upload.arduinoExecutablePath', ({newValue, oldValue}) =>
boards.load()
atom.config.onDidChange 'arduino-upload.board', ({newValue, oldValue}) =>
boards.set newValue
atom.workspace.observeActivePaneItem (editor) =>
if @isArduinoProject().isArduino
boards.show()
else
boards.hide()
deactivate: ->
for own s, f of @buildFolders
removeDir f
@subscriptions.dispose()
output?.remove()
boards.destroy()
@closeserial()
consumeStatusBar: (statusBar) ->
boards.init()
boards.setStatusBar statusBar
additionalArduinoOptions: (path, port = false) ->
options = ['-v']
if atom.config.get('arduino-upload.board') != ''
options = options.concat ['--board', atom.config.get('arduino-upload.board')]
if typeof port != 'boolean'
if port == 'PROGRAMMER'
options.push '--useprogrammer'
else if port != 'ARDUINO'
options = options.concat ['--port', port]
if not @buildFolders[path]
@buildFolders[path] = tmp.dirSync().name
options = options.concat ['--pref', 'build.path='+@buildFolders[path]]
return options
isArduinoProject: () ->
editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file?.getPath()?.split separator
file?.pop()
name = file?.pop()
file?.push name
workpath = file?.join separator
name += '.ino'
file?.push name
file = file?.join separator
isArduino = fs.existsSync file
return {isArduino, workpath, file, name}
_build: (options, callback, onerror, port = false) ->
serialWasOpen = false
autosaveConf = atom.config.get('arduino-upload.autosave')
if (autosaveConf == 'save') || (autosaveConf == 'save+reopen')
if (autosaveConf == 'save+reopen') && (serial != null)
serialWasOpen = true
@closeserial()
atom.commands.dispatch(atom.views.getView(atom.workspace.getActiveTextEditor()), 'window:save-all')
{isArduino, workpath, file, name} = @isArduinoProject()
if not isArduino
atom.notifications.addError "The file isn't part of an Arduino sketch!"
callback false
return
dispError = false
output.reset()
atom.notifications.addInfo 'Building...'
options = [file].concat(options).concat @additionalArduinoOptions file, port
stdoutput = spawn getArduinoPath(), options
error = false
stdoutput.on 'error', (err) =>
atom.notifications.addError "Can't find the Arduino IDE, please install it and set <i>Arduino Executable Path</i> in the settings! (" + err + ")"
callback false
error = true
stdoutput.stdout.on 'data', (data) =>
if data.toString().strip().indexOf('Sketch') == 0 || data.toString().strip().indexOf('Global') == 0
atom.notifications.addInfo data.toString()
stdoutput.stderr.on 'data', (data) =>
console.log data.toString()
overrideError = false
if onerror
overrideError = onerror(data)
if data.toString().strip() == "exit status 1"
console.log "ERROR OUTPUT OFF"
dispError = false
if dispError && !overrideError
console.log data.toString()
output.addLine data.toString(), @buildFolders[file], workpath
if -1 != data.toString().toLowerCase().indexOf "verifying"
console.log "ERROR OUTPUT ACTIVATED"
dispError = true
stdoutput.on 'close', (code) =>
if error
return
info = {
'buildFolder': @buildFolders[file]
'name': <NAME>
'workpath': workpath
}
callback code, info
output.finish()
if (autosaveConf == 'save+reopen') && (serialWasOpen)
@openserial()
build: (keep) ->
@_build ['--verify'], (code, info) =>
if code != false
if code != 0
atom.notifications.addError 'Build failed!'
else if keep
for ending in ['.eep', '.elf', '.hex', '.bin']
fs.createReadStream(info.buildFolder + separator + info.name + ending).pipe(fs.createWriteStream(info.workpath + separator + info.name + ending))
upload: ->
@getPort (port) =>
if port == ''
atom.notifications.addError 'No Arduino found!'
return
callback = (code, info) =>
if code != false
if code == 0
atom.notifications.addInfo 'Successfully uploaded sketch'
else
if uploading
atom.notifications.addError "Couldn't upload the sketch to the board, is it connected?"
else
atom.notifications.addError 'Build failed!'
if serial != null
@_openserialport port, false
uploading = false
onerror = (data) =>
s = data.toString().toLowerCase()
if (s.indexOf("avrdude:") != -1 || s.indexOf("uploading") == 0) && !uploading
uploading = true
atom.notifications.addInfo 'Uploading...'
return uploading
if serial == null
# no serial connection open to halt
@_build ['--upload'], callback, onerror, port
return
@serialNormalClose = false
serial.close (err) =>
@_build ['--upload'], callback, onerror, port
isArduino: (vid, pid, vendors = false) ->
if typeof vid == 'string'
vid = parseInt vid, 16
if typeof pid == 'string'
pid = parseInt pid, 16
if !vendors
vendors = @vendorsArduino
for own v, p of vendors
if vid == parseInt v
if p && typeof p == 'boolean'
return true
if -1 != p.indexOf pid
return true
return false
_getPort: (callback) ->
serialport.list().then (ports) =>
console.log ports
p = ''
for port in ports
if @isArduino(port.vendorId, port.productId)
p = port.path;
break
callback p
getPort: (callback) ->
if serialport == null and usbDetect == null
console.log 'NOTHING TO CHECK'
callback 'ARDUINO'
return
if usbDetect == null
console.log 'ONLY SERIALPORT'
@_getPort callback
return
usbDetect.find (err, ports) =>
for port in ports
if @isArduino port.vendorId, port.productId, @vendorsProgrammer
callback 'PROGRAMMER'
return
if serialport == null
callback 'ARDUINO'
return
@_getPort callback
serialNormalClose: true
_openserialport: (port, start = true)->
try
serialport serial = new serialport(port, {
baudRate: atom.config.get('arduino-upload.baudRate')
parser: serialport.parsers.raw
});
@serialNormalClose = true
serial.on 'open', (data) =>
if start
atom.notifications.addInfo 'Serial port opened'
serial.on 'data', (data) =>
serialeditor?.insertText data
serial.on 'close', (data) =>
if @serialNormalClose
@closeserial()
atom.notifications.addInfo 'Serial port closed'
serial.on 'error', (data) =>
console.log data
@closeserial()
atom.notifications.addInfo "Can't open serial port"
catch e
@closeserial()
atom.notifications.addError e.toString()
openserialport: ->
if serial!=null
atom.notifications.addInfo 'Serial port already open'
return
p = ''
@getPort (port) =>
if port == 'PROGRAMMER'
atom.notifications.addError "Can't use a programmer as serial monitor!"
@closeserial()
return
if port == '' or port == 'ARDUINO'
atom.notifications.addError 'No Arduino found!'
@closeserial()
return
@_openserialport(port)
openserial: ->
if serialport == null
atom.notifications.addInfo 'Serialport dependency not present!'
return
if serial!=null
return
serialeditor = new SerialView
serialeditor.open =>
serialeditor.onDidDestroy =>
@closeserial()
serialeditor.onSend (s) =>
serial?.write s
@openserialport()
closeserial: ->
serial?.close (err) ->
return
serial = null
serialeditor?.destroy()
serialeditor = null
| true | {CompositeDisposable} = require 'atom'
{spawn} = require 'child_process'
String::strip = -> if String::trim? then @trim() else @replace /^\s+|\s+$/g, ""
fs = require 'fs'
path = require 'path'
OutputView = require './output-view'
SerialView = require './serial-view'
tmp = require 'tmp'
{ separator, getArduinoPath } = require './util'
Boards = require './boards'
try
serialport = require 'serialport'
catch e
serialport = null
try
usbDetect = require 'usb-detection'
catch e
usbDetect = null
boards = new Boards
output = null
serial = null
serialeditor = null
removeDir = (dir) ->
if fs.existsSync dir
for file in fs.readdirSync dir
path = dir + '/' + file
if fs.lstatSync(path).isDirectory()
removeDir path
else
fs.unlinkSync path
fs.rmdirSync dir
module.exports = ArduinoUpload =
config:
arduinoExecutablePath:
title: 'Arduino Executable Path'
description: '''The path to the Arduino IDE executable or debug executable
. This checks the default install location automatically.'''
type: 'string'
default: 'arduino'
autosave:
title: 'AutoSave'
description: '''Enables auto-saving before building, uploading, or
verifying. The serial monitor will be closed for this operation, but can
be made to reopen automatically.'''
type: 'string'
default: 'disabled'
enum: ['disabled', 'save', 'save+reopen']
baudRate:
title: 'BAUD Rate'
description: '''Sets the BAUD rate for the serial connection, if this is
changed the serial monitor will need to be reopened.'''
type: 'number'
default: '9600'
board:
title: 'Arduino board'
description: '''If kept blank, this will take the settings from the
Arduino IDE. The board uses the pattern as described
<a href="https://github.com/arduino/Arduino/blob/ide-1.5.x/build/shared/manpage.adoc#options">here</a>'''
type: 'string'
default: ''
lineEnding:
title: 'Default line ending in serial monitor'
description: '''
0 - No line ending<br>
1 - Newline<br>
2 - Carriage return<br>
3 - Both NL & CR'''
type: 'integer'
default: 1
minimum: 0
maximum: 3
vendorsArduino: {
0x2341: true # Arduino
0x2a03: true # Arduino M0 Pro (perhaps other devices?)
0x03eb: true # Atmel
# knockoff producers
0x0403: [ 0x6001 ] # FTDI
0x1a86: [ 0x7523 ] # QuinHeng
0x0403: [ 0x6001 ] # Future Technology Devices International, Ltd
0x10c4: [ 0xea60 ] # Silicon Labs CP210x USB to UART Bridge
}
vendorsProgrammer: {
0x03eb: [ 0x2141 ] # Atmel ICE debugger
0x1781: [ 0x0c9f ] # USBtinyISP Clones
}
buildFolders: []
activate: (state) ->
# Setup to use the new composite disposables API for registering commands
@subscriptions = new CompositeDisposable
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:verify': => @build false
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:build': => @build true
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:upload': => @upload()
@subscriptions.add atom.commands.add "atom-workspace",
'arduino-upload:serial-monitor': => @openserial()
output = new OutputView
atom.workspace.addBottomPanel(item:output)
output.hide()
boards.init()
boards.load()
atom.config.onDidChange 'arduino-upload.arduinoExecutablePath', ({newValue, oldValue}) =>
boards.load()
atom.config.onDidChange 'arduino-upload.board', ({newValue, oldValue}) =>
boards.set newValue
atom.workspace.observeActivePaneItem (editor) =>
if @isArduinoProject().isArduino
boards.show()
else
boards.hide()
deactivate: ->
for own s, f of @buildFolders
removeDir f
@subscriptions.dispose()
output?.remove()
boards.destroy()
@closeserial()
consumeStatusBar: (statusBar) ->
boards.init()
boards.setStatusBar statusBar
additionalArduinoOptions: (path, port = false) ->
options = ['-v']
if atom.config.get('arduino-upload.board') != ''
options = options.concat ['--board', atom.config.get('arduino-upload.board')]
if typeof port != 'boolean'
if port == 'PROGRAMMER'
options.push '--useprogrammer'
else if port != 'ARDUINO'
options = options.concat ['--port', port]
if not @buildFolders[path]
@buildFolders[path] = tmp.dirSync().name
options = options.concat ['--pref', 'build.path='+@buildFolders[path]]
return options
isArduinoProject: () ->
editor = atom.workspace.getActivePaneItem()
file = editor?.buffer?.file?.getPath()?.split separator
file?.pop()
name = file?.pop()
file?.push name
workpath = file?.join separator
name += '.ino'
file?.push name
file = file?.join separator
isArduino = fs.existsSync file
return {isArduino, workpath, file, name}
_build: (options, callback, onerror, port = false) ->
serialWasOpen = false
autosaveConf = atom.config.get('arduino-upload.autosave')
if (autosaveConf == 'save') || (autosaveConf == 'save+reopen')
if (autosaveConf == 'save+reopen') && (serial != null)
serialWasOpen = true
@closeserial()
atom.commands.dispatch(atom.views.getView(atom.workspace.getActiveTextEditor()), 'window:save-all')
{isArduino, workpath, file, name} = @isArduinoProject()
if not isArduino
atom.notifications.addError "The file isn't part of an Arduino sketch!"
callback false
return
dispError = false
output.reset()
atom.notifications.addInfo 'Building...'
options = [file].concat(options).concat @additionalArduinoOptions file, port
stdoutput = spawn getArduinoPath(), options
error = false
stdoutput.on 'error', (err) =>
atom.notifications.addError "Can't find the Arduino IDE, please install it and set <i>Arduino Executable Path</i> in the settings! (" + err + ")"
callback false
error = true
stdoutput.stdout.on 'data', (data) =>
if data.toString().strip().indexOf('Sketch') == 0 || data.toString().strip().indexOf('Global') == 0
atom.notifications.addInfo data.toString()
stdoutput.stderr.on 'data', (data) =>
console.log data.toString()
overrideError = false
if onerror
overrideError = onerror(data)
if data.toString().strip() == "exit status 1"
console.log "ERROR OUTPUT OFF"
dispError = false
if dispError && !overrideError
console.log data.toString()
output.addLine data.toString(), @buildFolders[file], workpath
if -1 != data.toString().toLowerCase().indexOf "verifying"
console.log "ERROR OUTPUT ACTIVATED"
dispError = true
stdoutput.on 'close', (code) =>
if error
return
info = {
'buildFolder': @buildFolders[file]
'name': PI:NAME:<NAME>END_PI
'workpath': workpath
}
callback code, info
output.finish()
if (autosaveConf == 'save+reopen') && (serialWasOpen)
@openserial()
build: (keep) ->
@_build ['--verify'], (code, info) =>
if code != false
if code != 0
atom.notifications.addError 'Build failed!'
else if keep
for ending in ['.eep', '.elf', '.hex', '.bin']
fs.createReadStream(info.buildFolder + separator + info.name + ending).pipe(fs.createWriteStream(info.workpath + separator + info.name + ending))
upload: ->
@getPort (port) =>
if port == ''
atom.notifications.addError 'No Arduino found!'
return
callback = (code, info) =>
if code != false
if code == 0
atom.notifications.addInfo 'Successfully uploaded sketch'
else
if uploading
atom.notifications.addError "Couldn't upload the sketch to the board, is it connected?"
else
atom.notifications.addError 'Build failed!'
if serial != null
@_openserialport port, false
uploading = false
onerror = (data) =>
s = data.toString().toLowerCase()
if (s.indexOf("avrdude:") != -1 || s.indexOf("uploading") == 0) && !uploading
uploading = true
atom.notifications.addInfo 'Uploading...'
return uploading
if serial == null
# no serial connection open to halt
@_build ['--upload'], callback, onerror, port
return
@serialNormalClose = false
serial.close (err) =>
@_build ['--upload'], callback, onerror, port
isArduino: (vid, pid, vendors = false) ->
if typeof vid == 'string'
vid = parseInt vid, 16
if typeof pid == 'string'
pid = parseInt pid, 16
if !vendors
vendors = @vendorsArduino
for own v, p of vendors
if vid == parseInt v
if p && typeof p == 'boolean'
return true
if -1 != p.indexOf pid
return true
return false
_getPort: (callback) ->
serialport.list().then (ports) =>
console.log ports
p = ''
for port in ports
if @isArduino(port.vendorId, port.productId)
p = port.path;
break
callback p
getPort: (callback) ->
if serialport == null and usbDetect == null
console.log 'NOTHING TO CHECK'
callback 'ARDUINO'
return
if usbDetect == null
console.log 'ONLY SERIALPORT'
@_getPort callback
return
usbDetect.find (err, ports) =>
for port in ports
if @isArduino port.vendorId, port.productId, @vendorsProgrammer
callback 'PROGRAMMER'
return
if serialport == null
callback 'ARDUINO'
return
@_getPort callback
serialNormalClose: true
_openserialport: (port, start = true)->
try
serialport serial = new serialport(port, {
baudRate: atom.config.get('arduino-upload.baudRate')
parser: serialport.parsers.raw
});
@serialNormalClose = true
serial.on 'open', (data) =>
if start
atom.notifications.addInfo 'Serial port opened'
serial.on 'data', (data) =>
serialeditor?.insertText data
serial.on 'close', (data) =>
if @serialNormalClose
@closeserial()
atom.notifications.addInfo 'Serial port closed'
serial.on 'error', (data) =>
console.log data
@closeserial()
atom.notifications.addInfo "Can't open serial port"
catch e
@closeserial()
atom.notifications.addError e.toString()
openserialport: ->
if serial!=null
atom.notifications.addInfo 'Serial port already open'
return
p = ''
@getPort (port) =>
if port == 'PROGRAMMER'
atom.notifications.addError "Can't use a programmer as serial monitor!"
@closeserial()
return
if port == '' or port == 'ARDUINO'
atom.notifications.addError 'No Arduino found!'
@closeserial()
return
@_openserialport(port)
openserial: ->
if serialport == null
atom.notifications.addInfo 'Serialport dependency not present!'
return
if serial!=null
return
serialeditor = new SerialView
serialeditor.open =>
serialeditor.onDidDestroy =>
@closeserial()
serialeditor.onSend (s) =>
serial?.write s
@openserialport()
closeserial: ->
serial?.close (err) ->
return
serial = null
serialeditor?.destroy()
serialeditor = null
|
[
{
"context": "our Delicious username>\n# DELICIOUS_PASSWORD = <Your Delicious password>\n#\n# bookmark <url> as <description> - add a url ",
"end": 337,
"score": 0.8147557377815247,
"start": 314,
"tag": "PASSWORD",
"value": "Your Delicious password"
},
{
"context": "msg, user, password) ->\n @msg = msg\n @user = user\n @password = password\n\n feed_url: ->\n \"htt",
"end": 4408,
"score": 0.9571202993392944,
"start": 4404,
"tag": "USERNAME",
"value": "user"
},
{
"context": "->\n @msg = msg\n @user = user\n @password = password\n\n feed_url: ->\n \"https://delicious.com/v2/rss",
"end": 4433,
"score": 0.998891294002533,
"start": 4425,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "om/v2/rss/#{@user}\"\n\n authdata: ->\n new Buffer(@user+':'+@password).toString('base64')\n\n createBo",
"end": 4524,
"score": 0.8618559241294861,
"start": 4524,
"tag": "USERNAME",
"value": ""
}
] | src/scripts/bookmark.coffee | iangreenleaf/hubot-scripts | 5 | # Manage your links and bookmarks. Links get stored in the robot brain while
# bookmarks get stored at delicious.com. Also keeps a history of all URLs in
# the "urls" section of the robot brain.
#
# You need to set the following variables:
# DELICIOUS_USER = <Your Delicious username>
# DELICIOUS_PASSWORD = <Your Delicious password>
#
# bookmark <url> as <description> - add a url to your delicious feed
# link <url> as <description> - add a url to the robot brain
# link me for <description> - find a link by description
# list bookmarks - get a list of the 15 most recent bookmarks
# list links - List all of the links that are being tracked
# feed me - get the URL to subscribe to your bookmark rss
#
module.exports = (robot) ->
robot.respond /feed me/i, (msg) ->
msg.reply "You can subscribe to the delicious feed at https://delicious.com/v2/rss/#{process.env.DELICIOUS_USER}"
robot.respond /list bookmarks/i, (msg) ->
delicious = new Delicious msg, process.env.DELICIOUS_USER, process.env.DELICIOUS_PASSWORD
delicious.listBookmarks (err, message) ->
if err?
msg.send "#{err}"
else
msg.send "#{message}"
robot.respond /bookmark (http(s?)\:\/\/\S+) as (.+)/i, (msg) ->
delicious = new Delicious msg, process.env.DELICIOUS_USER, process.env.DELICIOUS_PASSWORD
url = msg.match[1]
description = msg.match[3]
bookmark = new Bookmark url, description
delicious.createBookmark bookmark, (err, message) ->
if err?
msg.send "#{err}"
else
msg.send "#{message}"
robot.respond /link (http(s?)\:\/\/\S+) as (.+)/i, (msg) ->
url = msg.match[1]
description = msg.match[3]
bookmark = new Bookmark url, description
link = new Link robot
link.add bookmark, (err, message) ->
if err?
msg.reply "I have a vague memory of hearing about that link sometime in the past."
else
msg.reply "I've stuck that link into my robot brain."
robot.respond /link me for (.+)/i, (msg) ->
description = msg.match[1]
link = new Link robot
link.find description, (err, bookmark) ->
if err?
msg.send "#{err}"
else
msg.send bookmark.url
robot.respond /list links/i, (msg) ->
link = new Link robot
link.list (err, message) ->
if err?
msg.reply "Links? What links? I don't remember any links."
else
msg.reply message
robot.hear /(http(s?)\:\/\/\S+)/i, (msg) ->
href = msg.match[1]
url = new Url robot
url.add href, (err, message) ->
if err?
console.log "#{href} : #{err}"
# Classes
class Url
constructor: (robot) ->
robot.brain.data.urls ?= []
@urls_ = robot.brain.data.urls
all: (url) ->
if url
@urls_.push url
else
@urls_
add: (url, callback) ->
if url in @all()
callback "Url already exists"
else
@all url
callback null, "Url added"
class Bookmark
constructor: (url, description) ->
@url = url
@description = description
encodedUrl: ->
encodeURIComponent @url
encodedDescription: ->
encodeURIComponent @description
class Link
constructor: (robot) ->
robot.brain.data.links ?= []
@links_ = robot.brain.data.links
all: (bookmark) ->
if bookmark
@links_.push bookmark
else
@links_
add: (bookmark, callback) ->
result = []
@all().forEach (entry) ->
if entry
if entry.url is bookmark.url
result.push bookmark
if result.length > 0
callback "Bookmark already exists"
else
@all bookmark
callback null, "Bookmark added"
list: (callback) ->
if @all().length > 0
resp_str = "These are the links I'm remembering:\n\n"
for bookmark in @all()
if bookmark
resp_str += bookmark.description + " (" + bookmark.url + ")\n"
callback null, resp_str
else
callback "No bookmarks exist"
find: (description, callback) ->
result = []
@all().forEach (bookmark) ->
if bookmark && bookmark.description
if RegExp(description, "i").test bookmark.description
result.push bookmark
if result.length > 0
callback null, result[0]
else
callback "No results found"
class Delicious
constructor: (msg, user, password) ->
@msg = msg
@user = user
@password = password
feed_url: ->
"https://delicious.com/v2/rss/#{@user}"
authdata: ->
new Buffer(@user+':'+@password).toString('base64')
createBookmark: (bookmark, callback) ->
api_url = "https://api.del.icio.us/v1/posts/add?" +
"url=#{bookmark.encodedUrl()}" +
"&description=#{bookmark.encodedDescription()}"
@getDelicious api_url, (err, data) ->
if err? or not data?
callback err
else
resultRegexp = /result code="(.+)"/i
result = data.match(resultRegexp)[1]
if result == 'done'
callback null, "Your bookmark was added to delicious."
else
callback "There was a problem adding your bookmark to delicious: #{result}"
listBookmarks: (callback) ->
xml2js = require('xml2js')
api_url = "https://api.del.icio.us/v1/posts/recent"
@getDelicious api_url, (err, data) ->
if err? or not data?
callback err
else
resp_str = "My bookmarks: \n"
(new xml2js.Parser()).parseString data, (err, json)->
for post in json.post
resp_str += post["@"].description + " (" + post["@"].href + ")\n"
callback null, resp_str
getDelicious: (api_url, callback) ->
@msg.http(api_url).
header('Authorization', 'Basic ' + @authdata()).
get() (err, res, body) ->
if res.statusCode is 200
callback null, body
else if err?
callback err
else
callback "There were problems contacting delicious"
| 167565 | # Manage your links and bookmarks. Links get stored in the robot brain while
# bookmarks get stored at delicious.com. Also keeps a history of all URLs in
# the "urls" section of the robot brain.
#
# You need to set the following variables:
# DELICIOUS_USER = <Your Delicious username>
# DELICIOUS_PASSWORD = <<PASSWORD>>
#
# bookmark <url> as <description> - add a url to your delicious feed
# link <url> as <description> - add a url to the robot brain
# link me for <description> - find a link by description
# list bookmarks - get a list of the 15 most recent bookmarks
# list links - List all of the links that are being tracked
# feed me - get the URL to subscribe to your bookmark rss
#
module.exports = (robot) ->
robot.respond /feed me/i, (msg) ->
msg.reply "You can subscribe to the delicious feed at https://delicious.com/v2/rss/#{process.env.DELICIOUS_USER}"
robot.respond /list bookmarks/i, (msg) ->
delicious = new Delicious msg, process.env.DELICIOUS_USER, process.env.DELICIOUS_PASSWORD
delicious.listBookmarks (err, message) ->
if err?
msg.send "#{err}"
else
msg.send "#{message}"
robot.respond /bookmark (http(s?)\:\/\/\S+) as (.+)/i, (msg) ->
delicious = new Delicious msg, process.env.DELICIOUS_USER, process.env.DELICIOUS_PASSWORD
url = msg.match[1]
description = msg.match[3]
bookmark = new Bookmark url, description
delicious.createBookmark bookmark, (err, message) ->
if err?
msg.send "#{err}"
else
msg.send "#{message}"
robot.respond /link (http(s?)\:\/\/\S+) as (.+)/i, (msg) ->
url = msg.match[1]
description = msg.match[3]
bookmark = new Bookmark url, description
link = new Link robot
link.add bookmark, (err, message) ->
if err?
msg.reply "I have a vague memory of hearing about that link sometime in the past."
else
msg.reply "I've stuck that link into my robot brain."
robot.respond /link me for (.+)/i, (msg) ->
description = msg.match[1]
link = new Link robot
link.find description, (err, bookmark) ->
if err?
msg.send "#{err}"
else
msg.send bookmark.url
robot.respond /list links/i, (msg) ->
link = new Link robot
link.list (err, message) ->
if err?
msg.reply "Links? What links? I don't remember any links."
else
msg.reply message
robot.hear /(http(s?)\:\/\/\S+)/i, (msg) ->
href = msg.match[1]
url = new Url robot
url.add href, (err, message) ->
if err?
console.log "#{href} : #{err}"
# Classes
class Url
constructor: (robot) ->
robot.brain.data.urls ?= []
@urls_ = robot.brain.data.urls
all: (url) ->
if url
@urls_.push url
else
@urls_
add: (url, callback) ->
if url in @all()
callback "Url already exists"
else
@all url
callback null, "Url added"
class Bookmark
constructor: (url, description) ->
@url = url
@description = description
encodedUrl: ->
encodeURIComponent @url
encodedDescription: ->
encodeURIComponent @description
class Link
constructor: (robot) ->
robot.brain.data.links ?= []
@links_ = robot.brain.data.links
all: (bookmark) ->
if bookmark
@links_.push bookmark
else
@links_
add: (bookmark, callback) ->
result = []
@all().forEach (entry) ->
if entry
if entry.url is bookmark.url
result.push bookmark
if result.length > 0
callback "Bookmark already exists"
else
@all bookmark
callback null, "Bookmark added"
list: (callback) ->
if @all().length > 0
resp_str = "These are the links I'm remembering:\n\n"
for bookmark in @all()
if bookmark
resp_str += bookmark.description + " (" + bookmark.url + ")\n"
callback null, resp_str
else
callback "No bookmarks exist"
find: (description, callback) ->
result = []
@all().forEach (bookmark) ->
if bookmark && bookmark.description
if RegExp(description, "i").test bookmark.description
result.push bookmark
if result.length > 0
callback null, result[0]
else
callback "No results found"
class Delicious
constructor: (msg, user, password) ->
@msg = msg
@user = user
@password = <PASSWORD>
feed_url: ->
"https://delicious.com/v2/rss/#{@user}"
authdata: ->
new Buffer(@user+':'+@password).toString('base64')
createBookmark: (bookmark, callback) ->
api_url = "https://api.del.icio.us/v1/posts/add?" +
"url=#{bookmark.encodedUrl()}" +
"&description=#{bookmark.encodedDescription()}"
@getDelicious api_url, (err, data) ->
if err? or not data?
callback err
else
resultRegexp = /result code="(.+)"/i
result = data.match(resultRegexp)[1]
if result == 'done'
callback null, "Your bookmark was added to delicious."
else
callback "There was a problem adding your bookmark to delicious: #{result}"
listBookmarks: (callback) ->
xml2js = require('xml2js')
api_url = "https://api.del.icio.us/v1/posts/recent"
@getDelicious api_url, (err, data) ->
if err? or not data?
callback err
else
resp_str = "My bookmarks: \n"
(new xml2js.Parser()).parseString data, (err, json)->
for post in json.post
resp_str += post["@"].description + " (" + post["@"].href + ")\n"
callback null, resp_str
getDelicious: (api_url, callback) ->
@msg.http(api_url).
header('Authorization', 'Basic ' + @authdata()).
get() (err, res, body) ->
if res.statusCode is 200
callback null, body
else if err?
callback err
else
callback "There were problems contacting delicious"
| true | # Manage your links and bookmarks. Links get stored in the robot brain while
# bookmarks get stored at delicious.com. Also keeps a history of all URLs in
# the "urls" section of the robot brain.
#
# You need to set the following variables:
# DELICIOUS_USER = <Your Delicious username>
# DELICIOUS_PASSWORD = <PI:PASSWORD:<PASSWORD>END_PI>
#
# bookmark <url> as <description> - add a url to your delicious feed
# link <url> as <description> - add a url to the robot brain
# link me for <description> - find a link by description
# list bookmarks - get a list of the 15 most recent bookmarks
# list links - List all of the links that are being tracked
# feed me - get the URL to subscribe to your bookmark rss
#
module.exports = (robot) ->
robot.respond /feed me/i, (msg) ->
msg.reply "You can subscribe to the delicious feed at https://delicious.com/v2/rss/#{process.env.DELICIOUS_USER}"
robot.respond /list bookmarks/i, (msg) ->
delicious = new Delicious msg, process.env.DELICIOUS_USER, process.env.DELICIOUS_PASSWORD
delicious.listBookmarks (err, message) ->
if err?
msg.send "#{err}"
else
msg.send "#{message}"
robot.respond /bookmark (http(s?)\:\/\/\S+) as (.+)/i, (msg) ->
delicious = new Delicious msg, process.env.DELICIOUS_USER, process.env.DELICIOUS_PASSWORD
url = msg.match[1]
description = msg.match[3]
bookmark = new Bookmark url, description
delicious.createBookmark bookmark, (err, message) ->
if err?
msg.send "#{err}"
else
msg.send "#{message}"
robot.respond /link (http(s?)\:\/\/\S+) as (.+)/i, (msg) ->
url = msg.match[1]
description = msg.match[3]
bookmark = new Bookmark url, description
link = new Link robot
link.add bookmark, (err, message) ->
if err?
msg.reply "I have a vague memory of hearing about that link sometime in the past."
else
msg.reply "I've stuck that link into my robot brain."
robot.respond /link me for (.+)/i, (msg) ->
description = msg.match[1]
link = new Link robot
link.find description, (err, bookmark) ->
if err?
msg.send "#{err}"
else
msg.send bookmark.url
robot.respond /list links/i, (msg) ->
link = new Link robot
link.list (err, message) ->
if err?
msg.reply "Links? What links? I don't remember any links."
else
msg.reply message
robot.hear /(http(s?)\:\/\/\S+)/i, (msg) ->
href = msg.match[1]
url = new Url robot
url.add href, (err, message) ->
if err?
console.log "#{href} : #{err}"
# Classes
class Url
constructor: (robot) ->
robot.brain.data.urls ?= []
@urls_ = robot.brain.data.urls
all: (url) ->
if url
@urls_.push url
else
@urls_
add: (url, callback) ->
if url in @all()
callback "Url already exists"
else
@all url
callback null, "Url added"
class Bookmark
constructor: (url, description) ->
@url = url
@description = description
encodedUrl: ->
encodeURIComponent @url
encodedDescription: ->
encodeURIComponent @description
class Link
constructor: (robot) ->
robot.brain.data.links ?= []
@links_ = robot.brain.data.links
all: (bookmark) ->
if bookmark
@links_.push bookmark
else
@links_
add: (bookmark, callback) ->
result = []
@all().forEach (entry) ->
if entry
if entry.url is bookmark.url
result.push bookmark
if result.length > 0
callback "Bookmark already exists"
else
@all bookmark
callback null, "Bookmark added"
list: (callback) ->
if @all().length > 0
resp_str = "These are the links I'm remembering:\n\n"
for bookmark in @all()
if bookmark
resp_str += bookmark.description + " (" + bookmark.url + ")\n"
callback null, resp_str
else
callback "No bookmarks exist"
find: (description, callback) ->
result = []
@all().forEach (bookmark) ->
if bookmark && bookmark.description
if RegExp(description, "i").test bookmark.description
result.push bookmark
if result.length > 0
callback null, result[0]
else
callback "No results found"
class Delicious
constructor: (msg, user, password) ->
@msg = msg
@user = user
@password = PI:PASSWORD:<PASSWORD>END_PI
feed_url: ->
"https://delicious.com/v2/rss/#{@user}"
authdata: ->
new Buffer(@user+':'+@password).toString('base64')
createBookmark: (bookmark, callback) ->
api_url = "https://api.del.icio.us/v1/posts/add?" +
"url=#{bookmark.encodedUrl()}" +
"&description=#{bookmark.encodedDescription()}"
@getDelicious api_url, (err, data) ->
if err? or not data?
callback err
else
resultRegexp = /result code="(.+)"/i
result = data.match(resultRegexp)[1]
if result == 'done'
callback null, "Your bookmark was added to delicious."
else
callback "There was a problem adding your bookmark to delicious: #{result}"
listBookmarks: (callback) ->
xml2js = require('xml2js')
api_url = "https://api.del.icio.us/v1/posts/recent"
@getDelicious api_url, (err, data) ->
if err? or not data?
callback err
else
resp_str = "My bookmarks: \n"
(new xml2js.Parser()).parseString data, (err, json)->
for post in json.post
resp_str += post["@"].description + " (" + post["@"].href + ")\n"
callback null, resp_str
getDelicious: (api_url, callback) ->
@msg.http(api_url).
header('Authorization', 'Basic ' + @authdata()).
get() (err, res, body) ->
if res.statusCode is 200
callback null, body
else if err?
callback err
else
callback "There were problems contacting delicious"
|
[
{
"context": "r-chennai.slack.com/services/hooks/slackbot?token=XEmuuFUndDdQEkM3z1FDoNM8&channel=%23invite-requests\",\n \"#{name} (#{em",
"end": 238,
"score": 0.9596923589706421,
"start": 214,
"tag": "KEY",
"value": "XEmuuFUndDdQEkM3z1FDoNM8"
}
] | js/app.coffee | vraravam/elixir-chennai.github.io | 0 | ---
---
$ ->
$("#slack-invite-form").submit (e) ->
name = $("#slack_invite_name").val()
email = $("#slack_invite_email").val()
$.post "https://elixir-chennai.slack.com/services/hooks/slackbot?token=XEmuuFUndDdQEkM3z1FDoNM8&channel=%23invite-requests",
"#{name} (#{email}) would like to join our Slack. Can you please send an invite?",
=>
$(@).hide().html("Invitation Requested. We will get back to you shortly.").fadeIn('slow')
e.preventDefault()
| 112975 | ---
---
$ ->
$("#slack-invite-form").submit (e) ->
name = $("#slack_invite_name").val()
email = $("#slack_invite_email").val()
$.post "https://elixir-chennai.slack.com/services/hooks/slackbot?token=<KEY>&channel=%23invite-requests",
"#{name} (#{email}) would like to join our Slack. Can you please send an invite?",
=>
$(@).hide().html("Invitation Requested. We will get back to you shortly.").fadeIn('slow')
e.preventDefault()
| true | ---
---
$ ->
$("#slack-invite-form").submit (e) ->
name = $("#slack_invite_name").val()
email = $("#slack_invite_email").val()
$.post "https://elixir-chennai.slack.com/services/hooks/slackbot?token=PI:KEY:<KEY>END_PI&channel=%23invite-requests",
"#{name} (#{email}) would like to join our Slack. Can you please send an invite?",
=>
$(@).hide().html("Invitation Requested. We will get back to you shortly.").fadeIn('slow')
e.preventDefault()
|
[
{
"context": "ername The username for the user.\n * @password The password for the user.\n * @cb callback(Error, User)\n###\nUser.statics =\n",
"end": 2154,
"score": 0.8748189806938171,
"start": 2133,
"tag": "PASSWORD",
"value": "password for the user"
},
{
"context": "rch(regex) is -1\n\n newUser = new this(username: username, password: password)\n newUser.saveQ().then ->\n",
"end": 2547,
"score": 0.6705406904220581,
"start": 2539,
"tag": "USERNAME",
"value": "username"
},
{
"context": " newUser = new this(username: username, password: password)\n newUser.saveQ().then ->\n newUser\n\n fin",
"end": 2567,
"score": 0.9761123657226562,
"start": 2559,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "snt -1\n\n setting = new GroupSetting\n user: @_id\n group: group._id\n\n @groupSettings.push s",
"end": 4802,
"score": 0.9991642236709595,
"start": 4798,
"tag": "USERNAME",
"value": "@_id"
},
{
"context": "dexOfEquals(groupId) > -1\n\n login: ->\n token = @generateRandomToken()\n @accessToken.push(token)\n Q.all([to",
"end": 5409,
"score": 0.7098836898803711,
"start": 5394,
"tag": "USERNAME",
"value": "@generateRandom"
}
] | lib/model/user.coffee | ethanmick/fastchat-server | 7 | 'use strict'
#
# FastChat
# 2015
#
mongoose = require('mongoose-q')()
Schema = mongoose.Schema
bcrypt = require('bcrypt')
SALT_WORK_FACTOR = 10
Device = require('./device')
Group = require('./group')
GroupSetting = require './groupSetting'
ObjectId = mongoose.Types.ObjectId
Q = require('q')
fs = require('fs')
uuid = require 'uuid'
Boom = require 'boom'
AWS = require './aws'
Unauthorized = Boom.unauthorized
BUCKET = 'com.fastchat.dev.avatars'
EXTENSION_LOOKUP =
'image/jpeg': 'jpg'
'image/png': 'png'
'image/gif': 'gif'
mimeTypes = ['image/jpeg', 'image/png', 'image/gif']
###
Valid Username Regex
###
regex = /^[a-zA-Z0-9-_.]+$/
###
* User Model
* Stores all the information about the user. Users are required to have a username
* that must be unique. The password is hashed and stored using bcrypt. The accessToken
* is used to authenticate the user on API calls.
*
* Each users knows of it's groups and also knows of any pending invites.
###
User = new Schema
username: {type: String, required: true, unique: true, lowercase: true}
password: {type: String, required: true}
accessToken: [{type: String, default: []}]
groups: [{type: Schema.Types.ObjectId, ref: 'Group'}]
leftGroups: [{type: Schema.Types.ObjectId, ref: 'Group', default: [] }]
devices: [{type: Schema.Types.ObjectId, ref: 'Device', default: [] }]
groupSettings: [{type: Schema.Types.ObjectId, ref: 'GroupSetting', default: []}]
avatar: {type: String, default: null}
###
* BCrypt Middleware to hash the password given before the user is saved.
* This is never called explicitly.
###
User.pre 'save', (next)->
return next() unless @isModified 'password'
bcrypt.genSalt SALT_WORK_FACTOR, (err, salt)=>
return next(err) if err
bcrypt.hash @password, salt, (err, hash)=>
return next(err) if err
@password = hash
next()
###
* Creates a new user from a username and password.
* This will create the user and make a default group for them to chat
* in (which they can rename or invite someone too), and then it will return
* the user.
*
* @username The username for the user.
* @password The password for the user.
* @cb callback(Error, User)
###
User.statics =
register: (username, password)->
throw Boom.badRequest 'Username is required!' unless username
throw Boom.badRequest 'Password is required!' unless password
throw Boom.badRequest 'Invalid username! Only alphanumeric values are allowed, with -, _, and .' if username.search(regex) is -1
newUser = new this(username: username, password: password)
newUser.saveQ().then ->
newUser
findByLowercaseUsername: (username)->
@findOneQ(username: username?.toLowerCase())
.then (user)->
throw Unauthorized() unless user
user
findWithToken: (token, required = yes)->
@findOneQ(accessToken: token).then (user)->
throw Unauthorized() unless user
user
User.methods =
###
* Compares a given password with the user's password.
* Uses bcrypt and hashes the given password.
*
* @candidatePassword The given password to compare
* @cb The callback with the result. cb(error, isMatch)
###
comparePassword: (candidatePassword)->
compare = Q.denodeify(bcrypt.compare)
compare(candidatePassword, @password).then (matched)->
throw new Error('Incorrect username or password') unless matched
matched
###
* Creates the access token for the user.
* Utilizes the crypto library to generate the token, from the docs it:
* 'Generates cryptographically strong pseudo-random data'
* We then change that to a hex string for nice representation.
###
generateRandomToken: ->
require('crypto').randomBytes(48).toString('hex')
###
* Pushes a message to each device this user controls.
* We will want this to be 'smarter' in the future, but this is a good first
* pass. Smarter implementations will understand which device the user used
* last and will send the notification to that device first, wait some time,
* then send a notification to the other devices.
*
* @message The message from the server. Should have 'text' property.
###
push: (group, message, unread, contentAvailable)->
Device.findQ(user: @id).then (devices)->
device.send(group, message, unread, contentAvailable) for device in devices
# Leave a group
leave: (group)->
index = @groups.indexOfEquals group._id
throw Boom.notFound() if index is -1
@groups.splice index, 1
@leftGroups.push group._id
@saveQ()
add: (group)->
index = @leftGroups.indexOfEquals group._id
index2 = @groups.indexOfEquals group._id
throw Boom.badRequest('A user who left cannot be readded!') if index isnt -1 or index2 isnt -1
setting = new GroupSetting
user: @_id
group: group._id
@groupSettings.push setting._id
@groups.push group._id
Q.all([
@saveQ()
setting.saveQ()
]).then => this
###
* A convenience method that will return if the user is in the group
* requested.
*
* @group The group as a String or ObjectId that you want to see if the
* user is in.
###
hasGroup: (group)->
return no unless group
group = group.toString()
groupId = group
try
groupId = new ObjectId group
catch err
return no
@groups.indexOfEquals(groupId) > -1
login: ->
token = @generateRandomToken()
@accessToken.push(token)
Q.all([token, @saveQ()])
logout: (token, all = no)->
tokens = []
if all
tokens = tokens.concat @accessToken
@accessToken.splice 0, @accessToken.length
else
index = @accessToken.indexOf token
if index > -1
@accessToken.splice index, 1
tokens.push token
Device.findQ(accessToken: {$in: tokens}).then (devices)=>
device.logout() for device in devices
@saveQ()
setAvatar: (name)->
@avatar = name
@saveQ()
uploadAvatar: (file)->
deferred = Q.defer()
throw new Boom.badRequest('No files were found in the upload!') unless file
options =
'Content-Type': file.headers['content-type']
'Cache-Control': 'max-age=604800'
'x-amz-acl': 'public-read'
'Content-Length': file.bytes
aws = new AWS(BUCKET)
aws.upload fs.createReadStream(file.path), uuid.v4(), options, (err, result)=>
return deferred.reject(err) if err
deferred.resolve(@setAvatar(result.req.path.replace(/^.*[\\\/]/, '')))
deferred.promise
getAvatar: ->
throw Boom.notFound() unless @avatar
deferred = Q.defer()
data = ''
aws = new AWS(BUCKET)
aws.get(@avatar).on 'response', (res)->
if res.statusCode < 200 or res.statusCode > 300
deferred.reject new Error('There was an error fetching your image!')
res.setEncoding('binary')
res.on 'data', (chunk)->
data += chunk
res.on 'end', ->
deferred.resolve(['image/jpeg', data])
res.on 'error', deferred.reject
.end()
deferred.promise
module.exports = mongoose.model 'User', User
| 130672 | 'use strict'
#
# FastChat
# 2015
#
mongoose = require('mongoose-q')()
Schema = mongoose.Schema
bcrypt = require('bcrypt')
SALT_WORK_FACTOR = 10
Device = require('./device')
Group = require('./group')
GroupSetting = require './groupSetting'
ObjectId = mongoose.Types.ObjectId
Q = require('q')
fs = require('fs')
uuid = require 'uuid'
Boom = require 'boom'
AWS = require './aws'
Unauthorized = Boom.unauthorized
BUCKET = 'com.fastchat.dev.avatars'
EXTENSION_LOOKUP =
'image/jpeg': 'jpg'
'image/png': 'png'
'image/gif': 'gif'
mimeTypes = ['image/jpeg', 'image/png', 'image/gif']
###
Valid Username Regex
###
regex = /^[a-zA-Z0-9-_.]+$/
###
* User Model
* Stores all the information about the user. Users are required to have a username
* that must be unique. The password is hashed and stored using bcrypt. The accessToken
* is used to authenticate the user on API calls.
*
* Each users knows of it's groups and also knows of any pending invites.
###
User = new Schema
username: {type: String, required: true, unique: true, lowercase: true}
password: {type: String, required: true}
accessToken: [{type: String, default: []}]
groups: [{type: Schema.Types.ObjectId, ref: 'Group'}]
leftGroups: [{type: Schema.Types.ObjectId, ref: 'Group', default: [] }]
devices: [{type: Schema.Types.ObjectId, ref: 'Device', default: [] }]
groupSettings: [{type: Schema.Types.ObjectId, ref: 'GroupSetting', default: []}]
avatar: {type: String, default: null}
###
* BCrypt Middleware to hash the password given before the user is saved.
* This is never called explicitly.
###
User.pre 'save', (next)->
return next() unless @isModified 'password'
bcrypt.genSalt SALT_WORK_FACTOR, (err, salt)=>
return next(err) if err
bcrypt.hash @password, salt, (err, hash)=>
return next(err) if err
@password = hash
next()
###
* Creates a new user from a username and password.
* This will create the user and make a default group for them to chat
* in (which they can rename or invite someone too), and then it will return
* the user.
*
* @username The username for the user.
* @password The <PASSWORD>.
* @cb callback(Error, User)
###
User.statics =
register: (username, password)->
throw Boom.badRequest 'Username is required!' unless username
throw Boom.badRequest 'Password is required!' unless password
throw Boom.badRequest 'Invalid username! Only alphanumeric values are allowed, with -, _, and .' if username.search(regex) is -1
newUser = new this(username: username, password: <PASSWORD>)
newUser.saveQ().then ->
newUser
findByLowercaseUsername: (username)->
@findOneQ(username: username?.toLowerCase())
.then (user)->
throw Unauthorized() unless user
user
findWithToken: (token, required = yes)->
@findOneQ(accessToken: token).then (user)->
throw Unauthorized() unless user
user
User.methods =
###
* Compares a given password with the user's password.
* Uses bcrypt and hashes the given password.
*
* @candidatePassword The given password to compare
* @cb The callback with the result. cb(error, isMatch)
###
comparePassword: (candidatePassword)->
compare = Q.denodeify(bcrypt.compare)
compare(candidatePassword, @password).then (matched)->
throw new Error('Incorrect username or password') unless matched
matched
###
* Creates the access token for the user.
* Utilizes the crypto library to generate the token, from the docs it:
* 'Generates cryptographically strong pseudo-random data'
* We then change that to a hex string for nice representation.
###
generateRandomToken: ->
require('crypto').randomBytes(48).toString('hex')
###
* Pushes a message to each device this user controls.
* We will want this to be 'smarter' in the future, but this is a good first
* pass. Smarter implementations will understand which device the user used
* last and will send the notification to that device first, wait some time,
* then send a notification to the other devices.
*
* @message The message from the server. Should have 'text' property.
###
push: (group, message, unread, contentAvailable)->
Device.findQ(user: @id).then (devices)->
device.send(group, message, unread, contentAvailable) for device in devices
# Leave a group
leave: (group)->
index = @groups.indexOfEquals group._id
throw Boom.notFound() if index is -1
@groups.splice index, 1
@leftGroups.push group._id
@saveQ()
add: (group)->
index = @leftGroups.indexOfEquals group._id
index2 = @groups.indexOfEquals group._id
throw Boom.badRequest('A user who left cannot be readded!') if index isnt -1 or index2 isnt -1
setting = new GroupSetting
user: @_id
group: group._id
@groupSettings.push setting._id
@groups.push group._id
Q.all([
@saveQ()
setting.saveQ()
]).then => this
###
* A convenience method that will return if the user is in the group
* requested.
*
* @group The group as a String or ObjectId that you want to see if the
* user is in.
###
hasGroup: (group)->
return no unless group
group = group.toString()
groupId = group
try
groupId = new ObjectId group
catch err
return no
@groups.indexOfEquals(groupId) > -1
login: ->
token = @generateRandomToken()
@accessToken.push(token)
Q.all([token, @saveQ()])
logout: (token, all = no)->
tokens = []
if all
tokens = tokens.concat @accessToken
@accessToken.splice 0, @accessToken.length
else
index = @accessToken.indexOf token
if index > -1
@accessToken.splice index, 1
tokens.push token
Device.findQ(accessToken: {$in: tokens}).then (devices)=>
device.logout() for device in devices
@saveQ()
setAvatar: (name)->
@avatar = name
@saveQ()
uploadAvatar: (file)->
deferred = Q.defer()
throw new Boom.badRequest('No files were found in the upload!') unless file
options =
'Content-Type': file.headers['content-type']
'Cache-Control': 'max-age=604800'
'x-amz-acl': 'public-read'
'Content-Length': file.bytes
aws = new AWS(BUCKET)
aws.upload fs.createReadStream(file.path), uuid.v4(), options, (err, result)=>
return deferred.reject(err) if err
deferred.resolve(@setAvatar(result.req.path.replace(/^.*[\\\/]/, '')))
deferred.promise
getAvatar: ->
throw Boom.notFound() unless @avatar
deferred = Q.defer()
data = ''
aws = new AWS(BUCKET)
aws.get(@avatar).on 'response', (res)->
if res.statusCode < 200 or res.statusCode > 300
deferred.reject new Error('There was an error fetching your image!')
res.setEncoding('binary')
res.on 'data', (chunk)->
data += chunk
res.on 'end', ->
deferred.resolve(['image/jpeg', data])
res.on 'error', deferred.reject
.end()
deferred.promise
module.exports = mongoose.model 'User', User
| true | 'use strict'
#
# FastChat
# 2015
#
mongoose = require('mongoose-q')()
Schema = mongoose.Schema
bcrypt = require('bcrypt')
SALT_WORK_FACTOR = 10
Device = require('./device')
Group = require('./group')
GroupSetting = require './groupSetting'
ObjectId = mongoose.Types.ObjectId
Q = require('q')
fs = require('fs')
uuid = require 'uuid'
Boom = require 'boom'
AWS = require './aws'
Unauthorized = Boom.unauthorized
BUCKET = 'com.fastchat.dev.avatars'
EXTENSION_LOOKUP =
'image/jpeg': 'jpg'
'image/png': 'png'
'image/gif': 'gif'
mimeTypes = ['image/jpeg', 'image/png', 'image/gif']
###
Valid Username Regex
###
regex = /^[a-zA-Z0-9-_.]+$/
###
* User Model
* Stores all the information about the user. Users are required to have a username
* that must be unique. The password is hashed and stored using bcrypt. The accessToken
* is used to authenticate the user on API calls.
*
* Each users knows of it's groups and also knows of any pending invites.
###
User = new Schema
username: {type: String, required: true, unique: true, lowercase: true}
password: {type: String, required: true}
accessToken: [{type: String, default: []}]
groups: [{type: Schema.Types.ObjectId, ref: 'Group'}]
leftGroups: [{type: Schema.Types.ObjectId, ref: 'Group', default: [] }]
devices: [{type: Schema.Types.ObjectId, ref: 'Device', default: [] }]
groupSettings: [{type: Schema.Types.ObjectId, ref: 'GroupSetting', default: []}]
avatar: {type: String, default: null}
###
* BCrypt Middleware to hash the password given before the user is saved.
* This is never called explicitly.
###
User.pre 'save', (next)->
return next() unless @isModified 'password'
bcrypt.genSalt SALT_WORK_FACTOR, (err, salt)=>
return next(err) if err
bcrypt.hash @password, salt, (err, hash)=>
return next(err) if err
@password = hash
next()
###
* Creates a new user from a username and password.
* This will create the user and make a default group for them to chat
* in (which they can rename or invite someone too), and then it will return
* the user.
*
* @username The username for the user.
* @password The PI:PASSWORD:<PASSWORD>END_PI.
* @cb callback(Error, User)
###
User.statics =
register: (username, password)->
throw Boom.badRequest 'Username is required!' unless username
throw Boom.badRequest 'Password is required!' unless password
throw Boom.badRequest 'Invalid username! Only alphanumeric values are allowed, with -, _, and .' if username.search(regex) is -1
newUser = new this(username: username, password: PI:PASSWORD:<PASSWORD>END_PI)
newUser.saveQ().then ->
newUser
findByLowercaseUsername: (username)->
@findOneQ(username: username?.toLowerCase())
.then (user)->
throw Unauthorized() unless user
user
findWithToken: (token, required = yes)->
@findOneQ(accessToken: token).then (user)->
throw Unauthorized() unless user
user
User.methods =
###
* Compares a given password with the user's password.
* Uses bcrypt and hashes the given password.
*
* @candidatePassword The given password to compare
* @cb The callback with the result. cb(error, isMatch)
###
comparePassword: (candidatePassword)->
compare = Q.denodeify(bcrypt.compare)
compare(candidatePassword, @password).then (matched)->
throw new Error('Incorrect username or password') unless matched
matched
###
* Creates the access token for the user.
* Utilizes the crypto library to generate the token, from the docs it:
* 'Generates cryptographically strong pseudo-random data'
* We then change that to a hex string for nice representation.
###
generateRandomToken: ->
require('crypto').randomBytes(48).toString('hex')
###
* Pushes a message to each device this user controls.
* We will want this to be 'smarter' in the future, but this is a good first
* pass. Smarter implementations will understand which device the user used
* last and will send the notification to that device first, wait some time,
* then send a notification to the other devices.
*
* @message The message from the server. Should have 'text' property.
###
push: (group, message, unread, contentAvailable)->
Device.findQ(user: @id).then (devices)->
device.send(group, message, unread, contentAvailable) for device in devices
# Leave a group
leave: (group)->
index = @groups.indexOfEquals group._id
throw Boom.notFound() if index is -1
@groups.splice index, 1
@leftGroups.push group._id
@saveQ()
add: (group)->
index = @leftGroups.indexOfEquals group._id
index2 = @groups.indexOfEquals group._id
throw Boom.badRequest('A user who left cannot be readded!') if index isnt -1 or index2 isnt -1
setting = new GroupSetting
user: @_id
group: group._id
@groupSettings.push setting._id
@groups.push group._id
Q.all([
@saveQ()
setting.saveQ()
]).then => this
###
* A convenience method that will return if the user is in the group
* requested.
*
* @group The group as a String or ObjectId that you want to see if the
* user is in.
###
hasGroup: (group)->
return no unless group
group = group.toString()
groupId = group
try
groupId = new ObjectId group
catch err
return no
@groups.indexOfEquals(groupId) > -1
login: ->
token = @generateRandomToken()
@accessToken.push(token)
Q.all([token, @saveQ()])
logout: (token, all = no)->
tokens = []
if all
tokens = tokens.concat @accessToken
@accessToken.splice 0, @accessToken.length
else
index = @accessToken.indexOf token
if index > -1
@accessToken.splice index, 1
tokens.push token
Device.findQ(accessToken: {$in: tokens}).then (devices)=>
device.logout() for device in devices
@saveQ()
setAvatar: (name)->
@avatar = name
@saveQ()
uploadAvatar: (file)->
deferred = Q.defer()
throw new Boom.badRequest('No files were found in the upload!') unless file
options =
'Content-Type': file.headers['content-type']
'Cache-Control': 'max-age=604800'
'x-amz-acl': 'public-read'
'Content-Length': file.bytes
aws = new AWS(BUCKET)
aws.upload fs.createReadStream(file.path), uuid.v4(), options, (err, result)=>
return deferred.reject(err) if err
deferred.resolve(@setAvatar(result.req.path.replace(/^.*[\\\/]/, '')))
deferred.promise
getAvatar: ->
throw Boom.notFound() unless @avatar
deferred = Q.defer()
data = ''
aws = new AWS(BUCKET)
aws.get(@avatar).on 'response', (res)->
if res.statusCode < 200 or res.statusCode > 300
deferred.reject new Error('There was an error fetching your image!')
res.setEncoding('binary')
res.on 'data', (chunk)->
data += chunk
res.on 'end', ->
deferred.resolve(['image/jpeg', data])
res.on 'error', deferred.reject
.end()
deferred.promise
module.exports = mongoose.model 'User', User
|
[
{
"context": "ew Rules.Object\n email: emailRule\n password: passwordRule\n firstName: firstNameRule\n lastName: lastNa",
"end": 216,
"score": 0.9901385307312012,
"start": 204,
"tag": "PASSWORD",
"value": "passwordRule"
}
] | example/validatorsSrc/account.coffee | dbartholomae/node-validation-codes | 0 | define ['lib/ValidatorRules', './email', './password', './firstName', './lastName'],
(Rules, emailRule, passwordRule, firstNameRule, lastNameRule) ->
new Rules.Object
email: emailRule
password: passwordRule
firstName: firstNameRule
lastName: lastNameRule | 124346 | define ['lib/ValidatorRules', './email', './password', './firstName', './lastName'],
(Rules, emailRule, passwordRule, firstNameRule, lastNameRule) ->
new Rules.Object
email: emailRule
password: <PASSWORD>
firstName: firstNameRule
lastName: lastNameRule | true | define ['lib/ValidatorRules', './email', './password', './firstName', './lastName'],
(Rules, emailRule, passwordRule, firstNameRule, lastNameRule) ->
new Rules.Object
email: emailRule
password: PI:PASSWORD:<PASSWORD>END_PI
firstName: firstNameRule
lastName: lastNameRule |
[
{
"context": ", 'myService')\n expect(password).to.equal '12345'\n expectedCmd = \"/usr/bin/security find-ge",
"end": 552,
"score": 0.9974706768989563,
"start": 547,
"tag": "PASSWORD",
"value": "12345"
}
] | test/keychain-sync_spec.coffee | elentok/keychain-sync | 1 | chai = require 'chai'
expect = chai.expect
chai.use require('sinon-chai')
sinon = require 'sinon'
execSync =
stdout: sinon.stub()
sandbox = require 'sandboxed-module'
keychainSync = sandbox.require '../lib/keychain-sync',
requires:
execSync: execSync
describe "keychainSync", ->
describe "#getPassword", ->
describe "when the password exists", ->
it "returns the password", ->
execSync.stdout.returns "12345\n"
password = keychainSync.getPassword('myAccount', 'myService')
expect(password).to.equal '12345'
expectedCmd = "/usr/bin/security find-generic-password -a myAccount -s myService -w"
expect(execSync.stdout).to.have.been.calledWith(expectedCmd)
describe "when it doesn't exist", ->
it "returns null", ->
execSync.stdout.returns ""
password = keychainSync.getPassword('myAccount', 'myService')
expect(password).to.equal null
describe "#setPassword", ->
it "saves the password", ->
keychainSync.setPassword('myAccount', 'myService', 'myPassword')
expectedCmd = "/usr/bin/security add-generic-password -a myAccount -s myService -w myPassword"
expect(execSync.stdout).to.have.been.calledWith(expectedCmd)
| 86881 | chai = require 'chai'
expect = chai.expect
chai.use require('sinon-chai')
sinon = require 'sinon'
execSync =
stdout: sinon.stub()
sandbox = require 'sandboxed-module'
keychainSync = sandbox.require '../lib/keychain-sync',
requires:
execSync: execSync
describe "keychainSync", ->
describe "#getPassword", ->
describe "when the password exists", ->
it "returns the password", ->
execSync.stdout.returns "12345\n"
password = keychainSync.getPassword('myAccount', 'myService')
expect(password).to.equal '<PASSWORD>'
expectedCmd = "/usr/bin/security find-generic-password -a myAccount -s myService -w"
expect(execSync.stdout).to.have.been.calledWith(expectedCmd)
describe "when it doesn't exist", ->
it "returns null", ->
execSync.stdout.returns ""
password = keychainSync.getPassword('myAccount', 'myService')
expect(password).to.equal null
describe "#setPassword", ->
it "saves the password", ->
keychainSync.setPassword('myAccount', 'myService', 'myPassword')
expectedCmd = "/usr/bin/security add-generic-password -a myAccount -s myService -w myPassword"
expect(execSync.stdout).to.have.been.calledWith(expectedCmd)
| true | chai = require 'chai'
expect = chai.expect
chai.use require('sinon-chai')
sinon = require 'sinon'
execSync =
stdout: sinon.stub()
sandbox = require 'sandboxed-module'
keychainSync = sandbox.require '../lib/keychain-sync',
requires:
execSync: execSync
describe "keychainSync", ->
describe "#getPassword", ->
describe "when the password exists", ->
it "returns the password", ->
execSync.stdout.returns "12345\n"
password = keychainSync.getPassword('myAccount', 'myService')
expect(password).to.equal 'PI:PASSWORD:<PASSWORD>END_PI'
expectedCmd = "/usr/bin/security find-generic-password -a myAccount -s myService -w"
expect(execSync.stdout).to.have.been.calledWith(expectedCmd)
describe "when it doesn't exist", ->
it "returns null", ->
execSync.stdout.returns ""
password = keychainSync.getPassword('myAccount', 'myService')
expect(password).to.equal null
describe "#setPassword", ->
it "saves the password", ->
keychainSync.setPassword('myAccount', 'myService', 'myPassword')
expectedCmd = "/usr/bin/security add-generic-password -a myAccount -s myService -w myPassword"
expect(execSync.stdout).to.have.been.calledWith(expectedCmd)
|
[
{
"context": ".html\n# [gc]: http:gc.html\n\n# ---\n#\n# **(c) 2012 [Reg Braithwaite](http://braythwayt.com)** ([@raganwald](http://tw",
"end": 2977,
"score": 0.9995414614677429,
"start": 2962,
"tag": "NAME",
"value": "Reg Braithwaite"
},
{
"context": "2012 [Reg Braithwaite](http://braythwayt.com)** ([@raganwald](http://twitter.com/raganwald))\n#\n# Cafe au Life ",
"end": 3016,
"score": 0.9996544718742371,
"start": 3006,
"tag": "USERNAME",
"value": "@raganwald"
},
{
"context": "raythwayt.com)** ([@raganwald](http://twitter.com/raganwald))\n#\n# Cafe au Life is freely distributable under ",
"end": 3046,
"score": 0.9994774460792542,
"start": 3037,
"tag": "USERNAME",
"value": "raganwald"
},
{
"context": " [Docco][docco].\n#\n# [source]: https://github.com/raganwald/cafeaulife/blob/master/lib\n# [docco]: http://jash",
"end": 3322,
"score": 0.8852874040603638,
"start": 3313,
"tag": "USERNAME",
"value": "raganwald"
}
] | lib/cache.coffee | raganwald/recursiveuniverse | 4 | # This module is part of [recursiveuniver.se](http://recursiveuniver.se).
#
# ## Cache Module
#
# HashLife uses extensive [canonicalization][canonical] to optimize the storage of very large patterns with repetitive
# components. The Cache Module implements a very naive hash-table for canoncial representations of squares.
#
# [cache]: http:cache.html
# [canonical]: https://en.wikipedia.org/wiki/Canonicalization
# ### Canoncialization: The "Hash" in HashLife
#
# HashLife gets a tremendous speed-up by storing and reusing squares in a giant cache.
# Any result, at any scale, that has been computed before is reused. This is extremely
# efficient when dealing with patterns that contain a great deal of redundancy, such as
# the kinds of patterns constructed for the purpose of emulating circuits or machines in Life.
#
# Once Cafe au Life has calculated the results for the 65K possible four-by-four
# squares, the rules are no longer applied to any generation: Any pattern of any size is
# recursively computed terminating in a four-by-four square that has already been computed and cached.
#
# This module provides a `mixInto` function so that it retroactively modify existing classes.
# ### Baseline Setup
_ = require('underscore')
YouAreDaChef = require('YouAreDaChef').YouAreDaChef
exports ?= window or this
# ### Implementing the cache
#
# The cache is organized into an array of 'buckets', each of which is a hash from a simple key
# to a cached square. The buckets are organized by level of the square. This allows some simple
# ordering later when we start fooling around with garbage collection: It's easy to find the
# largest squares that aren't in use.
exports.mixInto = ({Square, Cell}) ->
counter = 0
YouAreDaChef(Cell)
.after 'initialize', ->
@id = (counter += 1)
YouAreDaChef(Square)
.after 'initialize', ->
@id = (counter += 1)
_.extend Square,
cache:
buckets: []
clear: ->
@buckets = []
length: 0
find: ({nw, ne, se, sw}) ->
console.trace() unless nw?.level?
(@buckets[nw.level + 1] ||= {})["#{nw.id}-#{ne.id}-#{se.id}-#{sw.id}"]
add: (square) ->
@length += 1
{nw, ne, se, sw} = square
(@buckets[nw.level + 1] ||= {})["#{nw.id}-#{ne.id}-#{se.id}-#{sw.id}"] = square
canonicalize: (quadrants) ->
found = @cache.find(quadrants)
if found
found
else
@cache.add(new Square.RecursivelyComputable(quadrants))
# ## The first time through
#
# If this is your first time through the code, and you've already read the [Rules][rules] and [Future][future] modules, you can look at the
# [Garbage Collection][gc] and [API][api] modules next.
#
# [menagerie]: http:menagerie.html
# [api]: http:api.html
# [future]: http:future.html
# [cache]: http:cache.html
# [canonical]: https://en.wikipedia.org/wiki/Canonicalization
# [rules]: http:rules.html
# [gc]: http:gc.html
# ---
#
# **(c) 2012 [Reg Braithwaite](http://braythwayt.com)** ([@raganwald](http://twitter.com/raganwald))
#
# Cafe au Life is freely distributable under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
#
# The annotated source code was generated directly from the [original source][source] using [Docco][docco].
#
# [source]: https://github.com/raganwald/cafeaulife/blob/master/lib
# [docco]: http://jashkenas.github.com/docco/ | 115819 | # This module is part of [recursiveuniver.se](http://recursiveuniver.se).
#
# ## Cache Module
#
# HashLife uses extensive [canonicalization][canonical] to optimize the storage of very large patterns with repetitive
# components. The Cache Module implements a very naive hash-table for canoncial representations of squares.
#
# [cache]: http:cache.html
# [canonical]: https://en.wikipedia.org/wiki/Canonicalization
# ### Canoncialization: The "Hash" in HashLife
#
# HashLife gets a tremendous speed-up by storing and reusing squares in a giant cache.
# Any result, at any scale, that has been computed before is reused. This is extremely
# efficient when dealing with patterns that contain a great deal of redundancy, such as
# the kinds of patterns constructed for the purpose of emulating circuits or machines in Life.
#
# Once Cafe au Life has calculated the results for the 65K possible four-by-four
# squares, the rules are no longer applied to any generation: Any pattern of any size is
# recursively computed terminating in a four-by-four square that has already been computed and cached.
#
# This module provides a `mixInto` function so that it retroactively modify existing classes.
# ### Baseline Setup
_ = require('underscore')
YouAreDaChef = require('YouAreDaChef').YouAreDaChef
exports ?= window or this
# ### Implementing the cache
#
# The cache is organized into an array of 'buckets', each of which is a hash from a simple key
# to a cached square. The buckets are organized by level of the square. This allows some simple
# ordering later when we start fooling around with garbage collection: It's easy to find the
# largest squares that aren't in use.
exports.mixInto = ({Square, Cell}) ->
counter = 0
YouAreDaChef(Cell)
.after 'initialize', ->
@id = (counter += 1)
YouAreDaChef(Square)
.after 'initialize', ->
@id = (counter += 1)
_.extend Square,
cache:
buckets: []
clear: ->
@buckets = []
length: 0
find: ({nw, ne, se, sw}) ->
console.trace() unless nw?.level?
(@buckets[nw.level + 1] ||= {})["#{nw.id}-#{ne.id}-#{se.id}-#{sw.id}"]
add: (square) ->
@length += 1
{nw, ne, se, sw} = square
(@buckets[nw.level + 1] ||= {})["#{nw.id}-#{ne.id}-#{se.id}-#{sw.id}"] = square
canonicalize: (quadrants) ->
found = @cache.find(quadrants)
if found
found
else
@cache.add(new Square.RecursivelyComputable(quadrants))
# ## The first time through
#
# If this is your first time through the code, and you've already read the [Rules][rules] and [Future][future] modules, you can look at the
# [Garbage Collection][gc] and [API][api] modules next.
#
# [menagerie]: http:menagerie.html
# [api]: http:api.html
# [future]: http:future.html
# [cache]: http:cache.html
# [canonical]: https://en.wikipedia.org/wiki/Canonicalization
# [rules]: http:rules.html
# [gc]: http:gc.html
# ---
#
# **(c) 2012 [<NAME>](http://braythwayt.com)** ([@raganwald](http://twitter.com/raganwald))
#
# Cafe au Life is freely distributable under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
#
# The annotated source code was generated directly from the [original source][source] using [Docco][docco].
#
# [source]: https://github.com/raganwald/cafeaulife/blob/master/lib
# [docco]: http://jashkenas.github.com/docco/ | true | # This module is part of [recursiveuniver.se](http://recursiveuniver.se).
#
# ## Cache Module
#
# HashLife uses extensive [canonicalization][canonical] to optimize the storage of very large patterns with repetitive
# components. The Cache Module implements a very naive hash-table for canoncial representations of squares.
#
# [cache]: http:cache.html
# [canonical]: https://en.wikipedia.org/wiki/Canonicalization
# ### Canoncialization: The "Hash" in HashLife
#
# HashLife gets a tremendous speed-up by storing and reusing squares in a giant cache.
# Any result, at any scale, that has been computed before is reused. This is extremely
# efficient when dealing with patterns that contain a great deal of redundancy, such as
# the kinds of patterns constructed for the purpose of emulating circuits or machines in Life.
#
# Once Cafe au Life has calculated the results for the 65K possible four-by-four
# squares, the rules are no longer applied to any generation: Any pattern of any size is
# recursively computed terminating in a four-by-four square that has already been computed and cached.
#
# This module provides a `mixInto` function so that it retroactively modify existing classes.
# ### Baseline Setup
_ = require('underscore')
YouAreDaChef = require('YouAreDaChef').YouAreDaChef
exports ?= window or this
# ### Implementing the cache
#
# The cache is organized into an array of 'buckets', each of which is a hash from a simple key
# to a cached square. The buckets are organized by level of the square. This allows some simple
# ordering later when we start fooling around with garbage collection: It's easy to find the
# largest squares that aren't in use.
exports.mixInto = ({Square, Cell}) ->
counter = 0
YouAreDaChef(Cell)
.after 'initialize', ->
@id = (counter += 1)
YouAreDaChef(Square)
.after 'initialize', ->
@id = (counter += 1)
_.extend Square,
cache:
buckets: []
clear: ->
@buckets = []
length: 0
find: ({nw, ne, se, sw}) ->
console.trace() unless nw?.level?
(@buckets[nw.level + 1] ||= {})["#{nw.id}-#{ne.id}-#{se.id}-#{sw.id}"]
add: (square) ->
@length += 1
{nw, ne, se, sw} = square
(@buckets[nw.level + 1] ||= {})["#{nw.id}-#{ne.id}-#{se.id}-#{sw.id}"] = square
canonicalize: (quadrants) ->
found = @cache.find(quadrants)
if found
found
else
@cache.add(new Square.RecursivelyComputable(quadrants))
# ## The first time through
#
# If this is your first time through the code, and you've already read the [Rules][rules] and [Future][future] modules, you can look at the
# [Garbage Collection][gc] and [API][api] modules next.
#
# [menagerie]: http:menagerie.html
# [api]: http:api.html
# [future]: http:future.html
# [cache]: http:cache.html
# [canonical]: https://en.wikipedia.org/wiki/Canonicalization
# [rules]: http:rules.html
# [gc]: http:gc.html
# ---
#
# **(c) 2012 [PI:NAME:<NAME>END_PI](http://braythwayt.com)** ([@raganwald](http://twitter.com/raganwald))
#
# Cafe au Life is freely distributable under the terms of the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
#
# The annotated source code was generated directly from the [original source][source] using [Docco][docco].
#
# [source]: https://github.com/raganwald/cafeaulife/blob/master/lib
# [docco]: http://jashkenas.github.com/docco/ |
[
{
"context": "grammar/\n\n'scopeName': 'source.kumachan'\n'name': 'KumaChan'\n'comment': 'KumaChan language'\n'type': 'tree-sit",
"end": 195,
"score": 0.5679764747619629,
"start": 187,
"tag": "NAME",
"value": "KumaChan"
}
] | grammars/kumachan.cson | mizusato/language-kumachan | 1 | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
'scopeName': 'source.kumachan'
'name': 'KumaChan'
'comment': 'KumaChan language'
'type': 'tree-sitter'
'parser': 'tree-sitter-kumachan'
'fileTypes': [
'km'
]
'scopes':
'''
"import",
"from",
"type",
"impl",
"enum",
"interface",
"native",
"weak",
"protected",
"opaque",
"export",
"function",
"const",
"method",
"entry",
"asset",
"in",
"out",
"=",
"<",
">",
"default",
"end",
"rec",
"parallel",
"if",
"elif",
"else",
"switch",
"select",
"case",
"let",
".",
";",
":",
":=",
cps_symbol
''': 'keyword.control'
'"(", ")", "[", "]", "{", "}", "&", "=>", "|"': 'entity.name.tag'
'comment': 'comment.block'
'string_text': 'string.quoted.single'
'formatter_text': 'string.quoted.double'
'int': 'constant.numeric'
'float': 'constant.numeric'
'char': 'constant.character'
'asset > name': 'constant.other'
'decl_func > name': 'entity.name.function'
'decl_const > name': 'constant.other'
'decl_method > name': 'entity.name.tag'
'decl_method > receiver': 'entity.name.type'
'decl_type > name': 'entity.name.type'
'type_decl_ref': 'entity.name.type'
'type_ref > name': 'entity.name.type'
'type_ref > module_prefix': 'entity.name.type'
'type_param > name': 'entity.name.type'
'branch > name': 'entity.name.type'
'multi_branch_key > name': 'entity.name.type'
'field > name': 'entity.name.tag'
'default_item > name': 'entity.name.tag'
'pair > name': 'entity.name.tag'
'pipe_get > name': 'entity.name.tag'
'pipe_interior > name': 'entity.name.tag'
'callee > expr > term > inline_ref > name': 'entity.name.function'
'callee > expr > term > inline_ref > module_prefix': 'entity.name.function'
'operator > expr > term > inline_ref > name': 'entity.name.function'
'operator > expr > term > inline_ref > module_prefix': 'entity.name.function'
'folds': [
{
'type': 'comment'
}
{
'type': 'decl_type'
}
{
'type': 'decl_func'
}
{
'type': 'decl_const'
}
{
'type': 'decl_method'
}
{
'type': 'entry'
}
{
'type': 'lambda'
}
{
'type': 'block'
}
{
'type': 'if'
}
{
'type': 'switch'
}
{
'type': 'select'
}
{
'type': 'list'
}
{
'type': 'tuple'
}
{
'type': 'record'
}
]
| 211101 | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
'scopeName': 'source.kumachan'
'name': '<NAME>'
'comment': 'KumaChan language'
'type': 'tree-sitter'
'parser': 'tree-sitter-kumachan'
'fileTypes': [
'km'
]
'scopes':
'''
"import",
"from",
"type",
"impl",
"enum",
"interface",
"native",
"weak",
"protected",
"opaque",
"export",
"function",
"const",
"method",
"entry",
"asset",
"in",
"out",
"=",
"<",
">",
"default",
"end",
"rec",
"parallel",
"if",
"elif",
"else",
"switch",
"select",
"case",
"let",
".",
";",
":",
":=",
cps_symbol
''': 'keyword.control'
'"(", ")", "[", "]", "{", "}", "&", "=>", "|"': 'entity.name.tag'
'comment': 'comment.block'
'string_text': 'string.quoted.single'
'formatter_text': 'string.quoted.double'
'int': 'constant.numeric'
'float': 'constant.numeric'
'char': 'constant.character'
'asset > name': 'constant.other'
'decl_func > name': 'entity.name.function'
'decl_const > name': 'constant.other'
'decl_method > name': 'entity.name.tag'
'decl_method > receiver': 'entity.name.type'
'decl_type > name': 'entity.name.type'
'type_decl_ref': 'entity.name.type'
'type_ref > name': 'entity.name.type'
'type_ref > module_prefix': 'entity.name.type'
'type_param > name': 'entity.name.type'
'branch > name': 'entity.name.type'
'multi_branch_key > name': 'entity.name.type'
'field > name': 'entity.name.tag'
'default_item > name': 'entity.name.tag'
'pair > name': 'entity.name.tag'
'pipe_get > name': 'entity.name.tag'
'pipe_interior > name': 'entity.name.tag'
'callee > expr > term > inline_ref > name': 'entity.name.function'
'callee > expr > term > inline_ref > module_prefix': 'entity.name.function'
'operator > expr > term > inline_ref > name': 'entity.name.function'
'operator > expr > term > inline_ref > module_prefix': 'entity.name.function'
'folds': [
{
'type': 'comment'
}
{
'type': 'decl_type'
}
{
'type': 'decl_func'
}
{
'type': 'decl_const'
}
{
'type': 'decl_method'
}
{
'type': 'entry'
}
{
'type': 'lambda'
}
{
'type': 'block'
}
{
'type': 'if'
}
{
'type': 'switch'
}
{
'type': 'select'
}
{
'type': 'list'
}
{
'type': 'tuple'
}
{
'type': 'record'
}
]
| true | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
'scopeName': 'source.kumachan'
'name': 'PI:NAME:<NAME>END_PI'
'comment': 'KumaChan language'
'type': 'tree-sitter'
'parser': 'tree-sitter-kumachan'
'fileTypes': [
'km'
]
'scopes':
'''
"import",
"from",
"type",
"impl",
"enum",
"interface",
"native",
"weak",
"protected",
"opaque",
"export",
"function",
"const",
"method",
"entry",
"asset",
"in",
"out",
"=",
"<",
">",
"default",
"end",
"rec",
"parallel",
"if",
"elif",
"else",
"switch",
"select",
"case",
"let",
".",
";",
":",
":=",
cps_symbol
''': 'keyword.control'
'"(", ")", "[", "]", "{", "}", "&", "=>", "|"': 'entity.name.tag'
'comment': 'comment.block'
'string_text': 'string.quoted.single'
'formatter_text': 'string.quoted.double'
'int': 'constant.numeric'
'float': 'constant.numeric'
'char': 'constant.character'
'asset > name': 'constant.other'
'decl_func > name': 'entity.name.function'
'decl_const > name': 'constant.other'
'decl_method > name': 'entity.name.tag'
'decl_method > receiver': 'entity.name.type'
'decl_type > name': 'entity.name.type'
'type_decl_ref': 'entity.name.type'
'type_ref > name': 'entity.name.type'
'type_ref > module_prefix': 'entity.name.type'
'type_param > name': 'entity.name.type'
'branch > name': 'entity.name.type'
'multi_branch_key > name': 'entity.name.type'
'field > name': 'entity.name.tag'
'default_item > name': 'entity.name.tag'
'pair > name': 'entity.name.tag'
'pipe_get > name': 'entity.name.tag'
'pipe_interior > name': 'entity.name.tag'
'callee > expr > term > inline_ref > name': 'entity.name.function'
'callee > expr > term > inline_ref > module_prefix': 'entity.name.function'
'operator > expr > term > inline_ref > name': 'entity.name.function'
'operator > expr > term > inline_ref > module_prefix': 'entity.name.function'
'folds': [
{
'type': 'comment'
}
{
'type': 'decl_type'
}
{
'type': 'decl_func'
}
{
'type': 'decl_const'
}
{
'type': 'decl_method'
}
{
'type': 'entry'
}
{
'type': 'lambda'
}
{
'type': 'block'
}
{
'type': 'if'
}
{
'type': 'switch'
}
{
'type': 'select'
}
{
'type': 'list'
}
{
'type': 'tuple'
}
{
'type': 'record'
}
]
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9986674189567566,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/pummel/test-net-many-clients.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.
# settings
# measured
runClient = (callback) ->
client = net.createConnection(common.PORT)
client.connections = 0
client.setEncoding "utf8"
client.on "connect", ->
common.print "c"
client.recved = ""
client.connections += 1
return
client.on "data", (chunk) ->
@recved += chunk
return
client.on "end", ->
client.end()
return
client.on "error", (e) ->
console.log "\n\nERROOOOOr"
throw ereturn
client.on "close", (had_error) ->
common.print "."
assert.equal false, had_error
assert.equal bytes, client.recved.length
console.log client.fd if client.fd
assert.ok not client.fd
if @connections < connections_per_client
@connect common.PORT
else
callback()
return
return
common = require("../common")
assert = require("assert")
net = require("net")
bytes = 1024 * 40
concurrency = 100
connections_per_client = 5
total_connections = 0
body = ""
i = 0
while i < bytes
body += "C"
i++
server = net.createServer((c) ->
console.log "connected"
total_connections++
common.print "#"
c.write body
c.end()
return
)
server.listen common.PORT, ->
finished_clients = 0
i = 0
while i < concurrency
runClient ->
server.close() if ++finished_clients is concurrency
return
i++
return
process.on "exit", ->
assert.equal connections_per_client * concurrency, total_connections
console.log "\nokay!"
return
| 225541 | # 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.
# settings
# measured
runClient = (callback) ->
client = net.createConnection(common.PORT)
client.connections = 0
client.setEncoding "utf8"
client.on "connect", ->
common.print "c"
client.recved = ""
client.connections += 1
return
client.on "data", (chunk) ->
@recved += chunk
return
client.on "end", ->
client.end()
return
client.on "error", (e) ->
console.log "\n\nERROOOOOr"
throw ereturn
client.on "close", (had_error) ->
common.print "."
assert.equal false, had_error
assert.equal bytes, client.recved.length
console.log client.fd if client.fd
assert.ok not client.fd
if @connections < connections_per_client
@connect common.PORT
else
callback()
return
return
common = require("../common")
assert = require("assert")
net = require("net")
bytes = 1024 * 40
concurrency = 100
connections_per_client = 5
total_connections = 0
body = ""
i = 0
while i < bytes
body += "C"
i++
server = net.createServer((c) ->
console.log "connected"
total_connections++
common.print "#"
c.write body
c.end()
return
)
server.listen common.PORT, ->
finished_clients = 0
i = 0
while i < concurrency
runClient ->
server.close() if ++finished_clients is concurrency
return
i++
return
process.on "exit", ->
assert.equal connections_per_client * concurrency, total_connections
console.log "\nokay!"
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.
# settings
# measured
runClient = (callback) ->
client = net.createConnection(common.PORT)
client.connections = 0
client.setEncoding "utf8"
client.on "connect", ->
common.print "c"
client.recved = ""
client.connections += 1
return
client.on "data", (chunk) ->
@recved += chunk
return
client.on "end", ->
client.end()
return
client.on "error", (e) ->
console.log "\n\nERROOOOOr"
throw ereturn
client.on "close", (had_error) ->
common.print "."
assert.equal false, had_error
assert.equal bytes, client.recved.length
console.log client.fd if client.fd
assert.ok not client.fd
if @connections < connections_per_client
@connect common.PORT
else
callback()
return
return
common = require("../common")
assert = require("assert")
net = require("net")
bytes = 1024 * 40
concurrency = 100
connections_per_client = 5
total_connections = 0
body = ""
i = 0
while i < bytes
body += "C"
i++
server = net.createServer((c) ->
console.log "connected"
total_connections++
common.print "#"
c.write body
c.end()
return
)
server.listen common.PORT, ->
finished_clients = 0
i = 0
while i < concurrency
runClient ->
server.close() if ++finished_clients is concurrency
return
i++
return
process.on "exit", ->
assert.equal connections_per_client * concurrency, total_connections
console.log "\nokay!"
return
|
[
{
"context": "http://elving.github.com/swag/>\n Copyright 2012 Elving Rodriguez <http://elving.me/>\n Available under MIT licen",
"end": 88,
"score": 0.9998777508735657,
"start": 72,
"tag": "NAME",
"value": "Elving Rodriguez"
},
{
"context": "ailable under MIT license <https://raw.github.com/elving/swag/master/LICENSE>\n###\n\nif window?\n window.S",
"end": 171,
"score": 0.9350681900978088,
"start": 165,
"tag": "USERNAME",
"value": "elving"
}
] | src/swag.coffee | fanfavorite/swag | 264 | ###
Swag v0.6.1 <http://elving.github.com/swag/>
Copyright 2012 Elving Rodriguez <http://elving.me/>
Available under MIT license <https://raw.github.com/elving/swag/master/LICENSE>
###
if window?
window.Swag = Swag = {}
else if module?
module.exports = Swag = {}
Swag.helpers = {}
Swag.addHelper = (name, helper, argTypes = []) ->
unless argTypes instanceof Array
argTypes = [argTypes]
Swag.helpers[name] = ->
# Verify all required arguments have been supplied
Utils.verify name, arguments, argTypes
# Call all arguments which are functions to get their result
args = Array.prototype.slice.apply(arguments)
resultArgs = []
for arg in args
unless Utils.isHandlebarsSpecific(arg)
arg = Utils.result(arg)
resultArgs.push(arg)
helper.apply @, resultArgs
Swag.registerHelpers = (localHandlebars) ->
if localHandlebars
Swag.Handlebars = localHandlebars
else
if window?
if window.Ember?
Swag.Handlebars = Ember.Handlebars
else
Swag.Handlebars = window.Handlebars
else if module?
Swag.Handlebars = require 'handlebars'
Swag.registerHelper = (name, helper) ->
if window? and window.Ember
Swag.Handlebars.helper name, helper
else
Swag.Handlebars.registerHelper name, helper
for name, helper of Swag.helpers
Swag.registerHelper name, helper
| 186793 | ###
Swag v0.6.1 <http://elving.github.com/swag/>
Copyright 2012 <NAME> <http://elving.me/>
Available under MIT license <https://raw.github.com/elving/swag/master/LICENSE>
###
if window?
window.Swag = Swag = {}
else if module?
module.exports = Swag = {}
Swag.helpers = {}
Swag.addHelper = (name, helper, argTypes = []) ->
unless argTypes instanceof Array
argTypes = [argTypes]
Swag.helpers[name] = ->
# Verify all required arguments have been supplied
Utils.verify name, arguments, argTypes
# Call all arguments which are functions to get their result
args = Array.prototype.slice.apply(arguments)
resultArgs = []
for arg in args
unless Utils.isHandlebarsSpecific(arg)
arg = Utils.result(arg)
resultArgs.push(arg)
helper.apply @, resultArgs
Swag.registerHelpers = (localHandlebars) ->
if localHandlebars
Swag.Handlebars = localHandlebars
else
if window?
if window.Ember?
Swag.Handlebars = Ember.Handlebars
else
Swag.Handlebars = window.Handlebars
else if module?
Swag.Handlebars = require 'handlebars'
Swag.registerHelper = (name, helper) ->
if window? and window.Ember
Swag.Handlebars.helper name, helper
else
Swag.Handlebars.registerHelper name, helper
for name, helper of Swag.helpers
Swag.registerHelper name, helper
| true | ###
Swag v0.6.1 <http://elving.github.com/swag/>
Copyright 2012 PI:NAME:<NAME>END_PI <http://elving.me/>
Available under MIT license <https://raw.github.com/elving/swag/master/LICENSE>
###
if window?
window.Swag = Swag = {}
else if module?
module.exports = Swag = {}
Swag.helpers = {}
Swag.addHelper = (name, helper, argTypes = []) ->
unless argTypes instanceof Array
argTypes = [argTypes]
Swag.helpers[name] = ->
# Verify all required arguments have been supplied
Utils.verify name, arguments, argTypes
# Call all arguments which are functions to get their result
args = Array.prototype.slice.apply(arguments)
resultArgs = []
for arg in args
unless Utils.isHandlebarsSpecific(arg)
arg = Utils.result(arg)
resultArgs.push(arg)
helper.apply @, resultArgs
Swag.registerHelpers = (localHandlebars) ->
if localHandlebars
Swag.Handlebars = localHandlebars
else
if window?
if window.Ember?
Swag.Handlebars = Ember.Handlebars
else
Swag.Handlebars = window.Handlebars
else if module?
Swag.Handlebars = require 'handlebars'
Swag.registerHelper = (name, helper) ->
if window? and window.Ember
Swag.Handlebars.helper name, helper
else
Swag.Handlebars.registerHelper name, helper
for name, helper of Swag.helpers
Swag.registerHelper name, helper
|
[
{
"context": "els.Users.create\n\t\t\t\t_id: 'rocket.cat'\n\t\t\t\tname: \"Rocket.Cat\"\n\t\t\t\tusername: 'rocket.cat'\n\t\t\t\tstatus: \"onli",
"end": 323,
"score": 0.5054472088813782,
"start": 317,
"tag": "NAME",
"value": "Rocket"
},
{
"context": "rocket.cat'\n\t\t\t\tname: \"Rocket.Cat\"\n\t\t\t\tusername: 'rocket.cat'\n\t\t\t\tstatus: \"online\"\n\t\t\t\tstatusDefault: \"online\"",
"end": 354,
"score": 0.9996374249458313,
"start": 344,
"tag": "USERNAME",
"value": "rocket.cat"
},
{
"context": "g admin user:'.green\n\n\t\t\t\tadminUser =\n\t\t\t\t\tname: \"Administrator\"\n\t\t\t\t\tusername: \"admin\"\n\t\t\t\t\tstatus: \"offline\"\n\t\t",
"end": 1010,
"score": 0.9848167300224304,
"start": 997,
"tag": "NAME",
"value": "Administrator"
},
{
"context": "User =\n\t\t\t\t\tname: \"Administrator\"\n\t\t\t\t\tusername: \"admin\"\n\t\t\t\t\tstatus: \"offline\"\n\t\t\t\t\tstatusDefault: \"onli",
"end": 1033,
"score": 0.9948692917823792,
"start": 1028,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "USERNAME)\n\t\t\t\t\t\t\tadminUser.username = process.env.ADMIN_USERNAME\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tconsole.log 'Username provided ",
"end": 2265,
"score": 0.9531650543212891,
"start": 2251,
"tag": "USERNAME",
"value": "ADMIN_USERNAME"
},
{
"context": " ADMIN_USERNAME'.red\n\t\t\t\tconsole.log \"Username: #{adminUser.username}\".green\n\n\t\t\t\tid = RocketChat.models.Users.create ",
"end": 2539,
"score": 0.9989761114120483,
"start": 2521,
"tag": "USERNAME",
"value": "adminUser.username"
},
{
"context": "nv.ADMIN_PASS\n\t\t\t\tconsole.log \"Password: #{process.env.ADMIN_PASS}\".green\n\t\t\t\tRocketChat.authz.addUserRol",
"end": 2692,
"score": 0.8280580639839172,
"start": 2689,
"tag": "PASSWORD",
"value": "env"
},
{
"context": "ASS\n\t\t\t\tconsole.log \"Password: #{process.env.ADMIN_PASS}\".green\n\t\t\t\tRocketChat.authz.addUserRoles( id, 'a",
"end": 2703,
"score": 0.7442675828933716,
"start": 2699,
"tag": "PASSWORD",
"value": "PASS"
}
] | server/startup/initialData.coffee | amaapp/ama | 0 | Meteor.startup ->
Meteor.defer ->
if not RocketChat.models.Rooms.findOneById('GENERAL')?
RocketChat.models.Rooms.createWithIdTypeAndName 'GENERAL', 'c', 'general',
default: true
if not RocketChat.models.Users.findOneById('rocket.cat')?
RocketChat.models.Users.create
_id: 'rocket.cat'
name: "Rocket.Cat"
username: 'rocket.cat'
status: "online"
statusDefault: "online"
utcOffset: 0
active: true
bot: true
rs = RocketChatFile.bufferToStream new Buffer(Assets.getBinary('avatars/rocketcat.png'), 'utf8')
RocketChatFileAvatarInstance.deleteFile "rocket.cat.jpg"
ws = RocketChatFileAvatarInstance.createWriteStream "rocket.cat.jpg", 'image/png'
ws.on 'end', Meteor.bindEnvironment ->
RocketChat.models.Users.setAvatarOrigin 'rocket.cat', 'local'
rs.pipe(ws)
if process.env.ADMIN_PASS?
if _.isEmpty(RocketChat.authz.getUsersInRole( 'admin' ).fetch())
console.log 'Inserting admin user:'.green
adminUser =
name: "Administrator"
username: "admin"
status: "offline"
statusDefault: "online"
utcOffset: 0
active: true
if process.env.ADMIN_NAME?
adminUser.name = process.env.ADMIN_NAME
console.log "Name: #{adminUser.name}".green
if process.env.ADMIN_EMAIL?
re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if re.test process.env.ADMIN_EMAIL
if not RocketChat.models.Users.findOneByEmailAddress process.env.ADMIN_EMAIL
adminUser.emails = [
address: process.env.ADMIN_EMAIL
verified: true
]
console.log "Email: #{process.env.ADMIN_EMAIL}".green
else
console.log 'E-mail provided already exists; Ignoring environment variables ADMIN_EMAIL'.red
else
console.log 'E-mail provided is invalid; Ignoring environment variables ADMIN_EMAIL'.red
if process.env.ADMIN_USERNAME?
try
nameValidation = new RegExp '^' + RocketChat.settings.get('UTF8_Names_Validation') + '$'
catch
nameValidation = new RegExp '^[0-9a-zA-Z-_.]+$'
if nameValidation.test process.env.ADMIN_USERNAME
if RocketChat.checkUsernameAvailability(process.env.ADMIN_USERNAME)
adminUser.username = process.env.ADMIN_USERNAME
else
console.log 'Username provided already exists; Ignoring environment variables ADMIN_USERNAME'.red
else
console.log 'Username provided is invalid; Ignoring environment variables ADMIN_USERNAME'.red
console.log "Username: #{adminUser.username}".green
id = RocketChat.models.Users.create adminUser
Accounts.setPassword id, process.env.ADMIN_PASS
console.log "Password: #{process.env.ADMIN_PASS}".green
RocketChat.authz.addUserRoles( id, 'admin')
else
console.log 'Users with admin role already exist; Ignoring environment variables ADMIN_PASS'.red
# Set oldest user as admin, if none exists yet
if _.isEmpty( RocketChat.authz.getUsersInRole( 'admin' ).fetch())
# get oldest user
oldestUser = RocketChat.models.Users.findOne({ _id: { $ne: 'rocket.cat' }}, { fields: { username: 1 }, sort: {createdAt: 1}})
if oldestUser
RocketChat.authz.addUserRoles( oldestUser._id, 'admin')
console.log "No admins are found. Set #{oldestUser.username} as admin for being the oldest user"
| 80187 | Meteor.startup ->
Meteor.defer ->
if not RocketChat.models.Rooms.findOneById('GENERAL')?
RocketChat.models.Rooms.createWithIdTypeAndName 'GENERAL', 'c', 'general',
default: true
if not RocketChat.models.Users.findOneById('rocket.cat')?
RocketChat.models.Users.create
_id: 'rocket.cat'
name: "<NAME>.Cat"
username: 'rocket.cat'
status: "online"
statusDefault: "online"
utcOffset: 0
active: true
bot: true
rs = RocketChatFile.bufferToStream new Buffer(Assets.getBinary('avatars/rocketcat.png'), 'utf8')
RocketChatFileAvatarInstance.deleteFile "rocket.cat.jpg"
ws = RocketChatFileAvatarInstance.createWriteStream "rocket.cat.jpg", 'image/png'
ws.on 'end', Meteor.bindEnvironment ->
RocketChat.models.Users.setAvatarOrigin 'rocket.cat', 'local'
rs.pipe(ws)
if process.env.ADMIN_PASS?
if _.isEmpty(RocketChat.authz.getUsersInRole( 'admin' ).fetch())
console.log 'Inserting admin user:'.green
adminUser =
name: "<NAME>"
username: "admin"
status: "offline"
statusDefault: "online"
utcOffset: 0
active: true
if process.env.ADMIN_NAME?
adminUser.name = process.env.ADMIN_NAME
console.log "Name: #{adminUser.name}".green
if process.env.ADMIN_EMAIL?
re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if re.test process.env.ADMIN_EMAIL
if not RocketChat.models.Users.findOneByEmailAddress process.env.ADMIN_EMAIL
adminUser.emails = [
address: process.env.ADMIN_EMAIL
verified: true
]
console.log "Email: #{process.env.ADMIN_EMAIL}".green
else
console.log 'E-mail provided already exists; Ignoring environment variables ADMIN_EMAIL'.red
else
console.log 'E-mail provided is invalid; Ignoring environment variables ADMIN_EMAIL'.red
if process.env.ADMIN_USERNAME?
try
nameValidation = new RegExp '^' + RocketChat.settings.get('UTF8_Names_Validation') + '$'
catch
nameValidation = new RegExp '^[0-9a-zA-Z-_.]+$'
if nameValidation.test process.env.ADMIN_USERNAME
if RocketChat.checkUsernameAvailability(process.env.ADMIN_USERNAME)
adminUser.username = process.env.ADMIN_USERNAME
else
console.log 'Username provided already exists; Ignoring environment variables ADMIN_USERNAME'.red
else
console.log 'Username provided is invalid; Ignoring environment variables ADMIN_USERNAME'.red
console.log "Username: #{adminUser.username}".green
id = RocketChat.models.Users.create adminUser
Accounts.setPassword id, process.env.ADMIN_PASS
console.log "Password: #{process.<PASSWORD>.ADMIN_<PASSWORD>}".green
RocketChat.authz.addUserRoles( id, 'admin')
else
console.log 'Users with admin role already exist; Ignoring environment variables ADMIN_PASS'.red
# Set oldest user as admin, if none exists yet
if _.isEmpty( RocketChat.authz.getUsersInRole( 'admin' ).fetch())
# get oldest user
oldestUser = RocketChat.models.Users.findOne({ _id: { $ne: 'rocket.cat' }}, { fields: { username: 1 }, sort: {createdAt: 1}})
if oldestUser
RocketChat.authz.addUserRoles( oldestUser._id, 'admin')
console.log "No admins are found. Set #{oldestUser.username} as admin for being the oldest user"
| true | Meteor.startup ->
Meteor.defer ->
if not RocketChat.models.Rooms.findOneById('GENERAL')?
RocketChat.models.Rooms.createWithIdTypeAndName 'GENERAL', 'c', 'general',
default: true
if not RocketChat.models.Users.findOneById('rocket.cat')?
RocketChat.models.Users.create
_id: 'rocket.cat'
name: "PI:NAME:<NAME>END_PI.Cat"
username: 'rocket.cat'
status: "online"
statusDefault: "online"
utcOffset: 0
active: true
bot: true
rs = RocketChatFile.bufferToStream new Buffer(Assets.getBinary('avatars/rocketcat.png'), 'utf8')
RocketChatFileAvatarInstance.deleteFile "rocket.cat.jpg"
ws = RocketChatFileAvatarInstance.createWriteStream "rocket.cat.jpg", 'image/png'
ws.on 'end', Meteor.bindEnvironment ->
RocketChat.models.Users.setAvatarOrigin 'rocket.cat', 'local'
rs.pipe(ws)
if process.env.ADMIN_PASS?
if _.isEmpty(RocketChat.authz.getUsersInRole( 'admin' ).fetch())
console.log 'Inserting admin user:'.green
adminUser =
name: "PI:NAME:<NAME>END_PI"
username: "admin"
status: "offline"
statusDefault: "online"
utcOffset: 0
active: true
if process.env.ADMIN_NAME?
adminUser.name = process.env.ADMIN_NAME
console.log "Name: #{adminUser.name}".green
if process.env.ADMIN_EMAIL?
re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if re.test process.env.ADMIN_EMAIL
if not RocketChat.models.Users.findOneByEmailAddress process.env.ADMIN_EMAIL
adminUser.emails = [
address: process.env.ADMIN_EMAIL
verified: true
]
console.log "Email: #{process.env.ADMIN_EMAIL}".green
else
console.log 'E-mail provided already exists; Ignoring environment variables ADMIN_EMAIL'.red
else
console.log 'E-mail provided is invalid; Ignoring environment variables ADMIN_EMAIL'.red
if process.env.ADMIN_USERNAME?
try
nameValidation = new RegExp '^' + RocketChat.settings.get('UTF8_Names_Validation') + '$'
catch
nameValidation = new RegExp '^[0-9a-zA-Z-_.]+$'
if nameValidation.test process.env.ADMIN_USERNAME
if RocketChat.checkUsernameAvailability(process.env.ADMIN_USERNAME)
adminUser.username = process.env.ADMIN_USERNAME
else
console.log 'Username provided already exists; Ignoring environment variables ADMIN_USERNAME'.red
else
console.log 'Username provided is invalid; Ignoring environment variables ADMIN_USERNAME'.red
console.log "Username: #{adminUser.username}".green
id = RocketChat.models.Users.create adminUser
Accounts.setPassword id, process.env.ADMIN_PASS
console.log "Password: #{process.PI:PASSWORD:<PASSWORD>END_PI.ADMIN_PI:PASSWORD:<PASSWORD>END_PI}".green
RocketChat.authz.addUserRoles( id, 'admin')
else
console.log 'Users with admin role already exist; Ignoring environment variables ADMIN_PASS'.red
# Set oldest user as admin, if none exists yet
if _.isEmpty( RocketChat.authz.getUsersInRole( 'admin' ).fetch())
# get oldest user
oldestUser = RocketChat.models.Users.findOne({ _id: { $ne: 'rocket.cat' }}, { fields: { username: 1 }, sort: {createdAt: 1}})
if oldestUser
RocketChat.authz.addUserRoles( oldestUser._id, 'admin')
console.log "No admins are found. Set #{oldestUser.username} as admin for being the oldest user"
|
[
{
"context": "sync login\":\"\"\"Usuario:\"\"\"\n \"sync password\":\"\"\"Contraseña:\"\"\"\n \"sync help\":\"\"\"¿Esta usted perdido(a)? si",
"end": 6161,
"score": 0.9985249638557434,
"start": 6151,
"tag": "PASSWORD",
"value": "Contraseña"
}
] | client/app/locales/es.coffee | Noctisae/cozy-series | 0 | module.exports =
"default calendar name":"""mi agenda"""
"Add":"""Añadir"""
"event":"""Evento"""
"create event":"""Creación de un evento"""
"edit event":"""Modificar un evento"""
"edit":"""Mofificar"""
"create":"""Crear"""
"creation":"""Creación"""
"invite":"""Invitar"""
"close":"""Cerrar"""
"delete":"""Suprimir"""
"change color":"""Cambiar el color"""
"rename":"""Renombrar"""
"export":"""Exportar"""
"remove":"""Suprimir el evento"""
"duplicate":"""Duplicar el evento"""
"Place":"""Lugar"""
"all day":"""día entero"""
"All day":"""Día entero"""
"description":"""Descripción"""
"date":"""fecha"""
"Day":"""Día"""
"days":"""días"""
"Edit":"""Modificar"""
"Email":"""Correo electrónico"""
"Import":"""Importar"""
"Export":"""Exportar"""
"show":"""Mostrar"""
"hide":"""Ocultar"""
"List":"""Lista"""
"list":"""Lista"""
"Calendar":"""Agenda"""
"calendar":"""Agenda"""
"Sync":"""Sincronizar"""
"ie: 9:00 important meeting":"""ej: 9:00 reunión importante"""
"Month":"""Mes"""
"Popup":"""Popup"""
"Switch to List":"""Cambiar a modo Lista"""
"Switch to Calendar":"""Cambiar a modo Agenda"""
"time":"""tiempo"""
"Today":"""Hoy"""
"today":"""hoy"""
"What should I remind you ?":"""¿Qué debo recordarle?"""
"select an icalendar file":"""Seleccionar un archivo icalendar"""
"import your icalendar file":"""importar su archivo icalendar"""
"confirm import":"""confirmar la importación"""
"cancel":"""anular"""
"Create":"""Crear"""
"Events to import":"""Eventos que se han de importar"""
"Create Event":"""Crear un evento"""
"From [hours:minutes]":"""De [horas:minutos]"""
"To [hours:minutes]":"""A [horas:minutos]"""
"To [date]":"""A [fecha]"""
"Description":"""Descripción"""
"days after":"""días después"""
"days later":"""días después"""
"Week":"""Semana"""
"Display":"""Notificación"""
"DISPLAY":"""Notificación"""
"EMAIL":"""Correo electrónico"""
"BOTH":"""Correo electrónico & notificación"""
"display previous events":"""Visualizar los eventos precedentes"""
"display next events":"""Visualizar los eventos siguientes"""
"are you sure":"""¿Está usted seguro(a)?"""
"confirm delete calendar":"""Usted está a punto de suprimir todos los eventos asociados a %{calendarName}. ¿Está seguro(a)?"""
"confirm delete selected calendars":"""Usted está a punto de suprimir todas las agendas seleccionadas. ¿Está seguro(a)?"""
"advanced":"""Más detalles"""
"enter email":"""Escriba la dirección del correo electrónico"""
"ON":"""activada"""
"OFF":"""desactivada"""
"no description":"""Sin descripción"""
"add calendar":"""Añadir agenda"""
"new calendar":"""Nueva agenda"""
"multiple actions":"""Acciones múltiples"""
"recurrence":"""Recurrencia"""
"recurrence rule":"""Reglas de recurrencia"""
"make reccurent":"""Volver recurrente"""
"repeat every":"""Repetir cada"""
"no recurrence":"""No se repite"""
"repeat on":"""Repetir los"""
"repeat on date":"""Repetir los días del mes"""
"repeat on weekday":"""Repetir el día de la semana"""
"repeat until":"""Repetir hasta"""
"after":"""O después"""
"repeat":"""Repetir"""
"forever":"""Siempre"""
"occurences":"""ocasiones"""
"every":"""Cada"""
"minutes":"""minutos"""
"minute":"""minuto"""
"minute ":"""minuto"""
"hours":"""horas"""
"hour":"""hora"""
"day":"""día"""
"weeks":"""semanas"""
"week":"""semana"""
"months":"""meses"""
"month":"""mes"""
"years":"""años"""
"year":"""año"""
"until":"""hasta"""
"for":"""durante"""
"on":"""el"""
"on the":"""el"""
"th":"""º """
"nd":"""º """
"rd":"""º """
"st":"""º """
"last":"""último"""
"and":"""y"""
"times":"""veces"""
"weekday":"""día de la semana"""
"summary":"""Título"""
"start":"""Comienzo"""
"end":"""Fin"""
"tags":"""Etiquetas"""
"add tags":"""Añadir etiquetas"""
"change":"""Cambiar"""
"change to":"""Cambiar a"""
"change calendar":"""Cambiar de agenda"""
"save changes":"""Guardar cambios"""
"save changes and invite guests":"""Guardar cambios y enviar las invitaciones"""
"guests":"""Invitados"""
"cancel Invitation":"""Anular la invitación"""
"From":"""De"""
"To":"""A"""
"All day, until":"""Todo el día, hasta"""
"All one day":"""Todo el día"""
"Reminders before the event":"""Recordatorios antes del evento"""
"reminder":"""Recordatorio"""
"send mails question":"""Enviar un correo electrónico de notificación a:"""
"modal send mails":"""Enviar una notificación"""
"yes":"""Si"""
"no":"""No"""
"no summary":"""El título es obligatorio"""
"start after end":"""La fecha del comienzo es posterior a la fecha del final."""
"invalid start date":"""La fecha del comienzo no es válida"""
"invalid end date":"""La fecha del final no es válida"""
"invalid trigg date":"""La fecha no es válida"""
"invalid action":"""La acción no es válida"""
"server error occured":"""Ha ocurrido un error en el servidor"""
"synchronization":"""Sincronización"""
"mobile sync":"""Sincronización con los móviles (CalDAV)"""
"link imported events with calendar":"""Ligar los eventos a importar con la siguiente agenda:"""
"import an ical file":"""Para importar un archivo ICal a su agenda Cozy, comenzar por hacer clic en este botón para precargarlo:"""
"download a copy of your calendar":"""Seleccionar una agenda y luego hacer clic en el botón para descargar una copia de la agenda como archivo ICal, :"""
"icalendar export":"""Exportar ICalendar"""
"icalendar import":"""Importar ICalendar"""
"to sync your cal with":"""Para sincronizar su agenda con sus periféricos, usted debe seguir los dos siguientes pasos"""
"sync headline with data":"""Para sincronizar su agenda, use la siguiente información:"""
"sync url":"""URL:"""
"sync login":"""Usuario:"""
"sync password":"""Contraseña:"""
"sync help":"""¿Esta usted perdido(a)? siga la"""
"sync help link":"""guía paso a paso!"""
"install the sync module":"""Instalar el módulo Sincronización desde la Apliteca Cozy"""
"connect to it and follow":"""Conectarse y seguir las instrucciones relativas a CalDAV."""
"some event fail to save":"""No se ha guardado un evento (ha ocurrido un error)"""
"imported events":"""Número de eventos importados"""
"import finished":"""La importación ha terminado"""
"import error occured for":"""Un error ha ocurrido al importar los siguientes elementos :"""
"export your calendar":"""Exportar su agenda"""
"please select existing calendar":"""Por favor seleccionar una agenda existente"""
"January":"""enero"""
"February":"""febrero"""
"March":"""marzo"""
"April":"""abril"""
"May":"""mayo"""
"June":"""junio"""
"July":"""julio"""
"August":"""agosto"""
"September":"""septiembre"""
"October":"""octubre"""
"November":"""noviembre"""
"December":"""diciembre"""
"Jan":"""ene"""
"Feb":"""feb"""
"Mar":"""mar"""
"Apr":"""abr"""
"Jun":"""jun"""
"Jul":"""jul"""
"Aug":"""ago"""
"Sep":"""sep"""
"Oct":"""oct"""
"Nov":"""nov"""
"Dec":"""dic"""
"calendar exist error":"""Una agenda llamada "Nueva agenda" ya existe."""
"email date format":"""DD/MM/AAAA [a] HH[h]mm"""
"email date format allday":"""DD/MM/AAAA [todo el día]"""
"email invitation title":"""Invitación a "%{description}\""""
"email invitation content":"""Buenos días, desearía invitarlo(a) al siguiente evento:
%{description} %{place}
el %{date}
¿Podríamos contar con su presencia?
Si
%{url}?status=ACCEPTED&key=%{key}
No
%{url}?status=DECLINED&key=%{key}"""
"email update title":"""El evento "%{description}" ha cambiado"""
"email update content":"""Un evento en el que usted participa se ha cambiado:
%{description} %{place}
el %{date}
Seguiré estando presente
%{url}?status=ACCEPTED&key=%{key}
No cuenten conmigo
%{url}?status=ACCEPTED&key=%{key}"""
"email delete title":"""Este evento ha sido anulado: %{description}"""
"email delete content":"""Este evento ha sido anulado:
%{description} %{place}
el %{date}"""
| 203273 | module.exports =
"default calendar name":"""mi agenda"""
"Add":"""Añadir"""
"event":"""Evento"""
"create event":"""Creación de un evento"""
"edit event":"""Modificar un evento"""
"edit":"""Mofificar"""
"create":"""Crear"""
"creation":"""Creación"""
"invite":"""Invitar"""
"close":"""Cerrar"""
"delete":"""Suprimir"""
"change color":"""Cambiar el color"""
"rename":"""Renombrar"""
"export":"""Exportar"""
"remove":"""Suprimir el evento"""
"duplicate":"""Duplicar el evento"""
"Place":"""Lugar"""
"all day":"""día entero"""
"All day":"""Día entero"""
"description":"""Descripción"""
"date":"""fecha"""
"Day":"""Día"""
"days":"""días"""
"Edit":"""Modificar"""
"Email":"""Correo electrónico"""
"Import":"""Importar"""
"Export":"""Exportar"""
"show":"""Mostrar"""
"hide":"""Ocultar"""
"List":"""Lista"""
"list":"""Lista"""
"Calendar":"""Agenda"""
"calendar":"""Agenda"""
"Sync":"""Sincronizar"""
"ie: 9:00 important meeting":"""ej: 9:00 reunión importante"""
"Month":"""Mes"""
"Popup":"""Popup"""
"Switch to List":"""Cambiar a modo Lista"""
"Switch to Calendar":"""Cambiar a modo Agenda"""
"time":"""tiempo"""
"Today":"""Hoy"""
"today":"""hoy"""
"What should I remind you ?":"""¿Qué debo recordarle?"""
"select an icalendar file":"""Seleccionar un archivo icalendar"""
"import your icalendar file":"""importar su archivo icalendar"""
"confirm import":"""confirmar la importación"""
"cancel":"""anular"""
"Create":"""Crear"""
"Events to import":"""Eventos que se han de importar"""
"Create Event":"""Crear un evento"""
"From [hours:minutes]":"""De [horas:minutos]"""
"To [hours:minutes]":"""A [horas:minutos]"""
"To [date]":"""A [fecha]"""
"Description":"""Descripción"""
"days after":"""días después"""
"days later":"""días después"""
"Week":"""Semana"""
"Display":"""Notificación"""
"DISPLAY":"""Notificación"""
"EMAIL":"""Correo electrónico"""
"BOTH":"""Correo electrónico & notificación"""
"display previous events":"""Visualizar los eventos precedentes"""
"display next events":"""Visualizar los eventos siguientes"""
"are you sure":"""¿Está usted seguro(a)?"""
"confirm delete calendar":"""Usted está a punto de suprimir todos los eventos asociados a %{calendarName}. ¿Está seguro(a)?"""
"confirm delete selected calendars":"""Usted está a punto de suprimir todas las agendas seleccionadas. ¿Está seguro(a)?"""
"advanced":"""Más detalles"""
"enter email":"""Escriba la dirección del correo electrónico"""
"ON":"""activada"""
"OFF":"""desactivada"""
"no description":"""Sin descripción"""
"add calendar":"""Añadir agenda"""
"new calendar":"""Nueva agenda"""
"multiple actions":"""Acciones múltiples"""
"recurrence":"""Recurrencia"""
"recurrence rule":"""Reglas de recurrencia"""
"make reccurent":"""Volver recurrente"""
"repeat every":"""Repetir cada"""
"no recurrence":"""No se repite"""
"repeat on":"""Repetir los"""
"repeat on date":"""Repetir los días del mes"""
"repeat on weekday":"""Repetir el día de la semana"""
"repeat until":"""Repetir hasta"""
"after":"""O después"""
"repeat":"""Repetir"""
"forever":"""Siempre"""
"occurences":"""ocasiones"""
"every":"""Cada"""
"minutes":"""minutos"""
"minute":"""minuto"""
"minute ":"""minuto"""
"hours":"""horas"""
"hour":"""hora"""
"day":"""día"""
"weeks":"""semanas"""
"week":"""semana"""
"months":"""meses"""
"month":"""mes"""
"years":"""años"""
"year":"""año"""
"until":"""hasta"""
"for":"""durante"""
"on":"""el"""
"on the":"""el"""
"th":"""º """
"nd":"""º """
"rd":"""º """
"st":"""º """
"last":"""último"""
"and":"""y"""
"times":"""veces"""
"weekday":"""día de la semana"""
"summary":"""Título"""
"start":"""Comienzo"""
"end":"""Fin"""
"tags":"""Etiquetas"""
"add tags":"""Añadir etiquetas"""
"change":"""Cambiar"""
"change to":"""Cambiar a"""
"change calendar":"""Cambiar de agenda"""
"save changes":"""Guardar cambios"""
"save changes and invite guests":"""Guardar cambios y enviar las invitaciones"""
"guests":"""Invitados"""
"cancel Invitation":"""Anular la invitación"""
"From":"""De"""
"To":"""A"""
"All day, until":"""Todo el día, hasta"""
"All one day":"""Todo el día"""
"Reminders before the event":"""Recordatorios antes del evento"""
"reminder":"""Recordatorio"""
"send mails question":"""Enviar un correo electrónico de notificación a:"""
"modal send mails":"""Enviar una notificación"""
"yes":"""Si"""
"no":"""No"""
"no summary":"""El título es obligatorio"""
"start after end":"""La fecha del comienzo es posterior a la fecha del final."""
"invalid start date":"""La fecha del comienzo no es válida"""
"invalid end date":"""La fecha del final no es válida"""
"invalid trigg date":"""La fecha no es válida"""
"invalid action":"""La acción no es válida"""
"server error occured":"""Ha ocurrido un error en el servidor"""
"synchronization":"""Sincronización"""
"mobile sync":"""Sincronización con los móviles (CalDAV)"""
"link imported events with calendar":"""Ligar los eventos a importar con la siguiente agenda:"""
"import an ical file":"""Para importar un archivo ICal a su agenda Cozy, comenzar por hacer clic en este botón para precargarlo:"""
"download a copy of your calendar":"""Seleccionar una agenda y luego hacer clic en el botón para descargar una copia de la agenda como archivo ICal, :"""
"icalendar export":"""Exportar ICalendar"""
"icalendar import":"""Importar ICalendar"""
"to sync your cal with":"""Para sincronizar su agenda con sus periféricos, usted debe seguir los dos siguientes pasos"""
"sync headline with data":"""Para sincronizar su agenda, use la siguiente información:"""
"sync url":"""URL:"""
"sync login":"""Usuario:"""
"sync password":"""<PASSWORD>:"""
"sync help":"""¿Esta usted perdido(a)? siga la"""
"sync help link":"""guía paso a paso!"""
"install the sync module":"""Instalar el módulo Sincronización desde la Apliteca Cozy"""
"connect to it and follow":"""Conectarse y seguir las instrucciones relativas a CalDAV."""
"some event fail to save":"""No se ha guardado un evento (ha ocurrido un error)"""
"imported events":"""Número de eventos importados"""
"import finished":"""La importación ha terminado"""
"import error occured for":"""Un error ha ocurrido al importar los siguientes elementos :"""
"export your calendar":"""Exportar su agenda"""
"please select existing calendar":"""Por favor seleccionar una agenda existente"""
"January":"""enero"""
"February":"""febrero"""
"March":"""marzo"""
"April":"""abril"""
"May":"""mayo"""
"June":"""junio"""
"July":"""julio"""
"August":"""agosto"""
"September":"""septiembre"""
"October":"""octubre"""
"November":"""noviembre"""
"December":"""diciembre"""
"Jan":"""ene"""
"Feb":"""feb"""
"Mar":"""mar"""
"Apr":"""abr"""
"Jun":"""jun"""
"Jul":"""jul"""
"Aug":"""ago"""
"Sep":"""sep"""
"Oct":"""oct"""
"Nov":"""nov"""
"Dec":"""dic"""
"calendar exist error":"""Una agenda llamada "Nueva agenda" ya existe."""
"email date format":"""DD/MM/AAAA [a] HH[h]mm"""
"email date format allday":"""DD/MM/AAAA [todo el día]"""
"email invitation title":"""Invitación a "%{description}\""""
"email invitation content":"""Buenos días, desearía invitarlo(a) al siguiente evento:
%{description} %{place}
el %{date}
¿Podríamos contar con su presencia?
Si
%{url}?status=ACCEPTED&key=%{key}
No
%{url}?status=DECLINED&key=%{key}"""
"email update title":"""El evento "%{description}" ha cambiado"""
"email update content":"""Un evento en el que usted participa se ha cambiado:
%{description} %{place}
el %{date}
Seguiré estando presente
%{url}?status=ACCEPTED&key=%{key}
No cuenten conmigo
%{url}?status=ACCEPTED&key=%{key}"""
"email delete title":"""Este evento ha sido anulado: %{description}"""
"email delete content":"""Este evento ha sido anulado:
%{description} %{place}
el %{date}"""
| true | module.exports =
"default calendar name":"""mi agenda"""
"Add":"""Añadir"""
"event":"""Evento"""
"create event":"""Creación de un evento"""
"edit event":"""Modificar un evento"""
"edit":"""Mofificar"""
"create":"""Crear"""
"creation":"""Creación"""
"invite":"""Invitar"""
"close":"""Cerrar"""
"delete":"""Suprimir"""
"change color":"""Cambiar el color"""
"rename":"""Renombrar"""
"export":"""Exportar"""
"remove":"""Suprimir el evento"""
"duplicate":"""Duplicar el evento"""
"Place":"""Lugar"""
"all day":"""día entero"""
"All day":"""Día entero"""
"description":"""Descripción"""
"date":"""fecha"""
"Day":"""Día"""
"days":"""días"""
"Edit":"""Modificar"""
"Email":"""Correo electrónico"""
"Import":"""Importar"""
"Export":"""Exportar"""
"show":"""Mostrar"""
"hide":"""Ocultar"""
"List":"""Lista"""
"list":"""Lista"""
"Calendar":"""Agenda"""
"calendar":"""Agenda"""
"Sync":"""Sincronizar"""
"ie: 9:00 important meeting":"""ej: 9:00 reunión importante"""
"Month":"""Mes"""
"Popup":"""Popup"""
"Switch to List":"""Cambiar a modo Lista"""
"Switch to Calendar":"""Cambiar a modo Agenda"""
"time":"""tiempo"""
"Today":"""Hoy"""
"today":"""hoy"""
"What should I remind you ?":"""¿Qué debo recordarle?"""
"select an icalendar file":"""Seleccionar un archivo icalendar"""
"import your icalendar file":"""importar su archivo icalendar"""
"confirm import":"""confirmar la importación"""
"cancel":"""anular"""
"Create":"""Crear"""
"Events to import":"""Eventos que se han de importar"""
"Create Event":"""Crear un evento"""
"From [hours:minutes]":"""De [horas:minutos]"""
"To [hours:minutes]":"""A [horas:minutos]"""
"To [date]":"""A [fecha]"""
"Description":"""Descripción"""
"days after":"""días después"""
"days later":"""días después"""
"Week":"""Semana"""
"Display":"""Notificación"""
"DISPLAY":"""Notificación"""
"EMAIL":"""Correo electrónico"""
"BOTH":"""Correo electrónico & notificación"""
"display previous events":"""Visualizar los eventos precedentes"""
"display next events":"""Visualizar los eventos siguientes"""
"are you sure":"""¿Está usted seguro(a)?"""
"confirm delete calendar":"""Usted está a punto de suprimir todos los eventos asociados a %{calendarName}. ¿Está seguro(a)?"""
"confirm delete selected calendars":"""Usted está a punto de suprimir todas las agendas seleccionadas. ¿Está seguro(a)?"""
"advanced":"""Más detalles"""
"enter email":"""Escriba la dirección del correo electrónico"""
"ON":"""activada"""
"OFF":"""desactivada"""
"no description":"""Sin descripción"""
"add calendar":"""Añadir agenda"""
"new calendar":"""Nueva agenda"""
"multiple actions":"""Acciones múltiples"""
"recurrence":"""Recurrencia"""
"recurrence rule":"""Reglas de recurrencia"""
"make reccurent":"""Volver recurrente"""
"repeat every":"""Repetir cada"""
"no recurrence":"""No se repite"""
"repeat on":"""Repetir los"""
"repeat on date":"""Repetir los días del mes"""
"repeat on weekday":"""Repetir el día de la semana"""
"repeat until":"""Repetir hasta"""
"after":"""O después"""
"repeat":"""Repetir"""
"forever":"""Siempre"""
"occurences":"""ocasiones"""
"every":"""Cada"""
"minutes":"""minutos"""
"minute":"""minuto"""
"minute ":"""minuto"""
"hours":"""horas"""
"hour":"""hora"""
"day":"""día"""
"weeks":"""semanas"""
"week":"""semana"""
"months":"""meses"""
"month":"""mes"""
"years":"""años"""
"year":"""año"""
"until":"""hasta"""
"for":"""durante"""
"on":"""el"""
"on the":"""el"""
"th":"""º """
"nd":"""º """
"rd":"""º """
"st":"""º """
"last":"""último"""
"and":"""y"""
"times":"""veces"""
"weekday":"""día de la semana"""
"summary":"""Título"""
"start":"""Comienzo"""
"end":"""Fin"""
"tags":"""Etiquetas"""
"add tags":"""Añadir etiquetas"""
"change":"""Cambiar"""
"change to":"""Cambiar a"""
"change calendar":"""Cambiar de agenda"""
"save changes":"""Guardar cambios"""
"save changes and invite guests":"""Guardar cambios y enviar las invitaciones"""
"guests":"""Invitados"""
"cancel Invitation":"""Anular la invitación"""
"From":"""De"""
"To":"""A"""
"All day, until":"""Todo el día, hasta"""
"All one day":"""Todo el día"""
"Reminders before the event":"""Recordatorios antes del evento"""
"reminder":"""Recordatorio"""
"send mails question":"""Enviar un correo electrónico de notificación a:"""
"modal send mails":"""Enviar una notificación"""
"yes":"""Si"""
"no":"""No"""
"no summary":"""El título es obligatorio"""
"start after end":"""La fecha del comienzo es posterior a la fecha del final."""
"invalid start date":"""La fecha del comienzo no es válida"""
"invalid end date":"""La fecha del final no es válida"""
"invalid trigg date":"""La fecha no es válida"""
"invalid action":"""La acción no es válida"""
"server error occured":"""Ha ocurrido un error en el servidor"""
"synchronization":"""Sincronización"""
"mobile sync":"""Sincronización con los móviles (CalDAV)"""
"link imported events with calendar":"""Ligar los eventos a importar con la siguiente agenda:"""
"import an ical file":"""Para importar un archivo ICal a su agenda Cozy, comenzar por hacer clic en este botón para precargarlo:"""
"download a copy of your calendar":"""Seleccionar una agenda y luego hacer clic en el botón para descargar una copia de la agenda como archivo ICal, :"""
"icalendar export":"""Exportar ICalendar"""
"icalendar import":"""Importar ICalendar"""
"to sync your cal with":"""Para sincronizar su agenda con sus periféricos, usted debe seguir los dos siguientes pasos"""
"sync headline with data":"""Para sincronizar su agenda, use la siguiente información:"""
"sync url":"""URL:"""
"sync login":"""Usuario:"""
"sync password":"""PI:PASSWORD:<PASSWORD>END_PI:"""
"sync help":"""¿Esta usted perdido(a)? siga la"""
"sync help link":"""guía paso a paso!"""
"install the sync module":"""Instalar el módulo Sincronización desde la Apliteca Cozy"""
"connect to it and follow":"""Conectarse y seguir las instrucciones relativas a CalDAV."""
"some event fail to save":"""No se ha guardado un evento (ha ocurrido un error)"""
"imported events":"""Número de eventos importados"""
"import finished":"""La importación ha terminado"""
"import error occured for":"""Un error ha ocurrido al importar los siguientes elementos :"""
"export your calendar":"""Exportar su agenda"""
"please select existing calendar":"""Por favor seleccionar una agenda existente"""
"January":"""enero"""
"February":"""febrero"""
"March":"""marzo"""
"April":"""abril"""
"May":"""mayo"""
"June":"""junio"""
"July":"""julio"""
"August":"""agosto"""
"September":"""septiembre"""
"October":"""octubre"""
"November":"""noviembre"""
"December":"""diciembre"""
"Jan":"""ene"""
"Feb":"""feb"""
"Mar":"""mar"""
"Apr":"""abr"""
"Jun":"""jun"""
"Jul":"""jul"""
"Aug":"""ago"""
"Sep":"""sep"""
"Oct":"""oct"""
"Nov":"""nov"""
"Dec":"""dic"""
"calendar exist error":"""Una agenda llamada "Nueva agenda" ya existe."""
"email date format":"""DD/MM/AAAA [a] HH[h]mm"""
"email date format allday":"""DD/MM/AAAA [todo el día]"""
"email invitation title":"""Invitación a "%{description}\""""
"email invitation content":"""Buenos días, desearía invitarlo(a) al siguiente evento:
%{description} %{place}
el %{date}
¿Podríamos contar con su presencia?
Si
%{url}?status=ACCEPTED&key=%{key}
No
%{url}?status=DECLINED&key=%{key}"""
"email update title":"""El evento "%{description}" ha cambiado"""
"email update content":"""Un evento en el que usted participa se ha cambiado:
%{description} %{place}
el %{date}
Seguiré estando presente
%{url}?status=ACCEPTED&key=%{key}
No cuenten conmigo
%{url}?status=ACCEPTED&key=%{key}"""
"email delete title":"""Este evento ha sido anulado: %{description}"""
"email delete content":"""Este evento ha sido anulado:
%{description} %{place}
el %{date}"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.