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": " @conf.setCredentialsByURI base,\n username: pre.username\n password: pre.password\n email: pre",
"end": 873,
"score": 0.9894747734069824,
"start": 861,
"tag": "USERNAME",
"value": "pre.username"
},
{
"context": ",\n username: pre.username\n password: pre.password\n email: pre.email\n\n @log.verbose \"add",
"end": 904,
"score": 0.9992479681968689,
"start": 892,
"tag": "PASSWORD",
"value": "pre.password"
},
{
"context": "tch(/^[^@]+@[^\\.]+\\.[^\\.]+/)\n userobj =\n name: username\n password: password\n email: email\n _id: ",
"end": 1940,
"score": 0.7511360049247742,
"start": 1932,
"tag": "NAME",
"value": "username"
},
{
"context": ".]+/)\n userobj =\n name: username\n password: password\n email: email\n _id: \"org.couchdb.user:\" + u",
"end": 1963,
"score": 0.9990962743759155,
"start": 1955,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ".getCredentialsByURI(base)\n pre =\n username: c.username\n password: c.password\n email: c.email\n t",
"end": 2158,
"score": 0.8894679546356201,
"start": 2150,
"tag": "USERNAME",
"value": "username"
},
{
"context": "se)\n pre =\n username: c.username\n password: c.password\n email: c.email\n token: @conf.get(\"_token\")",
"end": 2183,
"score": 0.998914897441864,
"start": 2173,
"tag": "PASSWORD",
"value": "c.password"
},
{
"context": " @conf.setCredentialsByURI base,\n username: username\n password: password\n email: email\n\n",
"end": 2890,
"score": 0.9977577924728394,
"start": 2882,
"tag": "USERNAME",
"value": "username"
},
{
"context": "base,\n username: username\n password: password\n email: email\n\n return cb(error, data, ",
"end": 2917,
"score": 0.9987962245941162,
"start": 2909,
"tag": "PASSWORD",
"value": "password"
}
] | deps/npm/node_modules/npm-registry-client/lib/adduser.coffee | lxe/io.coffee | 0 | adduser = (base, username, password, email, cb) ->
# pluck off any other username/password/token. it needs to be the
# same as the user we're becoming now. replace them on error.
# if it worked, then we just created a new user, and all is well.
# but if we're updating a current record, then it'll 409 first
# must be trying to re-auth on a new machine.
# use this info as auth
done = (cb, pre) ->
# there was some kind of error, re-instate previous auth/token/etc.
((error, data, json, response) ->
return cb(error, data, json, response) if not error and (not response or response.statusCode is 201)
@conf.set "_token", pre.token
if @couchLogin
@couchLogin.token = pre.token
@couchLogin.tokenSet pre.token if @couchLogin.tokenSet
@conf.setCredentialsByURI base,
username: pre.username
password: pre.password
email: pre.email
@log.verbose "adduser", "back", [
error
data
json
]
error = new Error((response and response.statusCode or "") + " " + "Could not create user\n" + JSON.stringify(data)) unless error
@log.warn "adduser", "Incorrect username or password\n" + "You can reset your account by visiting:\n" + "\n" + " https://npmjs.org/forgot\n" if response and (response.statusCode is 401 or response.statusCode is 403)
cb error
).bind this
return cb(new Error("Required base URI not supplied")) unless base
username = ("" + (username or "")).trim()
return cb(new Error("No username supplied.")) unless username
password = ("" + (password or "")).trim()
return cb(new Error("No password supplied.")) unless password
email = ("" + (email or "")).trim()
return cb(new Error("No email address supplied.")) unless email
return cb(new Error("Please use a real email address.")) unless email.match(/^[^@]+@[^\.]+\.[^\.]+/)
userobj =
name: username
password: password
email: email
_id: "org.couchdb.user:" + username
type: "user"
roles: []
date: new Date().toISOString()
c = @conf.getCredentialsByURI(base)
pre =
username: c.username
password: c.password
email: c.email
token: @conf.get("_token")
@conf.del "_token"
@couchLogin.token = null if @couchLogin
cb = done.call(this, cb, pre)
logObj = Object.keys(userobj).map((k) ->
if k is "password"
return [
k
"XXXXX"
]
[
k
userobj[k]
]
).reduce((s, kv) ->
s[kv[0]] = kv[1]
s
, {})
@log.verbose "adduser", "before first PUT", logObj
uri = url.resolve(base, "/-/user/org.couchdb.user:" + encodeURIComponent(username))
@request "PUT", uri,
body: userobj
, ((error, data, json, response) ->
c = @conf.getCredentialsByURI(base)
if error and not c.auth
@conf.setCredentialsByURI base,
username: username
password: password
email: email
return cb(error, data, json, response) if not error or not response or response.statusCode isnt 409
@log.verbose "adduser", "update existing user"
@request "GET", uri + "?write=true", null, ((er, data, json, response) ->
return cb(er, data, json, response) if er or data.error
Object.keys(data).forEach (k) ->
userobj[k] = data[k] if not userobj[k] or k is "roles"
return
@log.verbose "adduser", "userobj", logObj
@request "PUT", uri + "/-rev/" + userobj._rev,
body: userobj
, cb
return
).bind(this)
).bind(this)
return
module.exports = adduser
url = require("url")
| 100134 | adduser = (base, username, password, email, cb) ->
# pluck off any other username/password/token. it needs to be the
# same as the user we're becoming now. replace them on error.
# if it worked, then we just created a new user, and all is well.
# but if we're updating a current record, then it'll 409 first
# must be trying to re-auth on a new machine.
# use this info as auth
done = (cb, pre) ->
# there was some kind of error, re-instate previous auth/token/etc.
((error, data, json, response) ->
return cb(error, data, json, response) if not error and (not response or response.statusCode is 201)
@conf.set "_token", pre.token
if @couchLogin
@couchLogin.token = pre.token
@couchLogin.tokenSet pre.token if @couchLogin.tokenSet
@conf.setCredentialsByURI base,
username: pre.username
password: <PASSWORD>
email: pre.email
@log.verbose "adduser", "back", [
error
data
json
]
error = new Error((response and response.statusCode or "") + " " + "Could not create user\n" + JSON.stringify(data)) unless error
@log.warn "adduser", "Incorrect username or password\n" + "You can reset your account by visiting:\n" + "\n" + " https://npmjs.org/forgot\n" if response and (response.statusCode is 401 or response.statusCode is 403)
cb error
).bind this
return cb(new Error("Required base URI not supplied")) unless base
username = ("" + (username or "")).trim()
return cb(new Error("No username supplied.")) unless username
password = ("" + (password or "")).trim()
return cb(new Error("No password supplied.")) unless password
email = ("" + (email or "")).trim()
return cb(new Error("No email address supplied.")) unless email
return cb(new Error("Please use a real email address.")) unless email.match(/^[^@]+@[^\.]+\.[^\.]+/)
userobj =
name: <NAME>
password: <PASSWORD>
email: email
_id: "org.couchdb.user:" + username
type: "user"
roles: []
date: new Date().toISOString()
c = @conf.getCredentialsByURI(base)
pre =
username: c.username
password: <PASSWORD>
email: c.email
token: @conf.get("_token")
@conf.del "_token"
@couchLogin.token = null if @couchLogin
cb = done.call(this, cb, pre)
logObj = Object.keys(userobj).map((k) ->
if k is "password"
return [
k
"XXXXX"
]
[
k
userobj[k]
]
).reduce((s, kv) ->
s[kv[0]] = kv[1]
s
, {})
@log.verbose "adduser", "before first PUT", logObj
uri = url.resolve(base, "/-/user/org.couchdb.user:" + encodeURIComponent(username))
@request "PUT", uri,
body: userobj
, ((error, data, json, response) ->
c = @conf.getCredentialsByURI(base)
if error and not c.auth
@conf.setCredentialsByURI base,
username: username
password: <PASSWORD>
email: email
return cb(error, data, json, response) if not error or not response or response.statusCode isnt 409
@log.verbose "adduser", "update existing user"
@request "GET", uri + "?write=true", null, ((er, data, json, response) ->
return cb(er, data, json, response) if er or data.error
Object.keys(data).forEach (k) ->
userobj[k] = data[k] if not userobj[k] or k is "roles"
return
@log.verbose "adduser", "userobj", logObj
@request "PUT", uri + "/-rev/" + userobj._rev,
body: userobj
, cb
return
).bind(this)
).bind(this)
return
module.exports = adduser
url = require("url")
| true | adduser = (base, username, password, email, cb) ->
# pluck off any other username/password/token. it needs to be the
# same as the user we're becoming now. replace them on error.
# if it worked, then we just created a new user, and all is well.
# but if we're updating a current record, then it'll 409 first
# must be trying to re-auth on a new machine.
# use this info as auth
done = (cb, pre) ->
# there was some kind of error, re-instate previous auth/token/etc.
((error, data, json, response) ->
return cb(error, data, json, response) if not error and (not response or response.statusCode is 201)
@conf.set "_token", pre.token
if @couchLogin
@couchLogin.token = pre.token
@couchLogin.tokenSet pre.token if @couchLogin.tokenSet
@conf.setCredentialsByURI base,
username: pre.username
password: PI:PASSWORD:<PASSWORD>END_PI
email: pre.email
@log.verbose "adduser", "back", [
error
data
json
]
error = new Error((response and response.statusCode or "") + " " + "Could not create user\n" + JSON.stringify(data)) unless error
@log.warn "adduser", "Incorrect username or password\n" + "You can reset your account by visiting:\n" + "\n" + " https://npmjs.org/forgot\n" if response and (response.statusCode is 401 or response.statusCode is 403)
cb error
).bind this
return cb(new Error("Required base URI not supplied")) unless base
username = ("" + (username or "")).trim()
return cb(new Error("No username supplied.")) unless username
password = ("" + (password or "")).trim()
return cb(new Error("No password supplied.")) unless password
email = ("" + (email or "")).trim()
return cb(new Error("No email address supplied.")) unless email
return cb(new Error("Please use a real email address.")) unless email.match(/^[^@]+@[^\.]+\.[^\.]+/)
userobj =
name: PI:NAME:<NAME>END_PI
password: PI:PASSWORD:<PASSWORD>END_PI
email: email
_id: "org.couchdb.user:" + username
type: "user"
roles: []
date: new Date().toISOString()
c = @conf.getCredentialsByURI(base)
pre =
username: c.username
password: PI:PASSWORD:<PASSWORD>END_PI
email: c.email
token: @conf.get("_token")
@conf.del "_token"
@couchLogin.token = null if @couchLogin
cb = done.call(this, cb, pre)
logObj = Object.keys(userobj).map((k) ->
if k is "password"
return [
k
"XXXXX"
]
[
k
userobj[k]
]
).reduce((s, kv) ->
s[kv[0]] = kv[1]
s
, {})
@log.verbose "adduser", "before first PUT", logObj
uri = url.resolve(base, "/-/user/org.couchdb.user:" + encodeURIComponent(username))
@request "PUT", uri,
body: userobj
, ((error, data, json, response) ->
c = @conf.getCredentialsByURI(base)
if error and not c.auth
@conf.setCredentialsByURI base,
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
email: email
return cb(error, data, json, response) if not error or not response or response.statusCode isnt 409
@log.verbose "adduser", "update existing user"
@request "GET", uri + "?write=true", null, ((er, data, json, response) ->
return cb(er, data, json, response) if er or data.error
Object.keys(data).forEach (k) ->
userobj[k] = data[k] if not userobj[k] or k is "roles"
return
@log.verbose "adduser", "userobj", logObj
@request "PUT", uri + "/-rev/" + userobj._rev,
body: userobj
, cb
return
).bind(this)
).bind(this)
return
module.exports = adduser
url = require("url")
|
[
{
"context": "a subobject', ->\n context = { author: { name: 'jonas' } }\n\n @render '''\n article\n - in ",
"end": 204,
"score": 0.9991446137428284,
"start": 199,
"tag": "NAME",
"value": "jonas"
},
{
"context": "le children', ->\n context = { author: { name: 'jonas' } }\n\n @render '''\n article\n - in ",
"end": 432,
"score": 0.9994509220123291,
"start": 427,
"tag": "NAME",
"value": "jonas"
},
{
"context": "ged', ->\n context = Serenade( author: { name: 'jonas' } )\n\n @render '''\n article\n - in ",
"end": 744,
"score": 0.999352216720581,
"start": 739,
"tag": "NAME",
"value": "jonas"
},
{
"context": "article > p#jonas')\n context.author = { name: \"peter\" }\n expect(@body).to.have.element('article > p",
"end": 930,
"score": 0.9984722137451172,
"start": 925,
"tag": "NAME",
"value": "peter"
},
{
"context": "ged', ->\n context = { author: Serenade( name: 'jonas' ) }\n\n @render '''\n article\n - in ",
"end": 1158,
"score": 0.9993607997894287,
"start": 1153,
"tag": "NAME",
"value": "jonas"
},
{
"context": "\n article\n - in $author\n p[id=@name]\n ''', context\n expect(@body).to.have.eleme",
"end": 1236,
"score": 0.8199326992034912,
"start": 1231,
"tag": "USERNAME",
"value": "@name"
},
{
"context": "t('article > p#jonas')\n context.author.name = 'peter'\n expect(@body).to.have.element('article > p#p",
"end": 1342,
"score": 0.99833744764328,
"start": 1337,
"tag": "NAME",
"value": "peter"
}
] | test/integration/in.spec.coffee | jnicklas/serenade.js | 1 | require './../spec_helper'
Serenade = require("../../lib/serenade")
describe 'In', ->
beforeEach ->
@setupDom()
it 'changes the context to a subobject', ->
context = { author: { name: 'jonas' } }
@render '''
article
- in $author
p[id=name]
''', context
expect(@body).to.have.element('article > p#jonas')
it 'can have multiple children', ->
context = { author: { name: 'jonas' } }
@render '''
article
- in $author
p[id=name]
div
''', context
expect(@body).to.have.element('article > p#jonas')
expect(@body).to.have.element('article > div')
it 'updates when the subobject is changed', ->
context = Serenade( author: { name: 'jonas' } )
@render '''
article
- in @author
p[id=name]
''', context
expect(@body).to.have.element('article > p#jonas')
context.author = { name: "peter" }
expect(@body).to.have.element('article > p#peter')
expect(@body).not.to.have.element('article > p#jonas')
it 'updates when a property on the subobject is changed', ->
context = { author: Serenade( name: 'jonas' ) }
@render '''
article
- in $author
p[id=@name]
''', context
expect(@body).to.have.element('article > p#jonas')
context.author.name = 'peter'
expect(@body).to.have.element('article > p#peter')
expect(@body).not.to.have.element('article > p#jonas')
| 42993 | require './../spec_helper'
Serenade = require("../../lib/serenade")
describe 'In', ->
beforeEach ->
@setupDom()
it 'changes the context to a subobject', ->
context = { author: { name: '<NAME>' } }
@render '''
article
- in $author
p[id=name]
''', context
expect(@body).to.have.element('article > p#jonas')
it 'can have multiple children', ->
context = { author: { name: '<NAME>' } }
@render '''
article
- in $author
p[id=name]
div
''', context
expect(@body).to.have.element('article > p#jonas')
expect(@body).to.have.element('article > div')
it 'updates when the subobject is changed', ->
context = Serenade( author: { name: '<NAME>' } )
@render '''
article
- in @author
p[id=name]
''', context
expect(@body).to.have.element('article > p#jonas')
context.author = { name: "<NAME>" }
expect(@body).to.have.element('article > p#peter')
expect(@body).not.to.have.element('article > p#jonas')
it 'updates when a property on the subobject is changed', ->
context = { author: Serenade( name: '<NAME>' ) }
@render '''
article
- in $author
p[id=@name]
''', context
expect(@body).to.have.element('article > p#jonas')
context.author.name = '<NAME>'
expect(@body).to.have.element('article > p#peter')
expect(@body).not.to.have.element('article > p#jonas')
| true | require './../spec_helper'
Serenade = require("../../lib/serenade")
describe 'In', ->
beforeEach ->
@setupDom()
it 'changes the context to a subobject', ->
context = { author: { name: 'PI:NAME:<NAME>END_PI' } }
@render '''
article
- in $author
p[id=name]
''', context
expect(@body).to.have.element('article > p#jonas')
it 'can have multiple children', ->
context = { author: { name: 'PI:NAME:<NAME>END_PI' } }
@render '''
article
- in $author
p[id=name]
div
''', context
expect(@body).to.have.element('article > p#jonas')
expect(@body).to.have.element('article > div')
it 'updates when the subobject is changed', ->
context = Serenade( author: { name: 'PI:NAME:<NAME>END_PI' } )
@render '''
article
- in @author
p[id=name]
''', context
expect(@body).to.have.element('article > p#jonas')
context.author = { name: "PI:NAME:<NAME>END_PI" }
expect(@body).to.have.element('article > p#peter')
expect(@body).not.to.have.element('article > p#jonas')
it 'updates when a property on the subobject is changed', ->
context = { author: Serenade( name: 'PI:NAME:<NAME>END_PI' ) }
@render '''
article
- in $author
p[id=@name]
''', context
expect(@body).to.have.element('article > p#jonas')
context.author.name = 'PI:NAME:<NAME>END_PI'
expect(@body).to.have.element('article > p#peter')
expect(@body).not.to.have.element('article > p#jonas')
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9992174506187439,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-fs-append-file.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
fs = require("fs")
join = require("path").join
filename = join(common.tmpDir, "append.txt")
common.error "appending to " + filename
currentFileData = "ABCD"
n = 220
s = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、" + "广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。" + "南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。" + "前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年," + "南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年," + "历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度," + "它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"
ncallbacks = 0
# test that empty file will be created and have content added
fs.appendFile filename, s, (e) ->
throw e if e
ncallbacks++
common.error "appended to file"
fs.readFile filename, (e, buffer) ->
throw e if e
common.error "file read"
ncallbacks++
assert.equal Buffer.byteLength(s), buffer.length
return
return
# test that appends data to a non empty file
filename2 = join(common.tmpDir, "append2.txt")
fs.writeFileSync filename2, currentFileData
fs.appendFile filename2, s, (e) ->
throw e if e
ncallbacks++
common.error "appended to file2"
fs.readFile filename2, (e, buffer) ->
throw e if e
common.error "file2 read"
ncallbacks++
assert.equal Buffer.byteLength(s) + currentFileData.length, buffer.length
return
return
# test that appendFile accepts buffers
filename3 = join(common.tmpDir, "append3.txt")
fs.writeFileSync filename3, currentFileData
buf = new Buffer(s, "utf8")
common.error "appending to " + filename3
fs.appendFile filename3, buf, (e) ->
throw e if e
ncallbacks++
common.error "appended to file3"
fs.readFile filename3, (e, buffer) ->
throw e if e
common.error "file3 read"
ncallbacks++
assert.equal buf.length + currentFileData.length, buffer.length
return
return
# test that appendFile accepts numbers.
filename4 = join(common.tmpDir, "append4.txt")
fs.writeFileSync filename4, currentFileData
common.error "appending to " + filename4
m = 0600
fs.appendFile filename4, n,
mode: m
, (e) ->
throw e if e
ncallbacks++
common.error "appended to file4"
# windows permissions aren't unix
if process.platform isnt "win32"
st = fs.statSync(filename4)
assert.equal st.mode & 0700, m
fs.readFile filename4, (e, buffer) ->
throw e if e
common.error "file4 read"
ncallbacks++
assert.equal Buffer.byteLength("" + n) + currentFileData.length, buffer.length
return
return
process.on "exit", ->
common.error "done"
assert.equal 8, ncallbacks
fs.unlinkSync filename
fs.unlinkSync filename2
fs.unlinkSync filename3
fs.unlinkSync filename4
return
| 104666 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
fs = require("fs")
join = require("path").join
filename = join(common.tmpDir, "append.txt")
common.error "appending to " + filename
currentFileData = "ABCD"
n = 220
s = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、" + "广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。" + "南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。" + "前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年," + "南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年," + "历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度," + "它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"
ncallbacks = 0
# test that empty file will be created and have content added
fs.appendFile filename, s, (e) ->
throw e if e
ncallbacks++
common.error "appended to file"
fs.readFile filename, (e, buffer) ->
throw e if e
common.error "file read"
ncallbacks++
assert.equal Buffer.byteLength(s), buffer.length
return
return
# test that appends data to a non empty file
filename2 = join(common.tmpDir, "append2.txt")
fs.writeFileSync filename2, currentFileData
fs.appendFile filename2, s, (e) ->
throw e if e
ncallbacks++
common.error "appended to file2"
fs.readFile filename2, (e, buffer) ->
throw e if e
common.error "file2 read"
ncallbacks++
assert.equal Buffer.byteLength(s) + currentFileData.length, buffer.length
return
return
# test that appendFile accepts buffers
filename3 = join(common.tmpDir, "append3.txt")
fs.writeFileSync filename3, currentFileData
buf = new Buffer(s, "utf8")
common.error "appending to " + filename3
fs.appendFile filename3, buf, (e) ->
throw e if e
ncallbacks++
common.error "appended to file3"
fs.readFile filename3, (e, buffer) ->
throw e if e
common.error "file3 read"
ncallbacks++
assert.equal buf.length + currentFileData.length, buffer.length
return
return
# test that appendFile accepts numbers.
filename4 = join(common.tmpDir, "append4.txt")
fs.writeFileSync filename4, currentFileData
common.error "appending to " + filename4
m = 0600
fs.appendFile filename4, n,
mode: m
, (e) ->
throw e if e
ncallbacks++
common.error "appended to file4"
# windows permissions aren't unix
if process.platform isnt "win32"
st = fs.statSync(filename4)
assert.equal st.mode & 0700, m
fs.readFile filename4, (e, buffer) ->
throw e if e
common.error "file4 read"
ncallbacks++
assert.equal Buffer.byteLength("" + n) + currentFileData.length, buffer.length
return
return
process.on "exit", ->
common.error "done"
assert.equal 8, ncallbacks
fs.unlinkSync filename
fs.unlinkSync filename2
fs.unlinkSync filename3
fs.unlinkSync filename4
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.
common = require("../common")
assert = require("assert")
fs = require("fs")
join = require("path").join
filename = join(common.tmpDir, "append.txt")
common.error "appending to " + filename
currentFileData = "ABCD"
n = 220
s = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、" + "广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。" + "南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。" + "前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年," + "南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年," + "历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度," + "它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"
ncallbacks = 0
# test that empty file will be created and have content added
fs.appendFile filename, s, (e) ->
throw e if e
ncallbacks++
common.error "appended to file"
fs.readFile filename, (e, buffer) ->
throw e if e
common.error "file read"
ncallbacks++
assert.equal Buffer.byteLength(s), buffer.length
return
return
# test that appends data to a non empty file
filename2 = join(common.tmpDir, "append2.txt")
fs.writeFileSync filename2, currentFileData
fs.appendFile filename2, s, (e) ->
throw e if e
ncallbacks++
common.error "appended to file2"
fs.readFile filename2, (e, buffer) ->
throw e if e
common.error "file2 read"
ncallbacks++
assert.equal Buffer.byteLength(s) + currentFileData.length, buffer.length
return
return
# test that appendFile accepts buffers
filename3 = join(common.tmpDir, "append3.txt")
fs.writeFileSync filename3, currentFileData
buf = new Buffer(s, "utf8")
common.error "appending to " + filename3
fs.appendFile filename3, buf, (e) ->
throw e if e
ncallbacks++
common.error "appended to file3"
fs.readFile filename3, (e, buffer) ->
throw e if e
common.error "file3 read"
ncallbacks++
assert.equal buf.length + currentFileData.length, buffer.length
return
return
# test that appendFile accepts numbers.
filename4 = join(common.tmpDir, "append4.txt")
fs.writeFileSync filename4, currentFileData
common.error "appending to " + filename4
m = 0600
fs.appendFile filename4, n,
mode: m
, (e) ->
throw e if e
ncallbacks++
common.error "appended to file4"
# windows permissions aren't unix
if process.platform isnt "win32"
st = fs.statSync(filename4)
assert.equal st.mode & 0700, m
fs.readFile filename4, (e, buffer) ->
throw e if e
common.error "file4 read"
ncallbacks++
assert.equal Buffer.byteLength("" + n) + currentFileData.length, buffer.length
return
return
process.on "exit", ->
common.error "done"
assert.equal 8, ncallbacks
fs.unlinkSync filename
fs.unlinkSync filename2
fs.unlinkSync filename3
fs.unlinkSync filename4
return
|
[
{
"context": "s a random quote from the simpsons\n#\n# Author:\n# jjasghar\n# omardelarosa\n#\n\n\n# Quotes Via: http://www.man",
"end": 288,
"score": 0.998824417591095,
"start": 280,
"tag": "USERNAME",
"value": "jjasghar"
},
{
"context": "ote from the simpsons\n#\n# Author:\n# jjasghar\n# omardelarosa\n#\n\n\n# Quotes Via: http://www.mandatory.com/2013/0",
"end": 305,
"score": 0.998617947101593,
"start": 293,
"tag": "USERNAME",
"value": "omardelarosa"
},
{
"context": "ousand guilty men go free than chase after them. -Chief Wiggum\",\n \"Well, crying isn't gonna bring him back, un",
"end": 499,
"score": 0.9826056361198425,
"start": 487,
"tag": "NAME",
"value": "Chief Wiggum"
},
{
"context": "back, or you can go out there and find your dog. -Homer Simpson\",\n \"Go out on a Tuesday? Who am I, Charlie Shee",
"end": 787,
"score": 0.9996543526649475,
"start": 774,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "Homer Simpson\",\n \"Go out on a Tuesday? Who am I, Charlie Sheen? -Marge Simpson\",\n \"It's all over, people! We d",
"end": 838,
"score": 0.9997848868370056,
"start": 825,
"tag": "NAME",
"value": "Charlie Sheen"
},
{
"context": " \"Go out on a Tuesday? Who am I, Charlie Sheen? -Marge Simpson\",\n \"It's all over, people! We don't have a pray",
"end": 854,
"score": 0.9997649788856506,
"start": 841,
"tag": "NAME",
"value": "Marge Simpson"
},
{
"context": "s all over, people! We don't have a prayer! -Reverend Lovejoy\",\n \"Now we play the waiting game...Ahh,",
"end": 917,
"score": 0.7030487656593323,
"start": 914,
"tag": "NAME",
"value": "end"
},
{
"context": "er, people! We don't have a prayer! -Reverend Lovejoy\",\n \"Now we play the waiting game...Ahh, the wai",
"end": 925,
"score": 0.5289376378059387,
"start": 922,
"tag": "NAME",
"value": "joy"
},
{
"context": "ing game sucks. Let's play Hungry Hungry Hippos! -Homer Simpson\",\n \"Trust me, Bart, it's better to walk in on b",
"end": 1039,
"score": 0.9979194402694702,
"start": 1026,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "ngry Hungry Hippos! -Homer Simpson\",\n \"Trust me, Bart, it's better to walk in on both your parents than",
"end": 1060,
"score": 0.9997317790985107,
"start": 1056,
"tag": "NAME",
"value": "Bart"
},
{
"context": "n on both your parents than on just one of them. -Milhouse Van Houten\",\n \"There's only one thing to do at a moment li",
"end": 1152,
"score": 0.9996545910835266,
"start": 1133,
"tag": "NAME",
"value": "Milhouse Van Houten"
},
{
"context": "ly one thing to do at a moment like this: strut! -Bart Simpson\",\n \"Unshrink you? Well that would require some ",
"end": 1231,
"score": 0.9997568130493164,
"start": 1219,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "t makes me want to laugh out loud and chortle... -Professor Frink\",\n \"Wait a minute. Bart's teacher is named 'Kra",
"end": 1403,
"score": 0.996649980545044,
"start": 1388,
"tag": "NAME",
"value": "Professor Frink"
},
{
"context": "d chortle... -Professor Frink\",\n \"Wait a minute. Bart's teacher is named 'Krabappel'? Oh, I've been cal",
"end": 1429,
"score": 0.999719500541687,
"start": 1425,
"tag": "NAME",
"value": "Bart"
},
{
"context": "ink\",\n \"Wait a minute. Bart's teacher is named 'Krabappel'? Oh, I've been calling her 'Crandall.' Why didn'",
"end": 1459,
"score": 0.9991715550422668,
"start": 1450,
"tag": "NAME",
"value": "Krabappel"
},
{
"context": "? Ohhh, I've been making an idiot out of myself! -Homer Simpson\",\n \"Boy, I tell ya, they only come out at night",
"end": 1588,
"score": 0.9985252618789673,
"start": 1575,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "me out at night. Or in this case, the daytime. -Chief Wiggum\",\n \"Hi, I'm Troy McClure. You might remember ",
"end": 1681,
"score": 0.5494309663772583,
"start": 1673,
"tag": "NAME",
"value": "ief Wigg"
},
{
"context": "his case, the daytime. -Chief Wiggum\",\n \"Hi, I'm Troy McClure. You might remember me from such self-help videos",
"end": 1710,
"score": 0.9998682141304016,
"start": 1698,
"tag": "NAME",
"value": "Troy McClure"
},
{
"context": "e Yourself Thin\\\" and \\\"Get Confident, Stupid.\\\" -Troy McClure\",\n \"I used to be with it, but then they changed",
"end": 1832,
"score": 0.9946487545967102,
"start": 1820,
"tag": "NAME",
"value": "Troy McClure"
},
{
"context": ". And what's \\\"it\\\" seems weird and scary to me. -Grampa Simpson\",\n \"It tastes like...burning. -Ralph Wiggum\",\n ",
"end": 1994,
"score": 0.9995160102844238,
"start": 1980,
"tag": "NAME",
"value": "Grampa Simpson"
},
{
"context": " -Grampa Simpson\",\n \"It tastes like...burning. -Ralph Wiggum\",\n \"This is a thousand monkeys working at a tho",
"end": 2040,
"score": 0.9993029236793518,
"start": 2028,
"tag": "NAME",
"value": "Ralph Wiggum"
},
{
"context": " was the \\\"blurst\\\" of times! You stupid monkey! -Mr. Burns\",\n \"We want chilly-willy! We want chilly-willy!",
"end": 2266,
"score": 0.9754232168197632,
"start": 2257,
"tag": "NAME",
"value": "Mr. Burns"
},
{
"context": "\n \"We want chilly-willy! We want chilly-willy! -Barney Gumble\",\n \"(on phone) Lord, give me guidance...That's ",
"end": 2331,
"score": 0.999761700630188,
"start": 2318,
"tag": "NAME",
"value": "Barney Gumble"
},
{
"context": "'s right, the guidance department. Thank you, Mrs. Lord. -Principal Skinner\",\n \"But look! I got some co",
"end": 2433,
"score": 0.7350019216537476,
"start": 2429,
"tag": "NAME",
"value": "Lord"
},
{
"context": "Alf pogs! Remember Alf? He's back...in pog form! -Milhouse Van Houten\",\n \"Ha ha wha. Oh, sorry I'm late. There was tr",
"end": 2561,
"score": 0.9996808767318726,
"start": 2542,
"tag": "NAME",
"value": "Milhouse Van Houten"
},
{
"context": "monkeys stole the glasses off my head. Wh-ha ha. -Professor Frink\",\n \"\\\"We the purple?\\\" What the hell was that? ",
"end": 2752,
"score": 0.9992216229438782,
"start": 2737,
"tag": "NAME",
"value": "Professor Frink"
},
{
"context": ", my eye! I'm not supposed to get pudding in it. -Lenny\",\n \"A philanthropist. A humanitarian. A man of ",
"end": 2900,
"score": 0.9649952054023743,
"start": 2895,
"tag": "NAME",
"value": "Lenny"
},
{
"context": "ho have come to spit on Montgomery Burns' grave. -Kent Brockman\",\n \"Sit perfectly still. Only I may dance. -Con",
"end": 3053,
"score": 0.9964259266853333,
"start": 3040,
"tag": "NAME",
"value": "Kent Brockman"
},
{
"context": "man\",\n \"Sit perfectly still. Only I may dance. -Conan O'Brien\",\n \"I wash myself with a rag on a stick. – Futu",
"end": 3113,
"score": 0.9997631907463074,
"start": 3100,
"tag": "NAME",
"value": "Conan O'Brien"
},
{
"context": "Brien\",\n \"I wash myself with a rag on a stick. – Future Bart Simpson\",\n \"People, please. We're all frightened and",
"end": 3175,
"score": 0.8835269212722778,
"start": 3159,
"tag": "NAME",
"value": "Future Bart Simp"
},
{
"context": "killer dolphins keep us from living and scoring! -Mayor Quimby\",\n \"My Homer is not a communist. He may be a li",
"end": 3317,
"score": 0.9352493286132812,
"start": 3305,
"tag": "NAME",
"value": "Mayor Quimby"
},
{
"context": "n idiot, a communist, but he is not a porn star. -Grampa Simpson\",\n \"Save me, Jebus! -Homer Simpson\",\n \"Bake h",
"end": 3443,
"score": 0.9850713610649109,
"start": 3429,
"tag": "NAME",
"value": "Grampa Simpson"
},
{
"context": "is not a porn star. -Grampa Simpson\",\n \"Save me, Jebus! -Homer Simpson\",\n \"Bake him away, toys. -Chief",
"end": 3464,
"score": 0.7873346209526062,
"start": 3459,
"tag": "NAME",
"value": "Jebus"
},
{
"context": "porn star. -Grampa Simpson\",\n \"Save me, Jebus! -Homer Simpson\",\n \"Bake him away, toys. -Chief Wiggum\",\n \"He",
"end": 3480,
"score": 0.9994696974754333,
"start": 3467,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "n\",\n \"Another day, another box of stolen pens. -Homer Simpson\",\n \"Feels like I'm wearing nothing at all...not",
"end": 3803,
"score": 0.9992542862892151,
"start": 3790,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "othing at all...nothing at all...nothing at all! -Ned Flanders\",\n \"Aren't we forgetting the true meaning of Ch",
"end": 3896,
"score": 0.8073745965957642,
"start": 3884,
"tag": "NAME",
"value": "Ned Flanders"
},
{
"context": "e true meaning of Christmas: the birth of Santa. -Bart Simpson\",\n \"I'd be mortified if someone ever made a lou",
"end": 3988,
"score": 0.999602198600769,
"start": 3976,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "ade a lousy product with the Simpson name on it. -Lisa Simpson\",\n \"Oh boy, dinnertime. The perfect break betwe",
"end": 4091,
"score": 0.9996554255485535,
"start": 4079,
"tag": "NAME",
"value": "Lisa Simpson"
},
{
"context": "rtime. The perfect break between work and drunk! -Homer Simpson\",\n \"I don't get mad, I get stabby. -Fat Tony\",\n",
"end": 4174,
"score": 0.9991042613983154,
"start": 4161,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "\"Inflammable means flammable? What a country. -Dr. Nick Riviera\",\n \"I can't believe you don't shut up! -Apu Nah",
"end": 4350,
"score": 0.9998468160629272,
"start": 4338,
"tag": "NAME",
"value": "Nick Riviera"
},
{
"context": " and night-swimming. It's a winning combination. –Lenny\",\n \"I would kill everyone in this room for a dr",
"end": 4488,
"score": 0.8416085839271545,
"start": 4483,
"tag": "NAME",
"value": "Lenny"
},
{
"context": " everyone in this room for a drop of sweet beer. -Homer Simpson\",\n \"My eyes! The goggles do nothing! -Rainier W",
"end": 4570,
"score": 0.9994874596595764,
"start": 4557,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " a mother's love, or the good kind of priceless? -Bart Simpson\",\n \"Science. What's science ever done for us? T",
"end": 4712,
"score": 0.9993009567260742,
"start": 4700,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": " -Moe the Bartender\",\n \"Chocolate microscopes? -Ralph Wiggum\",\n \"Oops, lost a nail. Well, that's leprosy for",
"end": 4830,
"score": 0.9995673298835754,
"start": 4818,
"tag": "NAME",
"value": "Ralph Wiggum"
},
{
"context": "Oops, lost a nail. Well, that's leprosy for you. -Mr. Burns\",\n \"I'm filled with piss and vinegar! At",
"end": 4889,
"score": 0.6092811226844788,
"start": 4887,
"tag": "NAME",
"value": "Mr"
},
{
"context": "s, lost a nail. Well, that's leprosy for you. -Mr. Burns\",\n \"I'm filled with piss and vinegar! At first,",
"end": 4896,
"score": 0.9786857962608337,
"start": 4891,
"tag": "NAME",
"value": "Burns"
},
{
"context": "negar! At first, I was just filled with vinegar. -Grampa Simpson\",\n \"Miss Simpson, do you find something funny a",
"end": 4994,
"score": 0.9979739189147949,
"start": 4980,
"tag": "NAME",
"value": "Grampa Simpson"
},
{
"context": "s just filled with vinegar. -Grampa Simpson\",\n \"Miss Simpson, do you find something funny about the word \\\"tro",
"end": 5013,
"score": 0.9806459546089172,
"start": 5001,
"tag": "NAME",
"value": "Miss Simpson"
},
{
"context": "nd something funny about the word \\\"tromboner\\\"? -Mr. Largo\",\n \"Ya used me, Skinner! YA USED ME! -Groundske",
"end": 5083,
"score": 0.8269160389900208,
"start": 5074,
"tag": "NAME",
"value": "Mr. Largo"
},
{
"context": "\"repeatedly,\\\" and replace \\\"dog\\\" with \\\"son.\\\" -Lionel Hutz\",\n \"I don't mind if you pee in the shower, but ",
"end": 5329,
"score": 0.9997928738594055,
"start": 5318,
"tag": "NAME",
"value": "Lionel Hutz"
},
{
"context": " the shower, but only if you're taking a shower. -Marge Simpson\",\n \"Hi, you've reached the Corey Hotline -- $4.",
"end": 5425,
"score": 0.9998347759246826,
"start": 5412,
"tag": "NAME",
"value": "Marge Simpson"
},
{
"context": "seeing is a total disregard for the things St. Patrick's Day stand for. All this drinking, violence, des",
"end": 5678,
"score": 0.8204831480979919,
"start": 5674,
"tag": "NAME",
"value": "rick"
},
{
"context": "e things we think of when we think of the Irish? -Kent Brockman\",\n \"Well, if by \\\"wank\\\" you mean educational f",
"end": 5825,
"score": 0.9988840222358704,
"start": 5812,
"tag": "NAME",
"value": "Kent Brockman"
},
{
"context": "imless crime. Like punching someone in the dark. -Nelson Muntz\",\n \"This is Papa Bear. Put out an APB for a mal",
"end": 6023,
"score": 0.9997282028198242,
"start": 6011,
"tag": "NAME",
"value": "Nelson Muntz"
},
{
"context": "tless. -Chief Wiggum\",\n \"Stupid sexy Flanders! -Homer Simpson\",\n \"Inside every hardened criminal beats the he",
"end": 6276,
"score": 0.9987905025482178,
"start": 6263,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " criminal beats the heart of a ten-year-old boy. -Bart Simpson\",\n \"It's not easy to juggle a pregnant wife and",
"end": 6366,
"score": 0.9991886615753174,
"start": 6354,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "how I managed to fit in eight hours of TV a day. -Homer Simpson\",\n \"Chat away. I'll just amuse myself with some",
"end": 6506,
"score": 0.9996663928031921,
"start": 6493,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "use myself with some pornographic playing cards. -Mayor Quimby\",\n \"When are they gonna get to the fireworks fa",
"end": 6598,
"score": 0.9994657635688782,
"start": 6586,
"tag": "NAME",
"value": "Mayor Quimby"
},
{
"context": "na get to the fireworks factory? (begins to cry) –Milhouse Van Houten\",\n \"Oh, loneliness and cheeseburgers are a dang",
"end": 6691,
"score": 0.999207079410553,
"start": 6672,
"tag": "NAME",
"value": "Milhouse Van Houten"
},
{
"context": "don't care doesn't mean that I don't understand. -Homer Simpson\",\n \"My bones are so brittle. But I always drink",
"end": 6948,
"score": 0.9996929168701172,
"start": 6935,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "so brittle. But I always drink plenty of...malk? -Bart Simpson\",\n \"Me fail English? That's unpossible. -Ralph ",
"end": 7030,
"score": 0.9997363090515137,
"start": 7018,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "impson\",\n \"Me fail English? That's unpossible. -Ralph Wiggum\",\n \"La...tex con...dome. Boy, I'd like to live ",
"end": 7086,
"score": 0.9998350739479065,
"start": 7074,
"tag": "NAME",
"value": "Ralph Wiggum"
},
{
"context": "n...dome. Boy, I'd like to live in one of those! -Grampa Simpson\",\n \"When a woman says nothing's wrong, that mea",
"end": 7168,
"score": 0.9994983673095703,
"start": 7154,
"tag": "NAME",
"value": "Grampa Simpson"
},
{
"context": " not funny, you'd better not laugh your ass off. -Homer Simpson\",\n \"Ironic, isn't it, Smithers? This anonymous ",
"end": 7410,
"score": 0.9997202157974243,
"start": 7397,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "ur ass off. -Homer Simpson\",\n \"Ironic, isn't it, Smithers? This anonymous clan of slack-jawed troglodytes h",
"end": 7443,
"score": 0.6231087446212769,
"start": 7435,
"tag": "NAME",
"value": "Smithers"
},
{
"context": "the one to go to jail. That's democracy for you. -Mr. Burns\",\n \"Oh boy. Looks like it's suicide again for m",
"end": 7628,
"score": 0.816515326499939,
"start": 7619,
"tag": "NAME",
"value": "Mr. Burns"
},
{
"context": " \"Oh boy. Looks like it's suicide again for me. -Moe the Bartender\",\n \"I'm trying to be a sensitive",
"end": 7684,
"score": 0.5429759621620178,
"start": 7682,
"tag": "NAME",
"value": "Mo"
},
{
"context": "ng to be a sensitive father, you unwanted moron! -Homer Simpson\",\n \"Talking out of turn...that's a paddling. Lo",
"end": 7777,
"score": 0.9995232820510864,
"start": 7764,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "noe...ooh, you better believe that's a paddling. -Jasper\",\n \"How can I prove we're live? Penis! -Kent Br",
"end": 7990,
"score": 0.9983464479446411,
"start": 7984,
"tag": "NAME",
"value": "Jasper"
},
{
"context": "addling. -Jasper\",\n \"How can I prove we're live? Penis! -Kent Brockman\",\n \"Now make like my pants, and",
"end": 8030,
"score": 0.7293688654899597,
"start": 8025,
"tag": "NAME",
"value": "Penis"
},
{
"context": "-Jasper\",\n \"How can I prove we're live? Penis! -Kent Brockman\",\n \"Now make like my pants, and split. -Comic B",
"end": 8046,
"score": 0.9995720982551575,
"start": 8033,
"tag": "NAME",
"value": "Kent Brockman"
},
{
"context": "m going to party like it's on sale for $19\",\n \"-Apu Nahasapeemapetilon\",\n \"You know, FOX turned into a hardcore sex ch",
"end": 8211,
"score": 0.8537967801094055,
"start": 8189,
"tag": "NAME",
"value": "Apu Nahasapeemapetilon"
},
{
"context": " sex channel so gradually, I didn't even notice. -Marge Simpson\",\n \"Ahh, there's nothing better than a cigarett",
"end": 8317,
"score": 0.9929325580596924,
"start": 8304,
"tag": "NAME",
"value": "Marge Simpson"
},
{
"context": "er had any goldfish. Then why'd I have the bowl, Bart? Why did I have the bowl? -Milhouse Van Houten\",\n",
"end": 8576,
"score": 0.722701907157898,
"start": 8573,
"tag": "NAME",
"value": "art"
},
{
"context": " I have the bowl, Bart? Why did I have the bowl? -Milhouse Van Houten\",\n \"Stupider like a fox! -Homer Simpson\",\n \"H",
"end": 8623,
"score": 0.9943402409553528,
"start": 8604,
"tag": "NAME",
"value": "Milhouse Van Houten"
},
{
"context": " -Milhouse Van Houten\",\n \"Stupider like a fox! -Homer Simpson\",\n \"Hey, look at my feet. You like those moccas",
"end": 8665,
"score": 0.999536395072937,
"start": 8652,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "tta here! Ever see a guy say good-bye to a shoe? -Hank Scorpio\",\n \"Uh, no you've got the wrong number. This is",
"end": 8905,
"score": 0.9793893694877625,
"start": 8893,
"tag": "NAME",
"value": "Hank Scorpio"
},
{
"context": " \"Yes, but I'd trade it all for a little more. -Mr. Burns\",\n \"What do you mean I can't take off my sweate",
"end": 9038,
"score": 0.9384959936141968,
"start": 9029,
"tag": "NAME",
"value": "Mr. Burns"
},
{
"context": " you mean I can't take off my sweater? I'm HOT! -Drunk Mr. Rogers\",\n \"I'm so hungry, I could eat at Arby's. -Sher",
"end": 9117,
"score": 0.8611190915107727,
"start": 9102,
"tag": "NAME",
"value": "runk Mr. Rogers"
},
{
"context": " God. Can't this town go one day without a riot? -Mayor Quimby\",\n \"By the time I got to a phone, my discovery ",
"end": 9255,
"score": 0.9833430051803589,
"start": 9243,
"tag": "NAME",
"value": "Mayor Quimby"
},
{
"context": "n I love a cold beer on a hot Christmas morning. -Homer Simpson\",\n \"My cat's breath smells like cat food. -Ralp",
"end": 9537,
"score": 0.999357283115387,
"start": 9524,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "pson\",\n \"My cat's breath smells like cat food. -Ralph Wiggum\",\n \"I didn't think it was physically possible, ",
"end": 9595,
"score": 0.9950452446937561,
"start": 9583,
"tag": "NAME",
"value": "Ralph Wiggum"
},
{
"context": "sically possible, but this both sucks and blows. -Bart Simpson\",\n \"Jesus must be spinning in his grave! -Barne",
"end": 9689,
"score": 0.9993436336517334,
"start": 9677,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "ut this both sucks and blows. -Bart Simpson\",\n \"Jesus must be spinning in his grave! -Barney Gumble\",\n ",
"end": 9701,
"score": 0.9975018501281738,
"start": 9696,
"tag": "NAME",
"value": "Jesus"
},
{
"context": "mpson\",\n \"Jesus must be spinning in his grave! -Barney Gumble\",\n \"I've been called ugly, pug ugly, fugly, pug",
"end": 9747,
"score": 0.9989938735961914,
"start": 9734,
"tag": "NAME",
"value": "Barney Gumble"
},
{
"context": "artender\",\n \"You don't win friends with salad. -Homer Simpson\",\n \"If he was going to commit a crime, would he",
"end": 9899,
"score": 0.9988712668418884,
"start": 9886,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " a strange man offers you a ride, I say take it! -Grampa Simpson\",\n \"Well, if it isn't my old friend, Mr. McGreg",
"end": 10207,
"score": 0.9987465739250183,
"start": 10193,
"tag": "NAME",
"value": "Grampa Simpson"
},
{
"context": "mpa Simpson\",\n \"Well, if it isn't my old friend, Mr. McGreg, with a leg for an arm, and an arm for a l",
"end": 10249,
"score": 0.9351406097412109,
"start": 10247,
"tag": "NAME",
"value": "Mr"
},
{
"context": "Simpson\",\n \"Well, if it isn't my old friend, Mr. McGreg, with a leg for an arm, and an arm for a leg. -Dr",
"end": 10257,
"score": 0.9700497984886169,
"start": 10251,
"tag": "NAME",
"value": "McGreg"
},
{
"context": " with a leg for an arm, and an arm for a leg. -Dr. Nick Riviera\",\n \"We're here! We're queer! We don't want any ",
"end": 10321,
"score": 0.9998708367347717,
"start": 10309,
"tag": "NAME",
"value": "Nick Riviera"
},
{
"context": " \"Shut up, brain, or I'll stab you with a Q-tip! -Homer Simpson\",\n \"Everything's coming up Milhouse! -Milhouse ",
"end": 10463,
"score": 0.998603880405426,
"start": 10450,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " Simpson\",\n \"Everything's coming up Milhouse! -Milhouse Van Houten\",\n \"I was saying \\\"Boo-urns.\\\" -Hans",
"end": 10512,
"score": 0.668570876121521,
"start": 10505,
"tag": "NAME",
"value": "ilhouse"
},
{
"context": " \"Everything's coming up Milhouse! -Milhouse Van Houten\",\n \"I was saying \\\"Boo-urns.\\\" -Hans Moleman\",\n",
"end": 10523,
"score": 0.7270531058311462,
"start": 10518,
"tag": "NAME",
"value": "outen"
},
{
"context": "ouse Van Houten\",\n \"I was saying \\\"Boo-urns.\\\" -Hans Moleman\",\n \"I can't promise I'll try, but I'll try to t",
"end": 10570,
"score": 0.9996811747550964,
"start": 10558,
"tag": "NAME",
"value": "Hans Moleman"
},
{
"context": " \"I can't promise I'll try, but I'll try to try. -Bart Simpson\",\n \"To alcohol! The cause of, and solution to, ",
"end": 10637,
"score": 0.9989901781082153,
"start": 10625,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "use of, and solution to, all of life's problems. -Homer Simpson\",\n \"Oh boy, Liver! Iron helps us play! -Rod and",
"end": 10725,
"score": 0.9985768795013428,
"start": 10712,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "er know the simple joys of a monkey knife fight. -Homer Simpson\",\n \"Beer. Now there's a temporary solution. -Ho",
"end": 10926,
"score": 0.9984643459320068,
"start": 10913,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "on\",\n \"Beer. Now there's a temporary solution. -Homer Simpson\",\n \"All right, brain. You don't like me and I d",
"end": 10987,
"score": 0.9986185431480408,
"start": 10974,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "his and I can get back to killing you with beer. -Homer Simpson\",\n \"And how is education supposed to make me fe",
"end": 11134,
"score": 0.997923731803894,
"start": 11121,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "me winemaking course, and I forgot how to drive? -Homer Simpson\",\n \"I hope I didn't brain my damage. -Homer Sim",
"end": 11372,
"score": 0.9990662336349487,
"start": 11359,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "r Simpson\",\n \"I hope I didn't brain my damage. -Homer Simpson\",\n \"Oh, Lisa, you and your stories: Bart's a va",
"end": 11426,
"score": 0.999531626701355,
"start": 11413,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "I didn't brain my damage. -Homer Simpson\",\n \"Oh, Lisa, you and your stories: Bart's a vampire, beer kil",
"end": 11441,
"score": 0.995681881904602,
"start": 11437,
"tag": "NAME",
"value": "Lisa"
},
{
"context": "omer Simpson\",\n \"Oh, Lisa, you and your stories: Bart's a vampire, beer kills brain cells. Now let's go",
"end": 11469,
"score": 0.9612082242965698,
"start": 11465,
"tag": "NAME",
"value": "Bart"
},
{
"context": "lding... thingie... where our beds and TV... is. -Homer Simpson\",\n \"What are you gonna do? Sick your dogs on me",
"end": 11602,
"score": 0.9995625615119934,
"start": 11589,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "r mouth so when they bark they shoot bees at me? -Homer Simpson\",\n \"I have misplaced my pants. -Homer Simpson\",",
"end": 11756,
"score": 0.9994747638702393,
"start": 11743,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " -Homer Simpson\",\n \"I have misplaced my pants. -Homer Simpson\",\n \"Mmmm, 52 slices of American cheese. -Homer ",
"end": 11804,
"score": 0.9995943307876587,
"start": 11791,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "impson\",\n \"Mmmm, 52 slices of American cheese. -Homer Simpson\",\n \"Mmmm, forbidden donut. -Homer Simpson\",\n ",
"end": 11861,
"score": 0.9994471073150635,
"start": 11848,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "ese. -Homer Simpson\",\n \"Mmmm, forbidden donut. -Homer Simpson\",\n \"Mmmm, free goo. -Homer Simpson\",\n \"Mmmm, ",
"end": 11905,
"score": 0.9995419383049011,
"start": 11892,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "dden donut. -Homer Simpson\",\n \"Mmmm, free goo. -Homer Simpson\",\n \"Mmmm, Gummy-beer. -Homer Simpson\",\n \"Mmmm",
"end": 11942,
"score": 0.9994910359382629,
"start": 11929,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "free goo. -Homer Simpson\",\n \"Mmmm, Gummy-beer. -Homer Simpson\",\n \"Mmmm, purple. -Homer Simpson\",\n \"Mmmm, sa",
"end": 11981,
"score": 0.9995131492614746,
"start": 11968,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": ", Gummy-beer. -Homer Simpson\",\n \"Mmmm, purple. -Homer Simpson\",\n \"Mmmm, sacrilicious. -Homer Simpson\",\n \"Mm",
"end": 12016,
"score": 0.9992029666900635,
"start": 12003,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "purple. -Homer Simpson\",\n \"Mmmm, sacrilicious. -Homer Simpson\",\n \"Mmmm...fuzzy. -Homer Simpson\",\n \"Mmmm...o",
"end": 12057,
"score": 0.999430775642395,
"start": 12044,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "sacrilicious. -Homer Simpson\",\n \"Mmmm...fuzzy. -Homer Simpson\",\n \"Mmmm...open faced club sand wedge. -Homer S",
"end": 12092,
"score": 0.9993758797645569,
"start": 12079,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "Simpson\",\n \"Mmmm...open faced club sand wedge. -Homer Simpson\",\n \"Duff Man can't breathe! Oh no! -Duff Man\",\n",
"end": 12148,
"score": 0.9991084933280945,
"start": 12135,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "here I put my beverage or, if you will, cupcake. -Homer Simpson\",\n \"My eyes. The goggles, they do nothing. -Rad",
"end": 12563,
"score": 0.9993230104446411,
"start": 12550,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "face, and for what? -Moe the Bartender\",\n \"Hello Simpson. I'm riding the bus today because Mother hid my c",
"end": 12792,
"score": 0.9992006421089172,
"start": 12785,
"tag": "NAME",
"value": "Simpson"
},
{
"context": " You're going to give yourself a skin failure. -Dr Nick Riviera\",\n \"In his house, we obey the laws of thermodyn",
"end": 13026,
"score": 0.9998141527175903,
"start": 13014,
"tag": "NAME",
"value": "Nick Riviera"
},
{
"context": "n his house, we obey the laws of thermodynamics. -Homer Simpson\",\n \"Y'ello? You'll have to speak up, I'm wearin",
"end": 13097,
"score": 0.9996635913848877,
"start": 13084,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "o? You'll have to speak up, I'm wearing a towel. -Homer Simpson\",\n \"Hmm. Your ideas are intriguing to me and I ",
"end": 13172,
"score": 0.9996709823608398,
"start": 13159,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "o me and I wish to subscribe to your newsletter. -Homer Simpson\",\n \"I don't even believe in Jebus! Save me Jebu",
"end": 13274,
"score": 0.9996835589408875,
"start": 13261,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " \"I don't even believe in Jebus! Save me Jebus! -Homer Simpson\",\n \"There's a 4:30 in the morning now? -Bart Si",
"end": 13341,
"score": 0.9996392726898193,
"start": 13328,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "Simpson\",\n \"There's a 4:30 in the morning now? -Bart Simpson\",\n \"Oh wow, windows. I don't think I could affo",
"end": 13396,
"score": 0.9996083378791809,
"start": 13384,
"tag": "NAME",
"value": "Bart Simpson"
},
{
"context": "imless crime, like punching someone in the dark. -Nelson Munz\",\n \"Can't we have one meeting that doesn't end ",
"end": 13555,
"score": 0.9998254179954529,
"start": 13544,
"tag": "NAME",
"value": "Nelson Munz"
},
{
"context": "ng that doesn't end with us digging up a corpse? -Mayor Quimby\",\n \"Um, can you repeat the part of the stuff...",
"end": 13647,
"score": 0.9996965527534485,
"start": 13635,
"tag": "NAME",
"value": "Mayor Quimby"
},
{
"context": "e stuff...where you said about all the...things? -Homer Simpson\",\n \"Honey, if we didn't turn it down for the co",
"end": 13750,
"score": 0.9993391036987305,
"start": 13737,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "n it down for the cops, what chance do you have? -Homer Simpson\",\n \"Oh boy, sleep! That's where I'm a Viking! -",
"end": 13843,
"score": 0.9994151592254639,
"start": 13830,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "\",\n \"Oh boy, sleep! That's where I'm a Viking! -Ralph Wiggum\",\n \"A shiny new donkey to the man who brings me",
"end": 13905,
"score": 0.9996476173400879,
"start": 13893,
"tag": "NAME",
"value": "Ralph Wiggum"
},
{
"context": "ny new donkey to the man who brings me the head of Homer Simpson! -Mr Burns\",\n \"Sure, I'm flattered, maybe even ",
"end": 13981,
"score": 0.9991973638534546,
"start": 13968,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "the man who brings me the head of Homer Simpson! -Mr Burns\",\n \"Sure, I'm flattered, maybe even a little cu",
"end": 13992,
"score": 0.9945115447044373,
"start": 13984,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "ybe even a little curious, but the answer is no! -Homer Simpson\",\n \"Oh, if only we'd listened to that young man",
"end": 14085,
"score": 0.9995750784873962,
"start": 14072,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": "ad of walling him up in the abandoned coke oven. -Mr Burns\",\n \"You've made a powerful enemy today, my frie",
"end": 14200,
"score": 0.8934997916221619,
"start": 14192,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": " \"You've made a powerful enemy today, my friend. -Mr Burns\",\n \"All right, let's make this sporting, Leonar",
"end": 14263,
"score": 0.9884667992591858,
"start": 14255,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "thout using the letter e, you can keep your job. -Mr Burns\",\n \"Okay Mr. Burns Here are your messages: You ",
"end": 14420,
"score": 0.9653823375701904,
"start": 14412,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "ter e, you can keep your job. -Mr Burns\",\n \"Okay Mr. Burns Here are your messages: You have thirty minutes t",
"end": 14441,
"score": 0.9628700017929077,
"start": 14432,
"tag": "NAME",
"value": "Mr. Burns"
},
{
"context": "cube. You have thirty minutes to move your cube. -Homer Simpson\",\n \"Ooh, don't poo-poo a nickel, Lisa. A nickel",
"end": 14672,
"score": 0.9983968734741211,
"start": 14659,
"tag": "NAME",
"value": "Homer Simpson"
},
{
"context": " -Homer Simpson\",\n \"Ooh, don't poo-poo a nickel, Lisa. A nickel will buy you a steak and kidney pie, a ",
"end": 14712,
"score": 0.9994421005249023,
"start": 14708,
"tag": "NAME",
"value": "Lisa"
},
{
"context": "e trolley from Battery Park to the polo grounds. -Mr Burns\",\n \"Oh, so mother nature needs a favor? Well, m",
"end": 14914,
"score": 0.9817217588424683,
"start": 14906,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": " us with droughts and floods and poison monkeys. -Mr Burns\",\n \"Release the hounds. -Mr Burns\",\n \"I'm afr",
"end": 15081,
"score": 0.98656165599823,
"start": 15073,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "son monkeys. -Mr Burns\",\n \"Release the hounds. -Mr Burns\",\n \"I'm afraid all of those players have retire",
"end": 15117,
"score": 0.9916710257530212,
"start": 15109,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "er has been dead for a hundred and thirty years. -Mr Smithers\",\n \"Smithers, this monkey is going to need most",
"end": 15277,
"score": 0.9571783542633057,
"start": 15266,
"tag": "NAME",
"value": "Mr Smithers"
},
{
"context": "or a hundred and thirty years. -Mr Smithers\",\n \"Smithers, this monkey is going to need most of your skin. ",
"end": 15292,
"score": 0.9894552826881409,
"start": 15284,
"tag": "NAME",
"value": "Smithers"
},
{
"context": " this monkey is going to need most of your skin. -Mr Burns\",\n \"Now to enjoy the Miami of Canada: Chicago. ",
"end": 15351,
"score": 0.9921037554740906,
"start": 15343,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": ",\n \"Now to enjoy the Miami of Canada: Chicago. -Mr Burns\",\n \"I'm afraid it's not that simple. As punishm",
"end": 15410,
"score": 0.9896580576896667,
"start": 15402,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "ion, it's company policy to give you the plague. -Mr Burns\"\n \"Oh, Smithers. I would have said anything to ",
"end": 15537,
"score": 0.9799968600273132,
"start": 15529,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": " policy to give you the plague. -Mr Burns\"\n \"Oh, Smithers. I would have said anything to get your stem cell",
"end": 15555,
"score": 0.9964088201522827,
"start": 15547,
"tag": "NAME",
"value": "Smithers"
},
{
"context": "would have said anything to get your stem cells. -Mr Burns\",\n \"Oh, balderdash. It's not important how old ",
"end": 15617,
"score": 0.9697184562683105,
"start": 15609,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "parchment, it's how old you feel in the humours! -Mr Burns\",\n \"Compadres, it is imperative that we crush t",
"end": 15736,
"score": 0.9843880534172058,
"start": 15728,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": " whomever brings me the head of Colonel Montoya. -Mr Burns\",\n \"Have the Rolling Stones killed. -Mr Burns\",",
"end": 15938,
"score": 0.9658088088035583,
"start": 15930,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": " -Mr Burns\",\n \"Have the Rolling Stones killed. -Mr Burns\",\n \"I don't know why. It's a perfectly cromulen",
"end": 15986,
"score": 0.9826582670211792,
"start": 15978,
"tag": "NAME",
"value": "Mr Burns"
},
{
"context": "don't know why. It's a perfectly cromulent word. -Miss Hoover\",\n \"Roads closed, pipes frozen, albinos...virtu",
"end": 16056,
"score": 0.9933562278747559,
"start": 16045,
"tag": "NAME",
"value": "Miss Hoover"
},
{
"context": " from Winter Wonderland to a Class 3 Kill-Storm. -Kent Brockman\",\n \"Oh, I have had it, I have had it with this ",
"end": 16240,
"score": 0.9991281628608704,
"start": 16227,
"tag": "NAME",
"value": "Kent Brockman"
},
{
"context": "show you we're serious...you have 12 hours. -Fat Tony\",\n \"I can't wait to eat that monkey. -Grandpa S",
"end": 16501,
"score": 0.5948599576950073,
"start": 16498,
"tag": "NAME",
"value": "ony"
},
{
"context": "-Fat Tony\",\n \"I can't wait to eat that monkey. -Grandpa Simpson\",\n \"Uh, did I say corpse hatch? I meant innocen",
"end": 16557,
"score": 0.9900048971176147,
"start": 16542,
"tag": "NAME",
"value": "Grandpa Simpson"
},
{
"context": " did I say corpse hatch? I meant innocence tube. -Mr Burns\"\n]\n\nmodule.exports = (robot) ->\n robot.respond /",
"end": 16625,
"score": 0.8461195230484009,
"start": 16617,
"tag": "USERNAME",
"value": "Mr Burns"
}
] | src/thesimpsons.coffee | omardelarosa/hubot-thesimpsons | 18 | # Description
# A Simpsons Quote and Image Generator for Hubots.
#
# Configuration:
# None
#
# Commands:
# hubot simpsons image me - displays a random image from imgur.com/r/TheSimpsons
# hubot simpsons quote me - displays a random quote from the simpsons
#
# Author:
# jjasghar
# omardelarosa
#
# Quotes Via: http://www.mandatory.com/2013/02/12/the-100-greatest-quotes-from-the-simpsons/
quotes = [
"I'd rather let a thousand guilty men go free than chase after them. -Chief Wiggum",
"Well, crying isn't gonna bring him back, unless your tears smell like dog food. So you can either sit there crying and eating can after can of dog food until your tears smell enough like dog food to make your dog come back, or you can go out there and find your dog. -Homer Simpson",
"Go out on a Tuesday? Who am I, Charlie Sheen? -Marge Simpson",
"It's all over, people! We don't have a prayer! -Reverend Lovejoy",
"Now we play the waiting game...Ahh, the waiting game sucks. Let's play Hungry Hungry Hippos! -Homer Simpson",
"Trust me, Bart, it's better to walk in on both your parents than on just one of them. -Milhouse Van Houten",
"There's only one thing to do at a moment like this: strut! -Bart Simpson",
"Unshrink you? Well that would require some sort of a Rebigulator, which is a concept so ridiculous it makes me want to laugh out loud and chortle... -Professor Frink",
"Wait a minute. Bart's teacher is named 'Krabappel'? Oh, I've been calling her 'Crandall.' Why didn't anyone tell me? Ohhh, I've been making an idiot out of myself! -Homer Simpson",
"Boy, I tell ya, they only come out at night. Or in this case, the daytime. -Chief Wiggum",
"Hi, I'm Troy McClure. You might remember me from such self-help videos as \"Smoke Yourself Thin\" and \"Get Confident, Stupid.\" -Troy McClure",
"I used to be with it, but then they changed what \"it\" was, and now what I'm with isn't it. And what's \"it\" seems weird and scary to me. -Grampa Simpson",
"It tastes like...burning. -Ralph Wiggum",
"This is a thousand monkeys working at a thousand typewriters. Soon they'll have written the greatest novel known to man. Let's see. It was the best of times, it was the \"blurst\" of times! You stupid monkey! -Mr. Burns",
"We want chilly-willy! We want chilly-willy! -Barney Gumble",
"(on phone) Lord, give me guidance...That's right, the guidance department. Thank you, Mrs. Lord. -Principal Skinner",
"But look! I got some cool pogs: Alf pogs! Remember Alf? He's back...in pog form! -Milhouse Van Houten",
"Ha ha wha. Oh, sorry I'm late. There was trouble at the lab with the running and the exploding and the crying when the monkeys stole the glasses off my head. Wh-ha ha. -Professor Frink",
"\"We the purple?\" What the hell was that? –Father of losing child contestant",
"Ow, my eye! I'm not supposed to get pudding in it. -Lenny",
"A philanthropist. A humanitarian. A man of peace. These are just a few of the men who have come to spit on Montgomery Burns' grave. -Kent Brockman",
"Sit perfectly still. Only I may dance. -Conan O'Brien",
"I wash myself with a rag on a stick. – Future Bart Simpson",
"People, please. We're all frightened and horny, but we can't let some killer dolphins keep us from living and scoring! -Mayor Quimby",
"My Homer is not a communist. He may be a liar, a pig, an idiot, a communist, but he is not a porn star. -Grampa Simpson",
"Save me, Jebus! -Homer Simpson",
"Bake him away, toys. -Chief Wiggum",
"Hey, everybody! I'm a stupid moron with an ugly face and big butt and my butt smells and...I like to kiss my own butt. -Moe the Bartender",
"Does anybody hear me complaining about the breasts? -Krusty the Clown",
"Another day, another box of stolen pens. -Homer Simpson",
"Feels like I'm wearing nothing at all...nothing at all...nothing at all! -Ned Flanders",
"Aren't we forgetting the true meaning of Christmas: the birth of Santa. -Bart Simpson",
"I'd be mortified if someone ever made a lousy product with the Simpson name on it. -Lisa Simpson",
"Oh boy, dinnertime. The perfect break between work and drunk! -Homer Simpson",
"I don't get mad, I get stabby. -Fat Tony",
"Tonight, on \"Wings\"... ah, who cares? -TV Announcer",
"Inflammable means flammable? What a country. -Dr. Nick Riviera",
"I can't believe you don't shut up! -Apu Nahasapeemapetilon",
"Ah, alcohol and night-swimming. It's a winning combination. –Lenny",
"I would kill everyone in this room for a drop of sweet beer. -Homer Simpson",
"My eyes! The goggles do nothing! -Rainier Wolfcastle",
"Priceless like a mother's love, or the good kind of priceless? -Bart Simpson",
"Science. What's science ever done for us? TV off. -Moe the Bartender",
"Chocolate microscopes? -Ralph Wiggum",
"Oops, lost a nail. Well, that's leprosy for you. -Mr. Burns",
"I'm filled with piss and vinegar! At first, I was just filled with vinegar. -Grampa Simpson",
"Miss Simpson, do you find something funny about the word \"tromboner\"? -Mr. Largo",
"Ya used me, Skinner! YA USED ME! -Groundskeeper Willie",
"Well, he's kind of had it in for me ever since I accidently ran over his dog. Actually, replace \"accidently\" with \"repeatedly,\" and replace \"dog\" with \"son.\" -Lionel Hutz",
"I don't mind if you pee in the shower, but only if you're taking a shower. -Marge Simpson",
"Hi, you've reached the Corey Hotline -- $4.95 a minute. Here are some words that rhyme with Corey: gory, story, allegory, Montessori... -Corey Hotline",
"Ladies and gentlemen, what you are seeing is a total disregard for the things St. Patrick's Day stand for. All this drinking, violence, destruction of property. Are these the things we think of when we think of the Irish? -Kent Brockman",
"Well, if by \"wank\" you mean educational fun, then stand back, it's wanking time! -Principal Skinner",
"Shoplifting is a victimless crime. Like punching someone in the dark. -Nelson Muntz",
"This is Papa Bear. Put out an APB for a male suspect, driving a...car of some sort, heading in the direction of...you know, that place that sells chili. Suspect is hatless. Repeat, hatless. -Chief Wiggum",
"Stupid sexy Flanders! -Homer Simpson",
"Inside every hardened criminal beats the heart of a ten-year-old boy. -Bart Simpson",
"It's not easy to juggle a pregnant wife and a troubled child, but somehow I managed to fit in eight hours of TV a day. -Homer Simpson",
"Chat away. I'll just amuse myself with some pornographic playing cards. -Mayor Quimby",
"When are they gonna get to the fireworks factory? (begins to cry) –Milhouse Van Houten",
"Oh, loneliness and cheeseburgers are a dangerous mix. -Comic Book Guy",
"Skinner said the teachers will crack any minute purple monkey dishwasher. –Random Teacher",
"Just because I don't care doesn't mean that I don't understand. -Homer Simpson",
"My bones are so brittle. But I always drink plenty of...malk? -Bart Simpson",
"Me fail English? That's unpossible. -Ralph Wiggum",
"La...tex con...dome. Boy, I'd like to live in one of those! -Grampa Simpson",
"When a woman says nothing's wrong, that means everything's wrong. And when a woman says everything's wrong, that means everything's wrong. And when a woman says something's not funny, you'd better not laugh your ass off. -Homer Simpson",
"Ironic, isn't it, Smithers? This anonymous clan of slack-jawed troglodytes has cost me the election. And yet, if I were to have them killed, I would be the one to go to jail. That's democracy for you. -Mr. Burns",
"Oh boy. Looks like it's suicide again for me. -Moe the Bartender",
"I'm trying to be a sensitive father, you unwanted moron! -Homer Simpson",
"Talking out of turn...that's a paddling. Looking out the window...that's a paddling. Staring at my sandals...that's a paddling. Paddling the school canoe...ooh, you better believe that's a paddling. -Jasper",
"How can I prove we're live? Penis! -Kent Brockman",
"Now make like my pants, and split. -Comic Book Guy",
"For the next five minutes, I'm going to party like it's on sale for $19",
"-Apu Nahasapeemapetilon",
"You know, FOX turned into a hardcore sex channel so gradually, I didn't even notice. -Marge Simpson",
"Ahh, there's nothing better than a cigarette... unless it's a cigarette lit with a hundred-dollar bill. -Krusty the Clown",
"Remember the time he ate my goldfish, and you lied to me and said I never had any goldfish. Then why'd I have the bowl, Bart? Why did I have the bowl? -Milhouse Van Houten",
"Stupider like a fox! -Homer Simpson",
"Hey, look at my feet. You like those moccasins? Look in your closet; there's a pair for you. Don't like them? Then neither do I! [throws them out the door] Get the hell outta here! Ever see a guy say good-bye to a shoe? -Hank Scorpio",
"Uh, no you've got the wrong number. This is 9-1... -Chief Wiggum",
"Yes, but I'd trade it all for a little more. -Mr. Burns",
"What do you mean I can't take off my sweater? I'm HOT! -Drunk Mr. Rogers",
"I'm so hungry, I could eat at Arby's. -Sherri or Terri",
"Oh, dear God. Can't this town go one day without a riot? -Mayor Quimby",
"By the time I got to a phone, my discovery had already been reported by Principal Kohoutek. I got back at him, though...him and that little boy of his. -Principal Skinner",
"You must love this country more than I love a cold beer on a hot Christmas morning. -Homer Simpson",
"My cat's breath smells like cat food. -Ralph Wiggum",
"I didn't think it was physically possible, but this both sucks and blows. -Bart Simpson",
"Jesus must be spinning in his grave! -Barney Gumble",
"I've been called ugly, pug ugly, fugly, pug fugly, but never ugly ugly. -Moe the Bartender",
"You don't win friends with salad. -Homer Simpson",
"If he was going to commit a crime, would he have invited the number one cop in town? Now where did I put my gun? Oh yeah, I set it down when I got a piece of cake. -Chief Wiggum",
"Homer, you're as dumb as a mule and twice as ugly. If a strange man offers you a ride, I say take it! -Grampa Simpson",
"Well, if it isn't my old friend, Mr. McGreg, with a leg for an arm, and an arm for a leg. -Dr. Nick Riviera",
"We're here! We're queer! We don't want any more bears! -Townspeople",
"Shut up, brain, or I'll stab you with a Q-tip! -Homer Simpson",
"Everything's coming up Milhouse! -Milhouse Van Houten",
"I was saying \"Boo-urns.\" -Hans Moleman",
"I can't promise I'll try, but I'll try to try. -Bart Simpson",
"To alcohol! The cause of, and solution to, all of life's problems. -Homer Simpson",
"Oh boy, Liver! Iron helps us play! -Rod and Todd",
"Look at those poor saps back on land with their laws and ethics! They'll never know the simple joys of a monkey knife fight. -Homer Simpson",
"Beer. Now there's a temporary solution. -Homer Simpson",
"All right, brain. You don't like me and I don't like you, but let's just do this and I can get back to killing you with beer. -Homer Simpson",
"And how is education supposed to make me feel smarter? Besides, every time I learn something new, it pushes some old stuff out of my brain. Remember when I took that home winemaking course, and I forgot how to drive? -Homer Simpson",
"I hope I didn't brain my damage. -Homer Simpson",
"Oh, Lisa, you and your stories: Bart's a vampire, beer kills brain cells. Now let's go back to that... building... thingie... where our beds and TV... is. -Homer Simpson",
"What are you gonna do? Sick your dogs on me? Or your bees? Or dogs with bees in their mouth so when they bark they shoot bees at me? -Homer Simpson",
"I have misplaced my pants. -Homer Simpson",
"Mmmm, 52 slices of American cheese. -Homer Simpson",
"Mmmm, forbidden donut. -Homer Simpson",
"Mmmm, free goo. -Homer Simpson",
"Mmmm, Gummy-beer. -Homer Simpson",
"Mmmm, purple. -Homer Simpson",
"Mmmm, sacrilicious. -Homer Simpson",
"Mmmm...fuzzy. -Homer Simpson",
"Mmmm...open faced club sand wedge. -Homer Simpson",
"Duff Man can't breathe! Oh no! -Duff Man",
"Ooh, sorry, kid, sorry. I'm not used to the laughter of children. It cuts through me like a dentist drill. But no, no, that was funny, that was funny taking away my dignity like that, ha ha ha. -Moe the Bartender",
"Everything's coming up Milhouse! -Milhouse",
"And this is the snack holder where I put my beverage or, if you will, cupcake. -Homer Simpson",
"My eyes. The goggles, they do nothing. -Radioactive Man",
"You go through life, you try to be nice to people, you struggle to resist the urge to punch em in the face, and for what? -Moe the Bartender",
"Hello Simpson. I'm riding the bus today because Mother hid my car keys to punish me for talking to a woman on the phone. She was right to do it. -Principal Skinner",
"Slow down sir. You're going to give yourself a skin failure. -Dr Nick Riviera",
"In his house, we obey the laws of thermodynamics. -Homer Simpson",
"Y'ello? You'll have to speak up, I'm wearing a towel. -Homer Simpson",
"Hmm. Your ideas are intriguing to me and I wish to subscribe to your newsletter. -Homer Simpson",
"I don't even believe in Jebus! Save me Jebus! -Homer Simpson",
"There's a 4:30 in the morning now? -Bart Simpson",
"Oh wow, windows. I don't think I could afford this place. -Otto",
"Shoplifting is a victimless crime, like punching someone in the dark. -Nelson Munz",
"Can't we have one meeting that doesn't end with us digging up a corpse? -Mayor Quimby",
"Um, can you repeat the part of the stuff...where you said about all the...things? -Homer Simpson",
"Honey, if we didn't turn it down for the cops, what chance do you have? -Homer Simpson",
"Oh boy, sleep! That's where I'm a Viking! -Ralph Wiggum",
"A shiny new donkey to the man who brings me the head of Homer Simpson! -Mr Burns",
"Sure, I'm flattered, maybe even a little curious, but the answer is no! -Homer Simpson",
"Oh, if only we'd listened to that young man, instead of walling him up in the abandoned coke oven. -Mr Burns",
"You've made a powerful enemy today, my friend. -Mr Burns",
"All right, let's make this sporting, Leonard. If you can tell me why I shouldn't fire you without using the letter e, you can keep your job. -Mr Burns",
"Okay Mr. Burns Here are your messages: You have thirty minutes to move your car. You have ten minutes to move your car. Your car has been impounded. Your car has been crushed into a cube. You have thirty minutes to move your cube. -Homer Simpson",
"Ooh, don't poo-poo a nickel, Lisa. A nickel will buy you a steak and kidney pie, a cup of coffee, a slice of cheesecake and a newsreel... with enough change left over to ride the trolley from Battery Park to the polo grounds. -Mr Burns",
"Oh, so mother nature needs a favor? Well, maybe she should have thought of that when she was besetting us with droughts and floods and poison monkeys. -Mr Burns",
"Release the hounds. -Mr Burns",
"I'm afraid all of those players have retired and, uh... passed on. In fact, your right-fielder has been dead for a hundred and thirty years. -Mr Smithers",
"Smithers, this monkey is going to need most of your skin. -Mr Burns",
"Now to enjoy the Miami of Canada: Chicago. -Mr Burns",
"I'm afraid it's not that simple. As punishment for your desertion, it's company policy to give you the plague. -Mr Burns"
"Oh, Smithers. I would have said anything to get your stem cells. -Mr Burns",
"Oh, balderdash. It's not important how old you are on parchment, it's how old you feel in the humours! -Mr Burns",
"Compadres, it is imperative that we crush the freedom fighters before the start of the rainy season. And remember, a shiny new donkey for whomever brings me the head of Colonel Montoya. -Mr Burns",
"Have the Rolling Stones killed. -Mr Burns",
"I don't know why. It's a perfectly cromulent word. -Miss Hoover",
"Roads closed, pipes frozen, albinos...virtually invisible. The Weather Service has upgraded Springfield's blizzard from Winter Wonderland to a Class 3 Kill-Storm. -Kent Brockman",
"Oh, I have had it, I have had it with this school, Skinner! The low test scores, class after class of ugly, ugly children! -Superintendent Chalmers",
"You have 24 hours to give us our money. And to show you we're serious...you have 12 hours. -Fat Tony",
"I can't wait to eat that monkey. -Grandpa Simpson",
"Uh, did I say corpse hatch? I meant innocence tube. -Mr Burns"
]
module.exports = (robot) ->
robot.respond /simpsons quote me\b/i, (msg) ->
msg.send msg.random quotes
robot.respond /simpsons image me\b/i, (msg) ->
simpsonMe(msg, 1)
robot.respond /simpsons version\b/i, (msg) ->
msg.send require('../package').version
simpsonMe = (msg, num) ->
msg.http("https://api.imgur.com/3/gallery/r/TheSimpsons.json")
.headers(Authorization: 'Client-ID 8e4f0ec64cc27f6')
.get() (err, res, body) ->
if body?
content = JSON.parse(body)
if content?.data and content.data.length > 0
msg.send (msg.random content.data).link
else
msg.send "D'oh! No response from Imgur."
else
msg.send "D'oh! No response from Imgur."
| 220883 | # Description
# A Simpsons Quote and Image Generator for Hubots.
#
# Configuration:
# None
#
# Commands:
# hubot simpsons image me - displays a random image from imgur.com/r/TheSimpsons
# hubot simpsons quote me - displays a random quote from the simpsons
#
# Author:
# jjasghar
# omardelarosa
#
# Quotes Via: http://www.mandatory.com/2013/02/12/the-100-greatest-quotes-from-the-simpsons/
quotes = [
"I'd rather let a thousand guilty men go free than chase after them. -<NAME>",
"Well, crying isn't gonna bring him back, unless your tears smell like dog food. So you can either sit there crying and eating can after can of dog food until your tears smell enough like dog food to make your dog come back, or you can go out there and find your dog. -<NAME>",
"Go out on a Tuesday? Who am I, <NAME>? -<NAME>",
"It's all over, people! We don't have a prayer! -Rever<NAME> Love<NAME>",
"Now we play the waiting game...Ahh, the waiting game sucks. Let's play Hungry Hungry Hippos! -<NAME>",
"Trust me, <NAME>, it's better to walk in on both your parents than on just one of them. -<NAME>",
"There's only one thing to do at a moment like this: strut! -<NAME>",
"Unshrink you? Well that would require some sort of a Rebigulator, which is a concept so ridiculous it makes me want to laugh out loud and chortle... -<NAME>",
"Wait a minute. <NAME>'s teacher is named '<NAME>'? Oh, I've been calling her 'Crandall.' Why didn't anyone tell me? Ohhh, I've been making an idiot out of myself! -<NAME>",
"Boy, I tell ya, they only come out at night. Or in this case, the daytime. -Ch<NAME>um",
"Hi, I'm <NAME>. You might remember me from such self-help videos as \"Smoke Yourself Thin\" and \"Get Confident, Stupid.\" -<NAME>",
"I used to be with it, but then they changed what \"it\" was, and now what I'm with isn't it. And what's \"it\" seems weird and scary to me. -<NAME>",
"It tastes like...burning. -<NAME>",
"This is a thousand monkeys working at a thousand typewriters. Soon they'll have written the greatest novel known to man. Let's see. It was the best of times, it was the \"blurst\" of times! You stupid monkey! -<NAME>",
"We want chilly-willy! We want chilly-willy! -<NAME>",
"(on phone) Lord, give me guidance...That's right, the guidance department. Thank you, Mrs. <NAME>. -Principal Skinner",
"But look! I got some cool pogs: Alf pogs! Remember Alf? He's back...in pog form! -<NAME>",
"Ha ha wha. Oh, sorry I'm late. There was trouble at the lab with the running and the exploding and the crying when the monkeys stole the glasses off my head. Wh-ha ha. -<NAME>",
"\"We the purple?\" What the hell was that? –Father of losing child contestant",
"Ow, my eye! I'm not supposed to get pudding in it. -<NAME>",
"A philanthropist. A humanitarian. A man of peace. These are just a few of the men who have come to spit on Montgomery Burns' grave. -<NAME>",
"Sit perfectly still. Only I may dance. -<NAME>",
"I wash myself with a rag on a stick. – <NAME>son",
"People, please. We're all frightened and horny, but we can't let some killer dolphins keep us from living and scoring! -<NAME>",
"My Homer is not a communist. He may be a liar, a pig, an idiot, a communist, but he is not a porn star. -<NAME>",
"Save me, <NAME>! -<NAME>",
"Bake him away, toys. -Chief Wiggum",
"Hey, everybody! I'm a stupid moron with an ugly face and big butt and my butt smells and...I like to kiss my own butt. -Moe the Bartender",
"Does anybody hear me complaining about the breasts? -Krusty the Clown",
"Another day, another box of stolen pens. -<NAME>",
"Feels like I'm wearing nothing at all...nothing at all...nothing at all! -<NAME>",
"Aren't we forgetting the true meaning of Christmas: the birth of Santa. -<NAME>",
"I'd be mortified if someone ever made a lousy product with the Simpson name on it. -<NAME>",
"Oh boy, dinnertime. The perfect break between work and drunk! -<NAME>",
"I don't get mad, I get stabby. -Fat Tony",
"Tonight, on \"Wings\"... ah, who cares? -TV Announcer",
"Inflammable means flammable? What a country. -Dr. <NAME>",
"I can't believe you don't shut up! -Apu Nahasapeemapetilon",
"Ah, alcohol and night-swimming. It's a winning combination. –<NAME>",
"I would kill everyone in this room for a drop of sweet beer. -<NAME>",
"My eyes! The goggles do nothing! -Rainier Wolfcastle",
"Priceless like a mother's love, or the good kind of priceless? -<NAME>",
"Science. What's science ever done for us? TV off. -Moe the Bartender",
"Chocolate microscopes? -<NAME>",
"Oops, lost a nail. Well, that's leprosy for you. -<NAME>. <NAME>",
"I'm filled with piss and vinegar! At first, I was just filled with vinegar. -<NAME>",
"<NAME>, do you find something funny about the word \"tromboner\"? -<NAME>",
"Ya used me, Skinner! YA USED ME! -Groundskeeper Willie",
"Well, he's kind of had it in for me ever since I accidently ran over his dog. Actually, replace \"accidently\" with \"repeatedly,\" and replace \"dog\" with \"son.\" -<NAME>",
"I don't mind if you pee in the shower, but only if you're taking a shower. -<NAME>",
"Hi, you've reached the Corey Hotline -- $4.95 a minute. Here are some words that rhyme with Corey: gory, story, allegory, Montessori... -Corey Hotline",
"Ladies and gentlemen, what you are seeing is a total disregard for the things St. Pat<NAME>'s Day stand for. All this drinking, violence, destruction of property. Are these the things we think of when we think of the Irish? -<NAME>",
"Well, if by \"wank\" you mean educational fun, then stand back, it's wanking time! -Principal Skinner",
"Shoplifting is a victimless crime. Like punching someone in the dark. -<NAME>",
"This is Papa Bear. Put out an APB for a male suspect, driving a...car of some sort, heading in the direction of...you know, that place that sells chili. Suspect is hatless. Repeat, hatless. -Chief Wiggum",
"Stupid sexy Flanders! -<NAME>",
"Inside every hardened criminal beats the heart of a ten-year-old boy. -<NAME>",
"It's not easy to juggle a pregnant wife and a troubled child, but somehow I managed to fit in eight hours of TV a day. -<NAME>",
"Chat away. I'll just amuse myself with some pornographic playing cards. -<NAME>",
"When are they gonna get to the fireworks factory? (begins to cry) –<NAME>",
"Oh, loneliness and cheeseburgers are a dangerous mix. -Comic Book Guy",
"Skinner said the teachers will crack any minute purple monkey dishwasher. –Random Teacher",
"Just because I don't care doesn't mean that I don't understand. -<NAME>",
"My bones are so brittle. But I always drink plenty of...malk? -<NAME>",
"Me fail English? That's unpossible. -<NAME>",
"La...tex con...dome. Boy, I'd like to live in one of those! -<NAME>",
"When a woman says nothing's wrong, that means everything's wrong. And when a woman says everything's wrong, that means everything's wrong. And when a woman says something's not funny, you'd better not laugh your ass off. -<NAME>",
"Ironic, isn't it, <NAME>? This anonymous clan of slack-jawed troglodytes has cost me the election. And yet, if I were to have them killed, I would be the one to go to jail. That's democracy for you. -<NAME>",
"Oh boy. Looks like it's suicide again for me. -<NAME>e the Bartender",
"I'm trying to be a sensitive father, you unwanted moron! -<NAME>",
"Talking out of turn...that's a paddling. Looking out the window...that's a paddling. Staring at my sandals...that's a paddling. Paddling the school canoe...ooh, you better believe that's a paddling. -<NAME>",
"How can I prove we're live? <NAME>! -<NAME>",
"Now make like my pants, and split. -Comic Book Guy",
"For the next five minutes, I'm going to party like it's on sale for $19",
"-<NAME>",
"You know, FOX turned into a hardcore sex channel so gradually, I didn't even notice. -<NAME>",
"Ahh, there's nothing better than a cigarette... unless it's a cigarette lit with a hundred-dollar bill. -Krusty the Clown",
"Remember the time he ate my goldfish, and you lied to me and said I never had any goldfish. Then why'd I have the bowl, B<NAME>? Why did I have the bowl? -<NAME>",
"Stupider like a fox! -<NAME>",
"Hey, look at my feet. You like those moccasins? Look in your closet; there's a pair for you. Don't like them? Then neither do I! [throws them out the door] Get the hell outta here! Ever see a guy say good-bye to a shoe? -<NAME>",
"Uh, no you've got the wrong number. This is 9-1... -Chief Wiggum",
"Yes, but I'd trade it all for a little more. -<NAME>",
"What do you mean I can't take off my sweater? I'm HOT! -D<NAME>",
"I'm so hungry, I could eat at Arby's. -Sherri or Terri",
"Oh, dear God. Can't this town go one day without a riot? -<NAME>",
"By the time I got to a phone, my discovery had already been reported by Principal Kohoutek. I got back at him, though...him and that little boy of his. -Principal Skinner",
"You must love this country more than I love a cold beer on a hot Christmas morning. -<NAME>",
"My cat's breath smells like cat food. -<NAME>",
"I didn't think it was physically possible, but this both sucks and blows. -<NAME>",
"<NAME> must be spinning in his grave! -<NAME>",
"I've been called ugly, pug ugly, fugly, pug fugly, but never ugly ugly. -Moe the Bartender",
"You don't win friends with salad. -<NAME>",
"If he was going to commit a crime, would he have invited the number one cop in town? Now where did I put my gun? Oh yeah, I set it down when I got a piece of cake. -Chief Wiggum",
"Homer, you're as dumb as a mule and twice as ugly. If a strange man offers you a ride, I say take it! -<NAME>",
"Well, if it isn't my old friend, <NAME>. <NAME>, with a leg for an arm, and an arm for a leg. -Dr. <NAME>",
"We're here! We're queer! We don't want any more bears! -Townspeople",
"Shut up, brain, or I'll stab you with a Q-tip! -<NAME>",
"Everything's coming up Milhouse! -M<NAME> Van H<NAME>",
"I was saying \"Boo-urns.\" -<NAME>",
"I can't promise I'll try, but I'll try to try. -<NAME>",
"To alcohol! The cause of, and solution to, all of life's problems. -<NAME>",
"Oh boy, Liver! Iron helps us play! -Rod and Todd",
"Look at those poor saps back on land with their laws and ethics! They'll never know the simple joys of a monkey knife fight. -<NAME>",
"Beer. Now there's a temporary solution. -<NAME>",
"All right, brain. You don't like me and I don't like you, but let's just do this and I can get back to killing you with beer. -<NAME>",
"And how is education supposed to make me feel smarter? Besides, every time I learn something new, it pushes some old stuff out of my brain. Remember when I took that home winemaking course, and I forgot how to drive? -<NAME>",
"I hope I didn't brain my damage. -<NAME>",
"Oh, <NAME>, you and your stories: <NAME>'s a vampire, beer kills brain cells. Now let's go back to that... building... thingie... where our beds and TV... is. -<NAME>",
"What are you gonna do? Sick your dogs on me? Or your bees? Or dogs with bees in their mouth so when they bark they shoot bees at me? -<NAME>",
"I have misplaced my pants. -<NAME>",
"Mmmm, 52 slices of American cheese. -<NAME>",
"Mmmm, forbidden donut. -<NAME>",
"Mmmm, free goo. -<NAME>",
"Mmmm, Gummy-beer. -<NAME>",
"Mmmm, purple. -<NAME>",
"Mmmm, sacrilicious. -<NAME>",
"Mmmm...fuzzy. -<NAME>",
"Mmmm...open faced club sand wedge. -<NAME>",
"Duff Man can't breathe! Oh no! -Duff Man",
"Ooh, sorry, kid, sorry. I'm not used to the laughter of children. It cuts through me like a dentist drill. But no, no, that was funny, that was funny taking away my dignity like that, ha ha ha. -Moe the Bartender",
"Everything's coming up Milhouse! -Milhouse",
"And this is the snack holder where I put my beverage or, if you will, cupcake. -<NAME>",
"My eyes. The goggles, they do nothing. -Radioactive Man",
"You go through life, you try to be nice to people, you struggle to resist the urge to punch em in the face, and for what? -Moe the Bartender",
"Hello <NAME>. I'm riding the bus today because Mother hid my car keys to punish me for talking to a woman on the phone. She was right to do it. -Principal Skinner",
"Slow down sir. You're going to give yourself a skin failure. -Dr <NAME>",
"In his house, we obey the laws of thermodynamics. -<NAME>",
"Y'ello? You'll have to speak up, I'm wearing a towel. -<NAME>",
"Hmm. Your ideas are intriguing to me and I wish to subscribe to your newsletter. -<NAME>",
"I don't even believe in Jebus! Save me Jebus! -<NAME>",
"There's a 4:30 in the morning now? -<NAME>",
"Oh wow, windows. I don't think I could afford this place. -Otto",
"Shoplifting is a victimless crime, like punching someone in the dark. -<NAME>",
"Can't we have one meeting that doesn't end with us digging up a corpse? -<NAME>",
"Um, can you repeat the part of the stuff...where you said about all the...things? -<NAME>",
"Honey, if we didn't turn it down for the cops, what chance do you have? -<NAME>",
"Oh boy, sleep! That's where I'm a Viking! -<NAME>",
"A shiny new donkey to the man who brings me the head of <NAME>! -<NAME>",
"Sure, I'm flattered, maybe even a little curious, but the answer is no! -<NAME>",
"Oh, if only we'd listened to that young man, instead of walling him up in the abandoned coke oven. -<NAME>",
"You've made a powerful enemy today, my friend. -<NAME>",
"All right, let's make this sporting, Leonard. If you can tell me why I shouldn't fire you without using the letter e, you can keep your job. -<NAME>",
"Okay <NAME> Here are your messages: You have thirty minutes to move your car. You have ten minutes to move your car. Your car has been impounded. Your car has been crushed into a cube. You have thirty minutes to move your cube. -<NAME>",
"Ooh, don't poo-poo a nickel, <NAME>. A nickel will buy you a steak and kidney pie, a cup of coffee, a slice of cheesecake and a newsreel... with enough change left over to ride the trolley from Battery Park to the polo grounds. -<NAME>",
"Oh, so mother nature needs a favor? Well, maybe she should have thought of that when she was besetting us with droughts and floods and poison monkeys. -<NAME>",
"Release the hounds. -<NAME>",
"I'm afraid all of those players have retired and, uh... passed on. In fact, your right-fielder has been dead for a hundred and thirty years. -<NAME>",
"<NAME>, this monkey is going to need most of your skin. -<NAME>",
"Now to enjoy the Miami of Canada: Chicago. -<NAME>",
"I'm afraid it's not that simple. As punishment for your desertion, it's company policy to give you the plague. -<NAME>"
"Oh, <NAME>. I would have said anything to get your stem cells. -<NAME>",
"Oh, balderdash. It's not important how old you are on parchment, it's how old you feel in the humours! -<NAME>",
"Compadres, it is imperative that we crush the freedom fighters before the start of the rainy season. And remember, a shiny new donkey for whomever brings me the head of Colonel Montoya. -<NAME>",
"Have the Rolling Stones killed. -<NAME>",
"I don't know why. It's a perfectly cromulent word. -<NAME>",
"Roads closed, pipes frozen, albinos...virtually invisible. The Weather Service has upgraded Springfield's blizzard from Winter Wonderland to a Class 3 Kill-Storm. -<NAME>",
"Oh, I have had it, I have had it with this school, Skinner! The low test scores, class after class of ugly, ugly children! -Superintendent Chalmers",
"You have 24 hours to give us our money. And to show you we're serious...you have 12 hours. -Fat T<NAME>",
"I can't wait to eat that monkey. -<NAME>",
"Uh, did I say corpse hatch? I meant innocence tube. -Mr Burns"
]
module.exports = (robot) ->
robot.respond /simpsons quote me\b/i, (msg) ->
msg.send msg.random quotes
robot.respond /simpsons image me\b/i, (msg) ->
simpsonMe(msg, 1)
robot.respond /simpsons version\b/i, (msg) ->
msg.send require('../package').version
simpsonMe = (msg, num) ->
msg.http("https://api.imgur.com/3/gallery/r/TheSimpsons.json")
.headers(Authorization: 'Client-ID 8e4f0ec64cc27f6')
.get() (err, res, body) ->
if body?
content = JSON.parse(body)
if content?.data and content.data.length > 0
msg.send (msg.random content.data).link
else
msg.send "D'oh! No response from Imgur."
else
msg.send "D'oh! No response from Imgur."
| true | # Description
# A Simpsons Quote and Image Generator for Hubots.
#
# Configuration:
# None
#
# Commands:
# hubot simpsons image me - displays a random image from imgur.com/r/TheSimpsons
# hubot simpsons quote me - displays a random quote from the simpsons
#
# Author:
# jjasghar
# omardelarosa
#
# Quotes Via: http://www.mandatory.com/2013/02/12/the-100-greatest-quotes-from-the-simpsons/
quotes = [
"I'd rather let a thousand guilty men go free than chase after them. -PI:NAME:<NAME>END_PI",
"Well, crying isn't gonna bring him back, unless your tears smell like dog food. So you can either sit there crying and eating can after can of dog food until your tears smell enough like dog food to make your dog come back, or you can go out there and find your dog. -PI:NAME:<NAME>END_PI",
"Go out on a Tuesday? Who am I, PI:NAME:<NAME>END_PI? -PI:NAME:<NAME>END_PI",
"It's all over, people! We don't have a prayer! -ReverPI:NAME:<NAME>END_PI LovePI:NAME:<NAME>END_PI",
"Now we play the waiting game...Ahh, the waiting game sucks. Let's play Hungry Hungry Hippos! -PI:NAME:<NAME>END_PI",
"Trust me, PI:NAME:<NAME>END_PI, it's better to walk in on both your parents than on just one of them. -PI:NAME:<NAME>END_PI",
"There's only one thing to do at a moment like this: strut! -PI:NAME:<NAME>END_PI",
"Unshrink you? Well that would require some sort of a Rebigulator, which is a concept so ridiculous it makes me want to laugh out loud and chortle... -PI:NAME:<NAME>END_PI",
"Wait a minute. PI:NAME:<NAME>END_PI's teacher is named 'PI:NAME:<NAME>END_PI'? Oh, I've been calling her 'Crandall.' Why didn't anyone tell me? Ohhh, I've been making an idiot out of myself! -PI:NAME:<NAME>END_PI",
"Boy, I tell ya, they only come out at night. Or in this case, the daytime. -ChPI:NAME:<NAME>END_PIum",
"Hi, I'm PI:NAME:<NAME>END_PI. You might remember me from such self-help videos as \"Smoke Yourself Thin\" and \"Get Confident, Stupid.\" -PI:NAME:<NAME>END_PI",
"I used to be with it, but then they changed what \"it\" was, and now what I'm with isn't it. And what's \"it\" seems weird and scary to me. -PI:NAME:<NAME>END_PI",
"It tastes like...burning. -PI:NAME:<NAME>END_PI",
"This is a thousand monkeys working at a thousand typewriters. Soon they'll have written the greatest novel known to man. Let's see. It was the best of times, it was the \"blurst\" of times! You stupid monkey! -PI:NAME:<NAME>END_PI",
"We want chilly-willy! We want chilly-willy! -PI:NAME:<NAME>END_PI",
"(on phone) Lord, give me guidance...That's right, the guidance department. Thank you, Mrs. PI:NAME:<NAME>END_PI. -Principal Skinner",
"But look! I got some cool pogs: Alf pogs! Remember Alf? He's back...in pog form! -PI:NAME:<NAME>END_PI",
"Ha ha wha. Oh, sorry I'm late. There was trouble at the lab with the running and the exploding and the crying when the monkeys stole the glasses off my head. Wh-ha ha. -PI:NAME:<NAME>END_PI",
"\"We the purple?\" What the hell was that? –Father of losing child contestant",
"Ow, my eye! I'm not supposed to get pudding in it. -PI:NAME:<NAME>END_PI",
"A philanthropist. A humanitarian. A man of peace. These are just a few of the men who have come to spit on Montgomery Burns' grave. -PI:NAME:<NAME>END_PI",
"Sit perfectly still. Only I may dance. -PI:NAME:<NAME>END_PI",
"I wash myself with a rag on a stick. – PI:NAME:<NAME>END_PIson",
"People, please. We're all frightened and horny, but we can't let some killer dolphins keep us from living and scoring! -PI:NAME:<NAME>END_PI",
"My Homer is not a communist. He may be a liar, a pig, an idiot, a communist, but he is not a porn star. -PI:NAME:<NAME>END_PI",
"Save me, PI:NAME:<NAME>END_PI! -PI:NAME:<NAME>END_PI",
"Bake him away, toys. -Chief Wiggum",
"Hey, everybody! I'm a stupid moron with an ugly face and big butt and my butt smells and...I like to kiss my own butt. -Moe the Bartender",
"Does anybody hear me complaining about the breasts? -Krusty the Clown",
"Another day, another box of stolen pens. -PI:NAME:<NAME>END_PI",
"Feels like I'm wearing nothing at all...nothing at all...nothing at all! -PI:NAME:<NAME>END_PI",
"Aren't we forgetting the true meaning of Christmas: the birth of Santa. -PI:NAME:<NAME>END_PI",
"I'd be mortified if someone ever made a lousy product with the Simpson name on it. -PI:NAME:<NAME>END_PI",
"Oh boy, dinnertime. The perfect break between work and drunk! -PI:NAME:<NAME>END_PI",
"I don't get mad, I get stabby. -Fat Tony",
"Tonight, on \"Wings\"... ah, who cares? -TV Announcer",
"Inflammable means flammable? What a country. -Dr. PI:NAME:<NAME>END_PI",
"I can't believe you don't shut up! -Apu Nahasapeemapetilon",
"Ah, alcohol and night-swimming. It's a winning combination. –PI:NAME:<NAME>END_PI",
"I would kill everyone in this room for a drop of sweet beer. -PI:NAME:<NAME>END_PI",
"My eyes! The goggles do nothing! -Rainier Wolfcastle",
"Priceless like a mother's love, or the good kind of priceless? -PI:NAME:<NAME>END_PI",
"Science. What's science ever done for us? TV off. -Moe the Bartender",
"Chocolate microscopes? -PI:NAME:<NAME>END_PI",
"Oops, lost a nail. Well, that's leprosy for you. -PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI",
"I'm filled with piss and vinegar! At first, I was just filled with vinegar. -PI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI, do you find something funny about the word \"tromboner\"? -PI:NAME:<NAME>END_PI",
"Ya used me, Skinner! YA USED ME! -Groundskeeper Willie",
"Well, he's kind of had it in for me ever since I accidently ran over his dog. Actually, replace \"accidently\" with \"repeatedly,\" and replace \"dog\" with \"son.\" -PI:NAME:<NAME>END_PI",
"I don't mind if you pee in the shower, but only if you're taking a shower. -PI:NAME:<NAME>END_PI",
"Hi, you've reached the Corey Hotline -- $4.95 a minute. Here are some words that rhyme with Corey: gory, story, allegory, Montessori... -Corey Hotline",
"Ladies and gentlemen, what you are seeing is a total disregard for the things St. PatPI:NAME:<NAME>END_PI's Day stand for. All this drinking, violence, destruction of property. Are these the things we think of when we think of the Irish? -PI:NAME:<NAME>END_PI",
"Well, if by \"wank\" you mean educational fun, then stand back, it's wanking time! -Principal Skinner",
"Shoplifting is a victimless crime. Like punching someone in the dark. -PI:NAME:<NAME>END_PI",
"This is Papa Bear. Put out an APB for a male suspect, driving a...car of some sort, heading in the direction of...you know, that place that sells chili. Suspect is hatless. Repeat, hatless. -Chief Wiggum",
"Stupid sexy Flanders! -PI:NAME:<NAME>END_PI",
"Inside every hardened criminal beats the heart of a ten-year-old boy. -PI:NAME:<NAME>END_PI",
"It's not easy to juggle a pregnant wife and a troubled child, but somehow I managed to fit in eight hours of TV a day. -PI:NAME:<NAME>END_PI",
"Chat away. I'll just amuse myself with some pornographic playing cards. -PI:NAME:<NAME>END_PI",
"When are they gonna get to the fireworks factory? (begins to cry) –PI:NAME:<NAME>END_PI",
"Oh, loneliness and cheeseburgers are a dangerous mix. -Comic Book Guy",
"Skinner said the teachers will crack any minute purple monkey dishwasher. –Random Teacher",
"Just because I don't care doesn't mean that I don't understand. -PI:NAME:<NAME>END_PI",
"My bones are so brittle. But I always drink plenty of...malk? -PI:NAME:<NAME>END_PI",
"Me fail English? That's unpossible. -PI:NAME:<NAME>END_PI",
"La...tex con...dome. Boy, I'd like to live in one of those! -PI:NAME:<NAME>END_PI",
"When a woman says nothing's wrong, that means everything's wrong. And when a woman says everything's wrong, that means everything's wrong. And when a woman says something's not funny, you'd better not laugh your ass off. -PI:NAME:<NAME>END_PI",
"Ironic, isn't it, PI:NAME:<NAME>END_PI? This anonymous clan of slack-jawed troglodytes has cost me the election. And yet, if I were to have them killed, I would be the one to go to jail. That's democracy for you. -PI:NAME:<NAME>END_PI",
"Oh boy. Looks like it's suicide again for me. -PI:NAME:<NAME>END_PIe the Bartender",
"I'm trying to be a sensitive father, you unwanted moron! -PI:NAME:<NAME>END_PI",
"Talking out of turn...that's a paddling. Looking out the window...that's a paddling. Staring at my sandals...that's a paddling. Paddling the school canoe...ooh, you better believe that's a paddling. -PI:NAME:<NAME>END_PI",
"How can I prove we're live? PI:NAME:<NAME>END_PI! -PI:NAME:<NAME>END_PI",
"Now make like my pants, and split. -Comic Book Guy",
"For the next five minutes, I'm going to party like it's on sale for $19",
"-PI:NAME:<NAME>END_PI",
"You know, FOX turned into a hardcore sex channel so gradually, I didn't even notice. -PI:NAME:<NAME>END_PI",
"Ahh, there's nothing better than a cigarette... unless it's a cigarette lit with a hundred-dollar bill. -Krusty the Clown",
"Remember the time he ate my goldfish, and you lied to me and said I never had any goldfish. Then why'd I have the bowl, BPI:NAME:<NAME>END_PI? Why did I have the bowl? -PI:NAME:<NAME>END_PI",
"Stupider like a fox! -PI:NAME:<NAME>END_PI",
"Hey, look at my feet. You like those moccasins? Look in your closet; there's a pair for you. Don't like them? Then neither do I! [throws them out the door] Get the hell outta here! Ever see a guy say good-bye to a shoe? -PI:NAME:<NAME>END_PI",
"Uh, no you've got the wrong number. This is 9-1... -Chief Wiggum",
"Yes, but I'd trade it all for a little more. -PI:NAME:<NAME>END_PI",
"What do you mean I can't take off my sweater? I'm HOT! -DPI:NAME:<NAME>END_PI",
"I'm so hungry, I could eat at Arby's. -Sherri or Terri",
"Oh, dear God. Can't this town go one day without a riot? -PI:NAME:<NAME>END_PI",
"By the time I got to a phone, my discovery had already been reported by Principal Kohoutek. I got back at him, though...him and that little boy of his. -Principal Skinner",
"You must love this country more than I love a cold beer on a hot Christmas morning. -PI:NAME:<NAME>END_PI",
"My cat's breath smells like cat food. -PI:NAME:<NAME>END_PI",
"I didn't think it was physically possible, but this both sucks and blows. -PI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI must be spinning in his grave! -PI:NAME:<NAME>END_PI",
"I've been called ugly, pug ugly, fugly, pug fugly, but never ugly ugly. -Moe the Bartender",
"You don't win friends with salad. -PI:NAME:<NAME>END_PI",
"If he was going to commit a crime, would he have invited the number one cop in town? Now where did I put my gun? Oh yeah, I set it down when I got a piece of cake. -Chief Wiggum",
"Homer, you're as dumb as a mule and twice as ugly. If a strange man offers you a ride, I say take it! -PI:NAME:<NAME>END_PI",
"Well, if it isn't my old friend, PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI, with a leg for an arm, and an arm for a leg. -Dr. PI:NAME:<NAME>END_PI",
"We're here! We're queer! We don't want any more bears! -Townspeople",
"Shut up, brain, or I'll stab you with a Q-tip! -PI:NAME:<NAME>END_PI",
"Everything's coming up Milhouse! -MPI:NAME:<NAME>END_PI Van HPI:NAME:<NAME>END_PI",
"I was saying \"Boo-urns.\" -PI:NAME:<NAME>END_PI",
"I can't promise I'll try, but I'll try to try. -PI:NAME:<NAME>END_PI",
"To alcohol! The cause of, and solution to, all of life's problems. -PI:NAME:<NAME>END_PI",
"Oh boy, Liver! Iron helps us play! -Rod and Todd",
"Look at those poor saps back on land with their laws and ethics! They'll never know the simple joys of a monkey knife fight. -PI:NAME:<NAME>END_PI",
"Beer. Now there's a temporary solution. -PI:NAME:<NAME>END_PI",
"All right, brain. You don't like me and I don't like you, but let's just do this and I can get back to killing you with beer. -PI:NAME:<NAME>END_PI",
"And how is education supposed to make me feel smarter? Besides, every time I learn something new, it pushes some old stuff out of my brain. Remember when I took that home winemaking course, and I forgot how to drive? -PI:NAME:<NAME>END_PI",
"I hope I didn't brain my damage. -PI:NAME:<NAME>END_PI",
"Oh, PI:NAME:<NAME>END_PI, you and your stories: PI:NAME:<NAME>END_PI's a vampire, beer kills brain cells. Now let's go back to that... building... thingie... where our beds and TV... is. -PI:NAME:<NAME>END_PI",
"What are you gonna do? Sick your dogs on me? Or your bees? Or dogs with bees in their mouth so when they bark they shoot bees at me? -PI:NAME:<NAME>END_PI",
"I have misplaced my pants. -PI:NAME:<NAME>END_PI",
"Mmmm, 52 slices of American cheese. -PI:NAME:<NAME>END_PI",
"Mmmm, forbidden donut. -PI:NAME:<NAME>END_PI",
"Mmmm, free goo. -PI:NAME:<NAME>END_PI",
"Mmmm, Gummy-beer. -PI:NAME:<NAME>END_PI",
"Mmmm, purple. -PI:NAME:<NAME>END_PI",
"Mmmm, sacrilicious. -PI:NAME:<NAME>END_PI",
"Mmmm...fuzzy. -PI:NAME:<NAME>END_PI",
"Mmmm...open faced club sand wedge. -PI:NAME:<NAME>END_PI",
"Duff Man can't breathe! Oh no! -Duff Man",
"Ooh, sorry, kid, sorry. I'm not used to the laughter of children. It cuts through me like a dentist drill. But no, no, that was funny, that was funny taking away my dignity like that, ha ha ha. -Moe the Bartender",
"Everything's coming up Milhouse! -Milhouse",
"And this is the snack holder where I put my beverage or, if you will, cupcake. -PI:NAME:<NAME>END_PI",
"My eyes. The goggles, they do nothing. -Radioactive Man",
"You go through life, you try to be nice to people, you struggle to resist the urge to punch em in the face, and for what? -Moe the Bartender",
"Hello PI:NAME:<NAME>END_PI. I'm riding the bus today because Mother hid my car keys to punish me for talking to a woman on the phone. She was right to do it. -Principal Skinner",
"Slow down sir. You're going to give yourself a skin failure. -Dr PI:NAME:<NAME>END_PI",
"In his house, we obey the laws of thermodynamics. -PI:NAME:<NAME>END_PI",
"Y'ello? You'll have to speak up, I'm wearing a towel. -PI:NAME:<NAME>END_PI",
"Hmm. Your ideas are intriguing to me and I wish to subscribe to your newsletter. -PI:NAME:<NAME>END_PI",
"I don't even believe in Jebus! Save me Jebus! -PI:NAME:<NAME>END_PI",
"There's a 4:30 in the morning now? -PI:NAME:<NAME>END_PI",
"Oh wow, windows. I don't think I could afford this place. -Otto",
"Shoplifting is a victimless crime, like punching someone in the dark. -PI:NAME:<NAME>END_PI",
"Can't we have one meeting that doesn't end with us digging up a corpse? -PI:NAME:<NAME>END_PI",
"Um, can you repeat the part of the stuff...where you said about all the...things? -PI:NAME:<NAME>END_PI",
"Honey, if we didn't turn it down for the cops, what chance do you have? -PI:NAME:<NAME>END_PI",
"Oh boy, sleep! That's where I'm a Viking! -PI:NAME:<NAME>END_PI",
"A shiny new donkey to the man who brings me the head of PI:NAME:<NAME>END_PI! -PI:NAME:<NAME>END_PI",
"Sure, I'm flattered, maybe even a little curious, but the answer is no! -PI:NAME:<NAME>END_PI",
"Oh, if only we'd listened to that young man, instead of walling him up in the abandoned coke oven. -PI:NAME:<NAME>END_PI",
"You've made a powerful enemy today, my friend. -PI:NAME:<NAME>END_PI",
"All right, let's make this sporting, Leonard. If you can tell me why I shouldn't fire you without using the letter e, you can keep your job. -PI:NAME:<NAME>END_PI",
"Okay PI:NAME:<NAME>END_PI Here are your messages: You have thirty minutes to move your car. You have ten minutes to move your car. Your car has been impounded. Your car has been crushed into a cube. You have thirty minutes to move your cube. -PI:NAME:<NAME>END_PI",
"Ooh, don't poo-poo a nickel, PI:NAME:<NAME>END_PI. A nickel will buy you a steak and kidney pie, a cup of coffee, a slice of cheesecake and a newsreel... with enough change left over to ride the trolley from Battery Park to the polo grounds. -PI:NAME:<NAME>END_PI",
"Oh, so mother nature needs a favor? Well, maybe she should have thought of that when she was besetting us with droughts and floods and poison monkeys. -PI:NAME:<NAME>END_PI",
"Release the hounds. -PI:NAME:<NAME>END_PI",
"I'm afraid all of those players have retired and, uh... passed on. In fact, your right-fielder has been dead for a hundred and thirty years. -PI:NAME:<NAME>END_PI",
"PI:NAME:<NAME>END_PI, this monkey is going to need most of your skin. -PI:NAME:<NAME>END_PI",
"Now to enjoy the Miami of Canada: Chicago. -PI:NAME:<NAME>END_PI",
"I'm afraid it's not that simple. As punishment for your desertion, it's company policy to give you the plague. -PI:NAME:<NAME>END_PI"
"Oh, PI:NAME:<NAME>END_PI. I would have said anything to get your stem cells. -PI:NAME:<NAME>END_PI",
"Oh, balderdash. It's not important how old you are on parchment, it's how old you feel in the humours! -PI:NAME:<NAME>END_PI",
"Compadres, it is imperative that we crush the freedom fighters before the start of the rainy season. And remember, a shiny new donkey for whomever brings me the head of Colonel Montoya. -PI:NAME:<NAME>END_PI",
"Have the Rolling Stones killed. -PI:NAME:<NAME>END_PI",
"I don't know why. It's a perfectly cromulent word. -PI:NAME:<NAME>END_PI",
"Roads closed, pipes frozen, albinos...virtually invisible. The Weather Service has upgraded Springfield's blizzard from Winter Wonderland to a Class 3 Kill-Storm. -PI:NAME:<NAME>END_PI",
"Oh, I have had it, I have had it with this school, Skinner! The low test scores, class after class of ugly, ugly children! -Superintendent Chalmers",
"You have 24 hours to give us our money. And to show you we're serious...you have 12 hours. -Fat TPI:NAME:<NAME>END_PI",
"I can't wait to eat that monkey. -PI:NAME:<NAME>END_PI",
"Uh, did I say corpse hatch? I meant innocence tube. -Mr Burns"
]
module.exports = (robot) ->
robot.respond /simpsons quote me\b/i, (msg) ->
msg.send msg.random quotes
robot.respond /simpsons image me\b/i, (msg) ->
simpsonMe(msg, 1)
robot.respond /simpsons version\b/i, (msg) ->
msg.send require('../package').version
simpsonMe = (msg, num) ->
msg.http("https://api.imgur.com/3/gallery/r/TheSimpsons.json")
.headers(Authorization: 'Client-ID 8e4f0ec64cc27f6')
.get() (err, res, body) ->
if body?
content = JSON.parse(body)
if content?.data and content.data.length > 0
msg.send (msg.random content.data).link
else
msg.send "D'oh! No response from Imgur."
else
msg.send "D'oh! No response from Imgur."
|
[
{
"context": "w new ContactModal()\n\n contributors: [\n {id: '547acbb2af18b03c0563fdb3', name: 'David Liu', github: 'trotod'}\n {id: '",
"end": 565,
"score": 0.46455544233322144,
"start": 541,
"tag": "KEY",
"value": "547acbb2af18b03c0563fdb3"
},
{
"context": "rs: [\n {id: '547acbb2af18b03c0563fdb3', name: 'David Liu', github: 'trotod'}\n {id: '52ccfc9bd3eb6b5a410",
"end": 584,
"score": 0.9998276829719543,
"start": 575,
"tag": "NAME",
"value": "David Liu"
},
{
"context": "bb2af18b03c0563fdb3', name: 'David Liu', github: 'trotod'}\n {id: '52ccfc9bd3eb6b5a4100b60d', name: 'Gle",
"end": 602,
"score": 0.8726188540458679,
"start": 596,
"tag": "USERNAME",
"value": "trotod"
},
{
"context": "', name: 'David Liu', github: 'trotod'}\n {id: '52ccfc9bd3eb6b5a4100b60d', name: 'Glen De Cauwsemae",
"end": 616,
"score": 0.41247183084487915,
"start": 615,
"tag": "KEY",
"value": "5"
},
{
"context": ", name: 'David Liu', github: 'trotod'}\n {id: '52ccfc9bd3eb6b5a4100b60d', name: 'Glen De Cauwsemaec",
"end": 617,
"score": 0.377482533454895,
"start": 616,
"tag": "PASSWORD",
"value": "2"
},
{
"context": "id Liu', github: 'trotod'}\n {id: '52ccfc9bd3eb6b5a4100b60d', name: 'Glen De Cauwsemaecker', github",
"end": 629,
"score": 0.3618372678756714,
"start": 628,
"tag": "PASSWORD",
"value": "b"
},
{
"context": ", github: 'trotod'}\n {id: '52ccfc9bd3eb6b5a4100b60d', name: 'Glen De Cauwsemaecker', github: 'GlenDC'",
"end": 639,
"score": 0.41335880756378174,
"start": 635,
"tag": "PASSWORD",
"value": "b60d"
},
{
"context": "tod'}\n {id: '52ccfc9bd3eb6b5a4100b60d', name: 'Glen De Cauwsemaecker', github: 'GlenDC'}\n {id: '52bfc3ecb7ec6288680",
"end": 670,
"score": 0.9998518824577332,
"start": 649,
"tag": "NAME",
"value": "Glen De Cauwsemaecker"
},
{
"context": "100b60d', name: 'Glen De Cauwsemaecker', github: 'GlenDC'}\n {id: '52bfc3ecb7ec628868001297', name: 'Tom",
"end": 688,
"score": 0.973318874835968,
"start": 682,
"tag": "USERNAME",
"value": "GlenDC"
},
{
"context": "en De Cauwsemaecker', github: 'GlenDC'}\n {id: '52bfc3ecb7ec628868001297', name: 'Tom Steinbrecher'",
"end": 702,
"score": 0.5641324520111084,
"start": 701,
"tag": "KEY",
"value": "5"
},
{
"context": "n De Cauwsemaecker', github: 'GlenDC'}\n {id: '52bfc3ecb7ec628868001297', name: 'Tom Steinbrecher', github: 'TomSteinbrec",
"end": 725,
"score": 0.4985038936138153,
"start": 702,
"tag": "PASSWORD",
"value": "2bfc3ecb7ec628868001297"
},
{
"context": "nDC'}\n {id: '52bfc3ecb7ec628868001297', name: 'Tom Steinbrecher', github: 'TomSteinbrecher'}\n {id: '5272806093",
"end": 751,
"score": 0.9998481869697571,
"start": 735,
"tag": "NAME",
"value": "Tom Steinbrecher"
},
{
"context": "628868001297', name: 'Tom Steinbrecher', github: 'TomSteinbrecher'}\n {id: '5272806093680c5817033f73', name: 'Séb",
"end": 778,
"score": 0.9264551401138306,
"start": 763,
"tag": "USERNAME",
"value": "TomSteinbrecher"
},
{
"context": "einbrecher', github: 'TomSteinbrecher'}\n {id: '5272806093680c5817033f73', name: 'Sébastien Moratinos', github: 'sm",
"end": 808,
"score": 0.46305665373802185,
"start": 791,
"tag": "KEY",
"value": "5272806093680c581"
},
{
"context": "ub: 'TomSteinbrecher'}\n {id: '5272806093680c5817033f73', name: 'Sébastien Moratinos', github: 'smorat",
"end": 812,
"score": 0.4114624857902527,
"start": 808,
"tag": "PASSWORD",
"value": "7033"
},
{
"context": "'TomSteinbrecher'}\n {id: '5272806093680c5817033f73', name: 'Sébastien Moratinos', github: 'smorati",
"end": 813,
"score": 0.42071428894996643,
"start": 812,
"tag": "KEY",
"value": "f"
},
{
"context": "TomSteinbrecher'}\n {id: '5272806093680c5817033f73', name: 'Sébastien Moratinos', github: 'smoratino",
"end": 815,
"score": 0.44656699895858765,
"start": 813,
"tag": "PASSWORD",
"value": "73"
},
{
"context": "her'}\n {id: '5272806093680c5817033f73', name: 'Sébastien Moratinos', github: 'smoratinos'}\n {id: '52d133893dc46cb",
"end": 844,
"score": 0.999854564666748,
"start": 825,
"tag": "NAME",
"value": "Sébastien Moratinos"
},
{
"context": "817033f73', name: 'Sébastien Moratinos', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Dee",
"end": 866,
"score": 0.9757425785064697,
"start": 856,
"tag": "USERNAME",
"value": "smoratinos"
},
{
"context": "stien Moratinos', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', githu",
"end": 881,
"score": 0.46933555603027344,
"start": 879,
"tag": "KEY",
"value": "52"
},
{
"context": "ien Moratinos', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'de",
"end": 887,
"score": 0.40686383843421936,
"start": 881,
"tag": "PASSWORD",
"value": "d13389"
},
{
"context": "ratinos', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'dee",
"end": 888,
"score": 0.3736060559749603,
"start": 887,
"tag": "KEY",
"value": "3"
},
{
"context": "atinos', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'deepak",
"end": 891,
"score": 0.3745262622833252,
"start": 888,
"tag": "PASSWORD",
"value": "dc4"
},
{
"context": "nos', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'deepak1",
"end": 892,
"score": 0.3610832393169403,
"start": 891,
"tag": "KEY",
"value": "6"
},
{
"context": "os', github: 'smoratinos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'deepak1556'}\n {",
"end": 903,
"score": 0.4468332529067993,
"start": 892,
"tag": "PASSWORD",
"value": "cbe15001179"
},
{
"context": "nos'}\n {id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'deepak1556'}\n {id: '52699df70e404d5",
"end": 923,
"score": 0.9998711347579956,
"start": 913,
"tag": "NAME",
"value": "Deepak Raj"
},
{
"context": "893dc46cbe15001179', name: 'Deepak Raj', github: 'deepak1556'}\n {id: '52699df70e404d591b000af7', name: 'Ron",
"end": 945,
"score": 0.944558322429657,
"start": 935,
"tag": "USERNAME",
"value": "deepak1556"
},
{
"context": "me: 'Deepak Raj', github: 'deepak1556'}\n {id: '52699df70e404d591b000af7', name: 'Ronnie Cheng', gi",
"end": 959,
"score": 0.5517719388008118,
"start": 958,
"tag": "KEY",
"value": "5"
},
{
"context": "e: 'Deepak Raj', github: 'deepak1556'}\n {id: '52699df70e404d591b000af7', name: 'Ronnie Cheng', github: 'rhc2104'}\n {i",
"end": 982,
"score": 0.4980115294456482,
"start": 959,
"tag": "PASSWORD",
"value": "2699df70e404d591b000af7"
},
{
"context": "556'}\n {id: '52699df70e404d591b000af7', name: 'Ronnie Cheng', github: 'rhc2104'}\n {id: '5260b4c3ae8ec6795e",
"end": 1004,
"score": 0.9998492002487183,
"start": 992,
"tag": "NAME",
"value": "Ronnie Cheng"
},
{
"context": "0e404d591b000af7', name: 'Ronnie Cheng', github: 'rhc2104'}\n {id: '5260b4c3ae8ec6795e000019', name: 'Chl",
"end": 1023,
"score": 0.9246606230735779,
"start": 1016,
"tag": "USERNAME",
"value": "rhc2104"
},
{
"context": "ame: 'Ronnie Cheng', github: 'rhc2104'}\n {id: '5260b4c3ae8ec6795e000019', name: 'Chloe Fan', githu",
"end": 1037,
"score": 0.432699054479599,
"start": 1036,
"tag": "KEY",
"value": "5"
},
{
"context": "104'}\n {id: '5260b4c3ae8ec6795e000019', name: 'Chloe Fan', github: 'chloester'}\n {id: '52d726ab3c70cec9",
"end": 1079,
"score": 0.9998075366020203,
"start": 1070,
"tag": "NAME",
"value": "Chloe Fan"
},
{
"context": "4c3ae8ec6795e000019', name: 'Chloe Fan', github: 'chloester'}\n {id: '52d726ab3c70cec90c008f2d', name: 'Rac",
"end": 1100,
"score": 0.9229746460914612,
"start": 1091,
"tag": "USERNAME",
"value": "chloester"
},
{
"context": "name: 'Chloe Fan', github: 'chloester'}\n {id: '52d726ab3c70cec90c008f2d', name: 'Rachel Xiang', github: 'rdxiang'}\n {i",
"end": 1137,
"score": 0.7037274241447449,
"start": 1113,
"tag": "PASSWORD",
"value": "52d726ab3c70cec90c008f2d"
},
{
"context": "ter'}\n {id: '52d726ab3c70cec90c008f2d', name: 'Rachel Xiang', github: 'rdxiang'}\n {id: '5286706d93df39a952",
"end": 1159,
"score": 0.9998361468315125,
"start": 1147,
"tag": "NAME",
"value": "Rachel Xiang"
},
{
"context": "3c70cec90c008f2d', name: 'Rachel Xiang', github: 'rdxiang'}\n {id: '5286706d93df39a952001574', name: 'Dan",
"end": 1178,
"score": 0.9416148066520691,
"start": 1171,
"tag": "USERNAME",
"value": "rdxiang"
},
{
"context": "ng', github: 'rdxiang'}\n {id: '5286706d93df39a952001574', name: 'Dan Ristic', github: 'dristic'}\n {",
"end": 1212,
"score": 0.3929145932197571,
"start": 1207,
"tag": "PASSWORD",
"value": "52001"
},
{
"context": "ang'}\n {id: '5286706d93df39a952001574', name: 'Dan Ristic', github: 'dristic'}\n {id: '52cec8620b0d5c1b4c",
"end": 1235,
"score": 0.9998712539672852,
"start": 1225,
"tag": "NAME",
"value": "Dan Ristic"
},
{
"context": "6d93df39a952001574', name: 'Dan Ristic', github: 'dristic'}\n {id: '52cec8620b0d5c1b4c0039e6', name: 'Bra",
"end": 1254,
"score": 0.8635172247886658,
"start": 1247,
"tag": "USERNAME",
"value": "dristic"
},
{
"context": " name: 'Dan Ristic', github: 'dristic'}\n {id: '52cec8620b0d5c1b4c0039e6', name: 'Brad Dickason', g",
"end": 1268,
"score": 0.46613672375679016,
"start": 1267,
"tag": "KEY",
"value": "5"
},
{
"context": "tic'}\n {id: '52cec8620b0d5c1b4c0039e6', name: 'Brad Dickason', github: 'bdickason'}\n {id: '540397e2bc5b69a4",
"end": 1314,
"score": 0.9998431205749512,
"start": 1301,
"tag": "NAME",
"value": "Brad Dickason"
},
{
"context": "b0d5c1b4c0039e6', name: 'Brad Dickason', github: 'bdickason'}\n {id: '540397e2bc5b69a40e9c2fb1', name: 'Reb",
"end": 1335,
"score": 0.9579809308052063,
"start": 1326,
"tag": "USERNAME",
"value": "bdickason"
},
{
"context": ": 'Brad Dickason', github: 'bdickason'}\n {id: '540397e2bc5b69a40e9c2fb1', name: 'Rebecca Saines'}\n",
"end": 1349,
"score": 0.508805513381958,
"start": 1348,
"tag": "KEY",
"value": "5"
},
{
"context": "son'}\n {id: '540397e2bc5b69a40e9c2fb1', name: 'Rebecca Saines'}\n {id: '525ae40248839d81090013f2', name: 'Lau",
"end": 1396,
"score": 0.9998785853385925,
"start": 1382,
"tag": "NAME",
"value": "Rebecca Saines"
},
{
"context": "b69a40e9c2fb1', name: 'Rebecca Saines'}\n {id: '525ae40248839d81090013f2', name: 'Laura Watiker', g",
"end": 1410,
"score": 0.47209611535072327,
"start": 1409,
"tag": "KEY",
"value": "5"
},
{
"context": "nes'}\n {id: '525ae40248839d81090013f2', name: 'Laura Watiker', github: 'lwatiker'}\n {id: '540395e9fe5676911",
"end": 1456,
"score": 0.9998775720596313,
"start": 1443,
"tag": "NAME",
"value": "Laura Watiker"
},
{
"context": "8839d81090013f2', name: 'Laura Watiker', github: 'lwatiker'}\n {id: '540395e9fe56769115d7da86', name: 'Shi",
"end": 1476,
"score": 0.936748206615448,
"start": 1468,
"tag": "USERNAME",
"value": "lwatiker"
},
{
"context": "e: 'Laura Watiker', github: 'lwatiker'}\n {id: '540395e9fe56769115d7da86', name: 'Shiying Zheng', g",
"end": 1490,
"score": 0.6202759742736816,
"start": 1489,
"tag": "KEY",
"value": "5"
},
{
"context": ": 'Laura Watiker', github: 'lwatiker'}\n {id: '540395e9fe56769115d7da86', name: 'Shiying Zheng', github: 'shiy",
"end": 1502,
"score": 0.4308135211467743,
"start": 1490,
"tag": "PASSWORD",
"value": "40395e9fe567"
},
{
"context": "iker', github: 'lwatiker'}\n {id: '540395e9fe56769115d7da86', name: 'Shiying Zheng', github: 'shiyin",
"end": 1504,
"score": 0.3941015303134918,
"start": 1502,
"tag": "KEY",
"value": "69"
},
{
"context": "er', github: 'lwatiker'}\n {id: '540395e9fe56769115d7da86', name: 'Shiying Zheng', github: 'shiyingzheng'}\n",
"end": 1513,
"score": 0.43704378604888916,
"start": 1504,
"tag": "PASSWORD",
"value": "115d7da86"
},
{
"context": "ker'}\n {id: '540395e9fe56769115d7da86', name: 'Shiying Zheng', github: 'shiyingzheng'}\n {id: '5403964dfe567",
"end": 1536,
"score": 0.9998605847358704,
"start": 1523,
"tag": "NAME",
"value": "Shiying Zheng"
},
{
"context": "e56769115d7da86', name: 'Shiying Zheng', github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mis",
"end": 1560,
"score": 0.7831684947013855,
"start": 1548,
"tag": "USERNAME",
"value": "shiyingzheng"
},
{
"context": "Shiying Zheng', github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Nore",
"end": 1574,
"score": 0.6706467866897583,
"start": 1573,
"tag": "KEY",
"value": "5"
},
{
"context": "hiying Zheng', github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle',",
"end": 1579,
"score": 0.5126380920410156,
"start": 1574,
"tag": "PASSWORD",
"value": "40396"
},
{
"context": "g Zheng', github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle', ",
"end": 1580,
"score": 0.45213690400123596,
"start": 1579,
"tag": "KEY",
"value": "4"
},
{
"context": " Zheng', github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle', github:",
"end": 1587,
"score": 0.47613397240638733,
"start": 1580,
"tag": "PASSWORD",
"value": "dfe5676"
},
{
"context": ", github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle', github: ",
"end": 1588,
"score": 0.43671655654907227,
"start": 1587,
"tag": "KEY",
"value": "9"
},
{
"context": " github: 'shiyingzheng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle', github: 'mlewisno",
"end": 1597,
"score": 0.46530234813690186,
"start": 1588,
"tag": "PASSWORD",
"value": "115d7da96"
},
{
"context": "eng'}\n {id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle', github: 'mlewisno'}\n {id: '52b8be459e47006b4",
"end": 1627,
"score": 0.9998802542686462,
"start": 1607,
"tag": "NAME",
"value": "Mischa Lewis-Norelle"
},
{
"context": "15d7da96', name: 'Mischa Lewis-Norelle', github: 'mlewisno'}\n {id: '52b8be459e47006b4100094b', name: 'Pau",
"end": 1647,
"score": 0.936906099319458,
"start": 1639,
"tag": "USERNAME",
"value": "mlewisno"
},
{
"context": "cha Lewis-Norelle', github: 'mlewisno'}\n {id: '52b8be459e47006b4100094b', name: 'Paul Buser'}\n {id: '54039",
"end": 1672,
"score": 0.4171372652053833,
"start": 1660,
"tag": "KEY",
"value": "52b8be459e47"
},
{
"context": "e', github: 'mlewisno'}\n {id: '52b8be459e47006b4100094b', name: 'Paul Buser'}\n {id: '540396effe5676911",
"end": 1684,
"score": 0.3915322422981262,
"start": 1676,
"tag": "KEY",
"value": "4100094b"
},
{
"context": "sno'}\n {id: '52b8be459e47006b4100094b', name: 'Paul Buser'}\n {id: '540396effe56769115d7daa8', name: 'Ben",
"end": 1704,
"score": 0.9998665452003479,
"start": 1694,
"tag": "NAME",
"value": "Paul Buser"
},
{
"context": "59e47006b4100094b', name: 'Paul Buser'}\n {id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}\n ",
"end": 1720,
"score": 0.48054322600364685,
"start": 1717,
"tag": "KEY",
"value": "540"
},
{
"context": "47006b4100094b', name: 'Paul Buser'}\n {id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}\n ",
"end": 1721,
"score": 0.3744347393512726,
"start": 1720,
"tag": "PASSWORD",
"value": "3"
},
{
"context": "7006b4100094b', name: 'Paul Buser'}\n {id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}\n {id:",
"end": 1726,
"score": 0.40239420533180237,
"start": 1721,
"tag": "KEY",
"value": "96eff"
},
{
"context": "4100094b', name: 'Paul Buser'}\n {id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}\n {id: ",
"end": 1727,
"score": 0.387106716632843,
"start": 1726,
"tag": "PASSWORD",
"value": "e"
},
{
"context": "100094b', name: 'Paul Buser'}\n {id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}\n {id: '5403974b11058",
"end": 1741,
"score": 0.4374559223651886,
"start": 1727,
"tag": "KEY",
"value": "56769115d7daa8"
},
{
"context": "ser'}\n {id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}\n {id: '5403974b11058b4213074779', name: 'Ale",
"end": 1765,
"score": 0.9998558759689331,
"start": 1751,
"tag": "NAME",
"value": "Benjamin Stern"
},
{
"context": "ern'}\n {id: '5403974b11058b4213074779', name: 'Alex Cotsarelis'}\n {id: '54039780fe56769115d7dab5', name: 'Ken",
"end": 1827,
"score": 0.9998710751533508,
"start": 1812,
"tag": "NAME",
"value": "Alex Cotsarelis"
},
{
"context": "8b4213074779', name: 'Alex Cotsarelis'}\n {id: '54039780fe56769115d7dab5', name: 'Ken Stanley'}\n ",
"end": 1842,
"score": 0.4655553102493286,
"start": 1840,
"tag": "KEY",
"value": "54"
},
{
"context": "lis'}\n {id: '54039780fe56769115d7dab5', name: 'Ken Stanley'}\n {id: '531258b5e0789d4609614110', name: 'Rub",
"end": 1885,
"score": 0.9998258352279663,
"start": 1874,
"tag": "NAME",
"value": "Ken Stanley"
},
{
"context": "ley'}\n {id: '531258b5e0789d4609614110', name: 'Ruben Vereecken', github: 'rubenvereecken'}\n {id: '5276ad5dcf8",
"end": 1947,
"score": 0.9998729825019836,
"start": 1932,
"tag": "NAME",
"value": "Ruben Vereecken"
},
{
"context": "89d4609614110', name: 'Ruben Vereecken', github: 'rubenvereecken'}\n {id: '5276ad5dcf83207a2801d3b4', name: 'Zac",
"end": 1973,
"score": 0.9532477259635925,
"start": 1959,
"tag": "USERNAME",
"value": "rubenvereecken"
},
{
"context": "n Vereecken', github: 'rubenvereecken'}\n {id: '5276ad5dcf83207a2801d3b4', name: 'Zach Martin', githu",
"end": 1989,
"score": 0.43039190769195557,
"start": 1986,
"tag": "KEY",
"value": "527"
},
{
"context": ": 'rubenvereecken'}\n {id: '5276ad5dcf83207a2801d3b4', name: 'Zach Martin', github: 'zachster01'}\n ",
"end": 2007,
"score": 0.3395073711872101,
"start": 2006,
"tag": "KEY",
"value": "d"
},
{
"context": "'rubenvereecken'}\n {id: '5276ad5dcf83207a2801d3b4', name: 'Zach Martin', github: 'zachster01'}\n ",
"end": 2009,
"score": 0.3602900505065918,
"start": 2008,
"tag": "KEY",
"value": "b"
},
{
"context": "ken'}\n {id: '5276ad5dcf83207a2801d3b4', name: 'Zach Martin', github: 'zachster01'}\n {id: '530df0cbc068544",
"end": 2031,
"score": 0.9998541474342346,
"start": 2020,
"tag": "NAME",
"value": "Zach Martin"
},
{
"context": "dcf83207a2801d3b4', name: 'Zach Martin', github: 'zachster01'}\n {id: '530df0cbc06854403ba67c15', name: 'Ale",
"end": 2053,
"score": 0.9675491452217102,
"start": 2043,
"tag": "USERNAME",
"value": "zachster01"
},
{
"context": "r01'}\n {id: '530df0cbc06854403ba67c15', name: 'Alexandru Caciulescu', github: 'Darredevil'}\n {id: '5268d9baa39d7db",
"end": 2120,
"score": 0.9998637437820435,
"start": 2100,
"tag": "NAME",
"value": "Alexandru Caciulescu"
},
{
"context": "3ba67c15', name: 'Alexandru Caciulescu', github: 'Darredevil'}\n {id: '5268d9baa39d7db617000b18', name: 'Tha",
"end": 2142,
"score": 0.9389858841896057,
"start": 2132,
"tag": "USERNAME",
"value": "Darredevil"
},
{
"context": "ndru Caciulescu', github: 'Darredevil'}\n {id: '5268d9baa39d7db617000b18', name: 'Thanish Muhammed', github: 'mnmtanish'}\n",
"end": 2179,
"score": 0.7708176374435425,
"start": 2155,
"tag": "KEY",
"value": "5268d9baa39d7db617000b18"
},
{
"context": "vil'}\n {id: '5268d9baa39d7db617000b18', name: 'Thanish Muhammed', github: 'mnmtanish'}\n {id: '53232f458e54704b",
"end": 2205,
"score": 0.9998709559440613,
"start": 2189,
"tag": "NAME",
"value": "Thanish Muhammed"
},
{
"context": "7db617000b18', name: 'Thanish Muhammed', github: 'mnmtanish'}\n {id: '53232f458e54704b074b271d', name: 'Ban",
"end": 2226,
"score": 0.9773061275482178,
"start": 2217,
"tag": "USERNAME",
"value": "mnmtanish"
},
{
"context": "Thanish Muhammed', github: 'mnmtanish'}\n {id: '53232f458e54704b074b271d', name: 'Bang Honam', github: 'walkingtospace'}\n ",
"end": 2263,
"score": 0.625156581401825,
"start": 2239,
"tag": "KEY",
"value": "53232f458e54704b074b271d"
},
{
"context": "ish'}\n {id: '53232f458e54704b074b271d', name: 'Bang Honam', github: 'walkingtospace'}\n {id: '52d16c1dc93",
"end": 2283,
"score": 0.999829888343811,
"start": 2273,
"tag": "NAME",
"value": "Bang Honam"
},
{
"context": "458e54704b074b271d', name: 'Bang Honam', github: 'walkingtospace'}\n {id: '52d16c1dc931e2544d001daa', name: 'Dav",
"end": 2309,
"score": 0.9144168496131897,
"start": 2295,
"tag": "USERNAME",
"value": "walkingtospace"
},
{
"context": "'Bang Honam', github: 'walkingtospace'}\n {id: '52d16c1dc931e2544d001daa', name: 'David Pendray', github: 'dpen2000'}\n ",
"end": 2346,
"score": 0.6337051391601562,
"start": 2322,
"tag": "KEY",
"value": "52d16c1dc931e2544d001daa"
},
{
"context": "ace'}\n {id: '52d16c1dc931e2544d001daa', name: 'David Pendray', github: 'dpen2000'}\n {id: '53132ea1828a17061",
"end": 2369,
"score": 0.9998498558998108,
"start": 2356,
"tag": "NAME",
"value": "David Pendray"
},
{
"context": "931e2544d001daa', name: 'David Pendray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dom",
"end": 2389,
"score": 0.955287754535675,
"start": 2381,
"tag": "USERNAME",
"value": "dpen2000"
},
{
"context": "e: 'David Pendray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id:",
"end": 2411,
"score": 0.5254397392272949,
"start": 2402,
"tag": "KEY",
"value": "53132ea18"
},
{
"context": " Pendray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '",
"end": 2413,
"score": 0.467242568731308,
"start": 2411,
"tag": "PASSWORD",
"value": "28"
},
{
"context": "endray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '5",
"end": 2414,
"score": 0.46692606806755066,
"start": 2413,
"tag": "KEY",
"value": "a"
},
{
"context": "ndray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '53",
"end": 2415,
"score": 0.45081403851509094,
"start": 2414,
"tag": "PASSWORD",
"value": "1"
},
{
"context": "dray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530",
"end": 2416,
"score": 0.47297948598861694,
"start": 2415,
"tag": "KEY",
"value": "7"
},
{
"context": "ray', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530e",
"end": 2417,
"score": 0.45839762687683105,
"start": 2416,
"tag": "PASSWORD",
"value": "0"
},
{
"context": "ay', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530eb2",
"end": 2419,
"score": 0.4860575199127197,
"start": 2417,
"tag": "KEY",
"value": "61"
},
{
"context": "', github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530eb293",
"end": 2421,
"score": 0.4645620286464691,
"start": 2419,
"tag": "PASSWORD",
"value": "08"
},
{
"context": " github: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530eb29347a",
"end": 2424,
"score": 0.48864904046058655,
"start": 2421,
"tag": "KEY",
"value": "ebb"
},
{
"context": "thub: 'dpen2000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530eb29347a89",
"end": 2426,
"score": 0.5457481145858765,
"start": 2424,
"tag": "PASSWORD",
"value": "38"
},
{
"context": "000'}\n {id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530eb29347a891b3518b3990', name: 'Ian",
"end": 2450,
"score": 0.9998621344566345,
"start": 2436,
"tag": "NAME",
"value": "Dominik Kundel"
},
{
"context": "a1706108ebb38', name: 'Dominik Kundel'}\n {id: '530eb29347a891b3518b3990', name: 'Ian Li'}\n {id: '531cd81dd00d2dc30991f",
"end": 2487,
"score": 0.751217246055603,
"start": 2463,
"tag": "KEY",
"value": "530eb29347a891b3518b3990"
},
{
"context": "del'}\n {id: '530eb29347a891b3518b3990', name: 'Ian Li'}\n {id: '531cd81dd00d2dc30991f924', name: 'Rus",
"end": 2503,
"score": 0.9998152256011963,
"start": 2497,
"tag": "NAME",
"value": "Ian Li"
},
{
"context": "eb29347a891b3518b3990', name: 'Ian Li'}\n {id: '531cd81dd00d2dc30991f924', name: 'Russ Fan'}\n {id: '53064b1905a6ad96734",
"end": 2540,
"score": 0.7952771186828613,
"start": 2516,
"tag": "KEY",
"value": "531cd81dd00d2dc30991f924"
},
{
"context": " Li'}\n {id: '531cd81dd00d2dc30991f924', name: 'Russ Fan'}\n {id: '53064b1905a6ad967346e654', name: 'Yan",
"end": 2558,
"score": 0.9998576641082764,
"start": 2550,
"tag": "NAME",
"value": "Russ Fan"
},
{
"context": "81dd00d2dc30991f924', name: 'Russ Fan'}\n {id: '53064b1905a6ad967346e654', name: 'Yang Shun'}\n {name: 'devast8a', avata",
"end": 2595,
"score": 0.6133580207824707,
"start": 2571,
"tag": "KEY",
"value": "53064b1905a6ad967346e654"
},
{
"context": "Fan'}\n {id: '53064b1905a6ad967346e654', name: 'Yang Shun'}\n {name: 'devast8a', avatar: '', github: 'dev",
"end": 2614,
"score": 0.9997963905334473,
"start": 2605,
"tag": "NAME",
"value": "Yang Shun"
},
{
"context": "05a6ad967346e654', name: 'Yang Shun'}\n {name: 'devast8a', avatar: '', github: 'devast8a'}\n ]\n",
"end": 2637,
"score": 0.9958149194717407,
"start": 2629,
"tag": "USERNAME",
"value": "devast8a"
},
{
"context": "hun'}\n {name: 'devast8a', avatar: '', github: 'devast8a'}\n ]\n",
"end": 2669,
"score": 0.9967545866966248,
"start": 2661,
"tag": "USERNAME",
"value": "devast8a"
}
] | app/views/contribute/ArchmageView.coffee | cihatislamdede/codecombat | 4,858 | ContributeClassView = require './ContributeClassView'
template = require 'templates/contribute/archmage'
ContactModal = require 'views/core/ContactModal'
module.exports = class ArchmageView extends ContributeClassView
id: 'archmage-view'
template: template
events:
'click [data-toggle="coco-modal"][data-target="core/ContactModal"]': 'openContactModal'
initialize: ->
@contributorClassName = 'archmage'
openContactModal: (e) ->
e.stopPropagation()
@openModalView new ContactModal()
contributors: [
{id: '547acbb2af18b03c0563fdb3', name: 'David Liu', github: 'trotod'}
{id: '52ccfc9bd3eb6b5a4100b60d', name: 'Glen De Cauwsemaecker', github: 'GlenDC'}
{id: '52bfc3ecb7ec628868001297', name: 'Tom Steinbrecher', github: 'TomSteinbrecher'}
{id: '5272806093680c5817033f73', name: 'Sébastien Moratinos', github: 'smoratinos'}
{id: '52d133893dc46cbe15001179', name: 'Deepak Raj', github: 'deepak1556'}
{id: '52699df70e404d591b000af7', name: 'Ronnie Cheng', github: 'rhc2104'}
{id: '5260b4c3ae8ec6795e000019', name: 'Chloe Fan', github: 'chloester'}
{id: '52d726ab3c70cec90c008f2d', name: 'Rachel Xiang', github: 'rdxiang'}
{id: '5286706d93df39a952001574', name: 'Dan Ristic', github: 'dristic'}
{id: '52cec8620b0d5c1b4c0039e6', name: 'Brad Dickason', github: 'bdickason'}
{id: '540397e2bc5b69a40e9c2fb1', name: 'Rebecca Saines'}
{id: '525ae40248839d81090013f2', name: 'Laura Watiker', github: 'lwatiker'}
{id: '540395e9fe56769115d7da86', name: 'Shiying Zheng', github: 'shiyingzheng'}
{id: '5403964dfe56769115d7da96', name: 'Mischa Lewis-Norelle', github: 'mlewisno'}
{id: '52b8be459e47006b4100094b', name: 'Paul Buser'}
{id: '540396effe56769115d7daa8', name: 'Benjamin Stern'}
{id: '5403974b11058b4213074779', name: 'Alex Cotsarelis'}
{id: '54039780fe56769115d7dab5', name: 'Ken Stanley'}
{id: '531258b5e0789d4609614110', name: 'Ruben Vereecken', github: 'rubenvereecken'}
{id: '5276ad5dcf83207a2801d3b4', name: 'Zach Martin', github: 'zachster01'}
{id: '530df0cbc06854403ba67c15', name: 'Alexandru Caciulescu', github: 'Darredevil'}
{id: '5268d9baa39d7db617000b18', name: 'Thanish Muhammed', github: 'mnmtanish'}
{id: '53232f458e54704b074b271d', name: 'Bang Honam', github: 'walkingtospace'}
{id: '52d16c1dc931e2544d001daa', name: 'David Pendray', github: 'dpen2000'}
{id: '53132ea1828a1706108ebb38', name: 'Dominik Kundel'}
{id: '530eb29347a891b3518b3990', name: 'Ian Li'}
{id: '531cd81dd00d2dc30991f924', name: 'Russ Fan'}
{id: '53064b1905a6ad967346e654', name: 'Yang Shun'}
{name: 'devast8a', avatar: '', github: 'devast8a'}
]
| 156036 | ContributeClassView = require './ContributeClassView'
template = require 'templates/contribute/archmage'
ContactModal = require 'views/core/ContactModal'
module.exports = class ArchmageView extends ContributeClassView
id: 'archmage-view'
template: template
events:
'click [data-toggle="coco-modal"][data-target="core/ContactModal"]': 'openContactModal'
initialize: ->
@contributorClassName = 'archmage'
openContactModal: (e) ->
e.stopPropagation()
@openModalView new ContactModal()
contributors: [
{id: '<KEY>', name: '<NAME>', github: 'trotod'}
{id: '<KEY> <PASSWORD>ccfc9bd3eb6<PASSWORD>5a4100<PASSWORD>', name: '<NAME>', github: 'GlenDC'}
{id: '<KEY> <PASSWORD>', name: '<NAME>', github: 'TomSteinbrecher'}
{id: '<KEY> <PASSWORD> <KEY> <PASSWORD>', name: '<NAME>', github: 'smoratinos'}
{id: '<KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD>', name: '<NAME>', github: 'deepak1556'}
{id: '<KEY> <PASSWORD>', name: '<NAME>', github: 'rhc2104'}
{id: '<KEY>260b4c3ae8ec6795e000019', name: '<NAME>', github: 'chloester'}
{id: '<PASSWORD>', name: '<NAME>', github: 'rdxiang'}
{id: '5286706d93df39a9<PASSWORD>574', name: '<NAME>', github: 'dristic'}
{id: '<KEY>2cec8620b0d5c1b4c0039e6', name: '<NAME>', github: 'bdickason'}
{id: '<KEY>40397e2bc5b69a40e9c2fb1', name: '<NAME>'}
{id: '<KEY>25ae40248839d81090013f2', name: '<NAME>', github: 'lwatiker'}
{id: '<KEY> <PASSWORD> <KEY> <PASSWORD>', name: '<NAME>', github: 'shiyingzheng'}
{id: '<KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD>', name: '<NAME>', github: 'mlewisno'}
{id: '<KEY>006b<KEY>', name: '<NAME>'}
{id: '<KEY> <KEY> <KEY> <PASSWORD> <KEY>', name: '<NAME>'}
{id: '5403974b11058b4213074779', name: '<NAME>'}
{id: '<KEY>039780fe56769115d7dab5', name: '<NAME>'}
{id: '531258b5e0789d4609614110', name: '<NAME>', github: 'rubenvereecken'}
{id: '<KEY>6ad5dcf83207a2801<KEY>3<PASSWORD>4', name: '<NAME>', github: 'zachster01'}
{id: '530df0cbc06854403ba67c15', name: '<NAME>', github: 'Darredevil'}
{id: '<KEY>', name: '<NAME>', github: 'mnmtanish'}
{id: '<KEY>', name: '<NAME>', github: 'walkingtospace'}
{id: '<KEY>', name: '<NAME>', github: 'dpen2000'}
{id: '<KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD> <KEY> <PASSWORD>', name: '<NAME>'}
{id: '<KEY>', name: '<NAME>'}
{id: '<KEY>', name: '<NAME>'}
{id: '<KEY>', name: '<NAME>'}
{name: 'devast8a', avatar: '', github: 'devast8a'}
]
| true | ContributeClassView = require './ContributeClassView'
template = require 'templates/contribute/archmage'
ContactModal = require 'views/core/ContactModal'
module.exports = class ArchmageView extends ContributeClassView
id: 'archmage-view'
template: template
events:
'click [data-toggle="coco-modal"][data-target="core/ContactModal"]': 'openContactModal'
initialize: ->
@contributorClassName = 'archmage'
openContactModal: (e) ->
e.stopPropagation()
@openModalView new ContactModal()
contributors: [
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'trotod'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PIccfc9bd3eb6PI:PASSWORD:<PASSWORD>END_PI5a4100PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'GlenDC'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'TomSteinbrecher'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'smoratinos'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'deepak1556'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'rhc2104'}
{id: 'PI:KEY:<KEY>END_PI260b4c3ae8ec6795e000019', name: 'PI:NAME:<NAME>END_PI', github: 'chloester'}
{id: 'PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'rdxiang'}
{id: '5286706d93df39a9PI:PASSWORD:<PASSWORD>END_PI574', name: 'PI:NAME:<NAME>END_PI', github: 'dristic'}
{id: 'PI:KEY:<KEY>END_PI2cec8620b0d5c1b4c0039e6', name: 'PI:NAME:<NAME>END_PI', github: 'bdickason'}
{id: 'PI:KEY:<KEY>END_PI40397e2bc5b69a40e9c2fb1', name: 'PI:NAME:<NAME>END_PI'}
{id: 'PI:KEY:<KEY>END_PI25ae40248839d81090013f2', name: 'PI:NAME:<NAME>END_PI', github: 'lwatiker'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'shiyingzheng'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'mlewisno'}
{id: 'PI:KEY:<KEY>END_PI006bPI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<KEY>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI'}
{id: '5403974b11058b4213074779', name: 'PI:NAME:<NAME>END_PI'}
{id: 'PI:KEY:<KEY>END_PI039780fe56769115d7dab5', name: 'PI:NAME:<NAME>END_PI'}
{id: '531258b5e0789d4609614110', name: 'PI:NAME:<NAME>END_PI', github: 'rubenvereecken'}
{id: 'PI:KEY:<KEY>END_PI6ad5dcf83207a2801PI:KEY:<KEY>END_PI3PI:KEY:<PASSWORD>END_PI4', name: 'PI:NAME:<NAME>END_PI', github: 'zachster01'}
{id: '530df0cbc06854403ba67c15', name: 'PI:NAME:<NAME>END_PI', github: 'Darredevil'}
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'mnmtanish'}
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'walkingtospace'}
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI', github: 'dpen2000'}
{id: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI', name: 'PI:NAME:<NAME>END_PI'}
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI'}
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI'}
{id: 'PI:KEY:<KEY>END_PI', name: 'PI:NAME:<NAME>END_PI'}
{name: 'devast8a', avatar: '', github: 'devast8a'}
]
|
[
{
"context": "te Port: serverPort\n //Update Username: userName\n //Update Password: password\n ",
"end": 270,
"score": 0.9996236562728882,
"start": 262,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " Username: userName\n //Update Password: password\n //Datasource ID comes after /datasour",
"end": 310,
"score": 0.9993504285812378,
"start": 302,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ddress=\\\"newAddr\\\" serverPort=\\\"5435\\\" userName=\\\"newUserName\\\" password=\\\"newPass\\\" />\\n</tsRequest>\"\n ",
"end": 843,
"score": 0.9995403289794922,
"start": 832,
"tag": "USERNAME",
"value": "newUserName"
},
{
"context": "Port=\\\"5435\\\" userName=\\\"newUserName\\\" password=\\\"newPass\\\" />\\n</tsRequest>\"\n }\n\n ",
"end": 864,
"score": 0.9993443489074707,
"start": 857,
"tag": "PASSWORD",
"value": "newPass"
}
] | snippets/updatedatasourceconn.cson | cmtoomey/TableauRESTJS | 1 | '.source.js':
'Update Data Source Connection':
'prefix': 'trudc'
'body': """
//Update Data Source Connection
//Update Server address: connection serverAddress
//Update Port: serverPort
//Update Username: userName
//Update Password: password
//Datasource ID comes after /datasources/
function updateDsConnection() {
var settings = {
"async": true,
"crossDomain": true,
"url": url + "sites/" + siteid + "/datasources/"+datasourceID+"/connection",
"method": "PUT",
"headers": {
"x-tableau-auth": auth
},
"data": "<tsRequest>\n\t<connection serverAddress=\"newAddr\" serverPort=\"5435\" userName=\"newUserName\" password=\"newPass\" />\n</tsRequest>"
}
$.ajax(settings).done(function(response) {
console.log(response);
});
}
"""
| 43806 | '.source.js':
'Update Data Source Connection':
'prefix': 'trudc'
'body': """
//Update Data Source Connection
//Update Server address: connection serverAddress
//Update Port: serverPort
//Update Username: userName
//Update Password: <PASSWORD>
//Datasource ID comes after /datasources/
function updateDsConnection() {
var settings = {
"async": true,
"crossDomain": true,
"url": url + "sites/" + siteid + "/datasources/"+datasourceID+"/connection",
"method": "PUT",
"headers": {
"x-tableau-auth": auth
},
"data": "<tsRequest>\n\t<connection serverAddress=\"newAddr\" serverPort=\"5435\" userName=\"newUserName\" password=\"<PASSWORD>\" />\n</tsRequest>"
}
$.ajax(settings).done(function(response) {
console.log(response);
});
}
"""
| true | '.source.js':
'Update Data Source Connection':
'prefix': 'trudc'
'body': """
//Update Data Source Connection
//Update Server address: connection serverAddress
//Update Port: serverPort
//Update Username: userName
//Update Password: PI:PASSWORD:<PASSWORD>END_PI
//Datasource ID comes after /datasources/
function updateDsConnection() {
var settings = {
"async": true,
"crossDomain": true,
"url": url + "sites/" + siteid + "/datasources/"+datasourceID+"/connection",
"method": "PUT",
"headers": {
"x-tableau-auth": auth
},
"data": "<tsRequest>\n\t<connection serverAddress=\"newAddr\" serverPort=\"5435\" userName=\"newUserName\" password=\"PI:PASSWORD:<PASSWORD>END_PI\" />\n</tsRequest>"
}
$.ajax(settings).done(function(response) {
console.log(response);
});
}
"""
|
[
{
"context": "ode.\n try\n key = '_storage_test'\n sessionStorage.setItem(key, ",
"end": 4675,
"score": 0.9974186420440674,
"start": 4661,
"tag": "KEY",
"value": "'_storage_test"
}
] | bower_components/jqTree/src/save_state_handler.coffee | mwelsman/js-scheme | 3 | util = require './util'
indexOf = util.indexOf
isInt = util.isInt
class SaveStateHandler
constructor: (tree_widget) ->
@tree_widget = tree_widget
saveState: ->
state = JSON.stringify(@getState())
if @tree_widget.options.onSetStateFromStorage
@tree_widget.options.onSetStateFromStorage(state)
else if @supportsLocalStorage()
localStorage.setItem(
@getCookieName(),
state
)
else if $.cookie
$.cookie.raw = true
$.cookie(
@getCookieName(),
state,
{path: '/'}
)
getStateFromStorage: ->
json_data = @_loadFromStorage()
if json_data
return @_parseState(json_data)
else
return null
_parseState: (json_data) ->
state = $.parseJSON(json_data)
# Check if selected_node is an int (instead of an array)
if state and state.selected_node and isInt(state.selected_node)
# Convert to array
state.selected_node = [state.selected_node]
return state
_loadFromStorage: ->
if @tree_widget.options.onGetStateFromStorage
return @tree_widget.options.onGetStateFromStorage()
else if @supportsLocalStorage()
return localStorage.getItem(
@getCookieName()
)
else if $.cookie
$.cookie.raw = true
return $.cookie(@getCookieName())
else
return null
getState: ->
getOpenNodeIds = =>
open_nodes = []
@tree_widget.tree.iterate((node) =>
if (
node.is_open and
node.id and
node.hasChildren()
)
open_nodes.push(node.id)
return true
)
return open_nodes
getSelectedNodeIds = =>
return (n.id for n in @tree_widget.getSelectedNodes())
return {
open_nodes: getOpenNodeIds(),
selected_node: getSelectedNodeIds()
}
# Set initial state
# Don't handle nodes that are loaded on demand
#
# result: must load on demand
setInitialState: (state) ->
if not state
return false
else
must_load_on_demand = @_openInitialNodes(state.open_nodes)
@_selectInitialNodes(state.selected_node)
return must_load_on_demand
_openInitialNodes: (node_ids) ->
must_load_on_demand = false
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if node
if not node.load_on_demand
node.is_open = true
else
must_load_on_demand = true
return must_load_on_demand
_selectInitialNodes: (node_ids) ->
select_count = 0
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if node
select_count += 1
@tree_widget.select_node_handler.addToSelection(node)
return select_count != 0
setInitialStateOnDemand: (state) ->
if state
@_setInitialStateOnDemand(state.open_nodes, state.selected_node)
_setInitialStateOnDemand: (node_ids, selected_nodes) ->
openNodes = =>
new_nodes_ids = []
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if not node
new_nodes_ids.push(node_id)
else
if not node.is_loading
if node.load_on_demand
loadAndOpenNode(node)
else
@tree_widget._openNode(node, false)
node_ids = new_nodes_ids
if @_selectInitialNodes(selected_nodes)
@tree_widget._refreshElements()
loadAndOpenNode = (node) =>
@tree_widget._openNode(node, false, openNodes)
openNodes()
getCookieName: ->
if typeof @tree_widget.options.saveState is 'string'
return @tree_widget.options.saveState
else
return 'tree'
supportsLocalStorage: ->
testSupport = ->
# Is local storage supported?
if not localStorage?
return false
else
# Check if it's possible to store an item. Safari does not allow this in private browsing mode.
try
key = '_storage_test'
sessionStorage.setItem(key, true);
sessionStorage.removeItem(key)
catch error
return false
return true
if not @_supportsLocalStorage?
@_supportsLocalStorage = testSupport()
return @_supportsLocalStorage
getNodeIdToBeSelected: ->
state = @getStateFromStorage()
if state and state.selected_node
return state.selected_node[0]
else
return null
module.exports = SaveStateHandler
| 60985 | util = require './util'
indexOf = util.indexOf
isInt = util.isInt
class SaveStateHandler
constructor: (tree_widget) ->
@tree_widget = tree_widget
saveState: ->
state = JSON.stringify(@getState())
if @tree_widget.options.onSetStateFromStorage
@tree_widget.options.onSetStateFromStorage(state)
else if @supportsLocalStorage()
localStorage.setItem(
@getCookieName(),
state
)
else if $.cookie
$.cookie.raw = true
$.cookie(
@getCookieName(),
state,
{path: '/'}
)
getStateFromStorage: ->
json_data = @_loadFromStorage()
if json_data
return @_parseState(json_data)
else
return null
_parseState: (json_data) ->
state = $.parseJSON(json_data)
# Check if selected_node is an int (instead of an array)
if state and state.selected_node and isInt(state.selected_node)
# Convert to array
state.selected_node = [state.selected_node]
return state
_loadFromStorage: ->
if @tree_widget.options.onGetStateFromStorage
return @tree_widget.options.onGetStateFromStorage()
else if @supportsLocalStorage()
return localStorage.getItem(
@getCookieName()
)
else if $.cookie
$.cookie.raw = true
return $.cookie(@getCookieName())
else
return null
getState: ->
getOpenNodeIds = =>
open_nodes = []
@tree_widget.tree.iterate((node) =>
if (
node.is_open and
node.id and
node.hasChildren()
)
open_nodes.push(node.id)
return true
)
return open_nodes
getSelectedNodeIds = =>
return (n.id for n in @tree_widget.getSelectedNodes())
return {
open_nodes: getOpenNodeIds(),
selected_node: getSelectedNodeIds()
}
# Set initial state
# Don't handle nodes that are loaded on demand
#
# result: must load on demand
setInitialState: (state) ->
if not state
return false
else
must_load_on_demand = @_openInitialNodes(state.open_nodes)
@_selectInitialNodes(state.selected_node)
return must_load_on_demand
_openInitialNodes: (node_ids) ->
must_load_on_demand = false
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if node
if not node.load_on_demand
node.is_open = true
else
must_load_on_demand = true
return must_load_on_demand
_selectInitialNodes: (node_ids) ->
select_count = 0
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if node
select_count += 1
@tree_widget.select_node_handler.addToSelection(node)
return select_count != 0
setInitialStateOnDemand: (state) ->
if state
@_setInitialStateOnDemand(state.open_nodes, state.selected_node)
_setInitialStateOnDemand: (node_ids, selected_nodes) ->
openNodes = =>
new_nodes_ids = []
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if not node
new_nodes_ids.push(node_id)
else
if not node.is_loading
if node.load_on_demand
loadAndOpenNode(node)
else
@tree_widget._openNode(node, false)
node_ids = new_nodes_ids
if @_selectInitialNodes(selected_nodes)
@tree_widget._refreshElements()
loadAndOpenNode = (node) =>
@tree_widget._openNode(node, false, openNodes)
openNodes()
getCookieName: ->
if typeof @tree_widget.options.saveState is 'string'
return @tree_widget.options.saveState
else
return 'tree'
supportsLocalStorage: ->
testSupport = ->
# Is local storage supported?
if not localStorage?
return false
else
# Check if it's possible to store an item. Safari does not allow this in private browsing mode.
try
key = <KEY>'
sessionStorage.setItem(key, true);
sessionStorage.removeItem(key)
catch error
return false
return true
if not @_supportsLocalStorage?
@_supportsLocalStorage = testSupport()
return @_supportsLocalStorage
getNodeIdToBeSelected: ->
state = @getStateFromStorage()
if state and state.selected_node
return state.selected_node[0]
else
return null
module.exports = SaveStateHandler
| true | util = require './util'
indexOf = util.indexOf
isInt = util.isInt
class SaveStateHandler
constructor: (tree_widget) ->
@tree_widget = tree_widget
saveState: ->
state = JSON.stringify(@getState())
if @tree_widget.options.onSetStateFromStorage
@tree_widget.options.onSetStateFromStorage(state)
else if @supportsLocalStorage()
localStorage.setItem(
@getCookieName(),
state
)
else if $.cookie
$.cookie.raw = true
$.cookie(
@getCookieName(),
state,
{path: '/'}
)
getStateFromStorage: ->
json_data = @_loadFromStorage()
if json_data
return @_parseState(json_data)
else
return null
_parseState: (json_data) ->
state = $.parseJSON(json_data)
# Check if selected_node is an int (instead of an array)
if state and state.selected_node and isInt(state.selected_node)
# Convert to array
state.selected_node = [state.selected_node]
return state
_loadFromStorage: ->
if @tree_widget.options.onGetStateFromStorage
return @tree_widget.options.onGetStateFromStorage()
else if @supportsLocalStorage()
return localStorage.getItem(
@getCookieName()
)
else if $.cookie
$.cookie.raw = true
return $.cookie(@getCookieName())
else
return null
getState: ->
getOpenNodeIds = =>
open_nodes = []
@tree_widget.tree.iterate((node) =>
if (
node.is_open and
node.id and
node.hasChildren()
)
open_nodes.push(node.id)
return true
)
return open_nodes
getSelectedNodeIds = =>
return (n.id for n in @tree_widget.getSelectedNodes())
return {
open_nodes: getOpenNodeIds(),
selected_node: getSelectedNodeIds()
}
# Set initial state
# Don't handle nodes that are loaded on demand
#
# result: must load on demand
setInitialState: (state) ->
if not state
return false
else
must_load_on_demand = @_openInitialNodes(state.open_nodes)
@_selectInitialNodes(state.selected_node)
return must_load_on_demand
_openInitialNodes: (node_ids) ->
must_load_on_demand = false
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if node
if not node.load_on_demand
node.is_open = true
else
must_load_on_demand = true
return must_load_on_demand
_selectInitialNodes: (node_ids) ->
select_count = 0
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if node
select_count += 1
@tree_widget.select_node_handler.addToSelection(node)
return select_count != 0
setInitialStateOnDemand: (state) ->
if state
@_setInitialStateOnDemand(state.open_nodes, state.selected_node)
_setInitialStateOnDemand: (node_ids, selected_nodes) ->
openNodes = =>
new_nodes_ids = []
for node_id in node_ids
node = @tree_widget.getNodeById(node_id)
if not node
new_nodes_ids.push(node_id)
else
if not node.is_loading
if node.load_on_demand
loadAndOpenNode(node)
else
@tree_widget._openNode(node, false)
node_ids = new_nodes_ids
if @_selectInitialNodes(selected_nodes)
@tree_widget._refreshElements()
loadAndOpenNode = (node) =>
@tree_widget._openNode(node, false, openNodes)
openNodes()
getCookieName: ->
if typeof @tree_widget.options.saveState is 'string'
return @tree_widget.options.saveState
else
return 'tree'
supportsLocalStorage: ->
testSupport = ->
# Is local storage supported?
if not localStorage?
return false
else
# Check if it's possible to store an item. Safari does not allow this in private browsing mode.
try
key = PI:KEY:<KEY>END_PI'
sessionStorage.setItem(key, true);
sessionStorage.removeItem(key)
catch error
return false
return true
if not @_supportsLocalStorage?
@_supportsLocalStorage = testSupport()
return @_supportsLocalStorage
getNodeIdToBeSelected: ->
state = @getStateFromStorage()
if state and state.selected_node
return state.selected_node[0]
else
return null
module.exports = SaveStateHandler
|
[
{
"context": "st-unloading iframes. Most of this is taken from\n# Steven Wittens (@unconed): https://github.com/unconed/fullfronta",
"end": 94,
"score": 0.9989172220230103,
"start": 80,
"tag": "NAME",
"value": "Steven Wittens"
},
{
"context": "rames. Most of this is taken from\n# Steven Wittens (@unconed): https://github.com/unconed/fullfrontal, but I'v",
"end": 104,
"score": 0.9996985793113708,
"start": 95,
"tag": "USERNAME",
"value": "(@unconed"
},
{
"context": "m\n# Steven Wittens (@unconed): https://github.com/unconed/fullfrontal, but I've\n# tried to separate out the",
"end": 133,
"score": 0.99965500831604,
"start": 126,
"tag": "USERNAME",
"value": "unconed"
}
] | scripts/iframes.coffee | lmjohns3/deck | 0 | # Code for pre-loading and post-unloading iframes. Most of this is taken from
# Steven Wittens (@unconed): https://github.com/unconed/fullfrontal, but I've
# tried to separate out the iframe handling from interactions with mathbox,
# since it's nice to have videos auto-load even if you're not using math.
TRANSITION = 300
$IFRAME_INDEX = {}
disableIframe = (iframe) ->
return if $(iframe).data('src')
src = $(iframe).attr('src')
$(iframe).data('src', src)
iframe.onload = null
iframe.src = 'about:blank'
enableIframe = (iframe) ->
src = $(iframe).data('src')
return unless src
iframe.src = src
$(iframe).data('src', null)
changeSlide = (e, from, to) ->
$subslide = $.deck('getSlide', to)
$parents = $subslide.parents('.slide')
$slide = if $parents.length then $parents else $subslide
# Start playing videos in our new slide.
$slide.find('video').each -> @play()
$slide.find('iframe').each ->
return unless $(@).hasClass('autoplay')
return unless /youtube\.com/.test $(@).attr('src')
@contentWindow.postMessage '{"event":"command","func":"playVideo","args":""}', '*'
# Stop videos in slide that we came from.
setTimeout (->
$.deck('getSlide', from).find('video').each -> @pause()
$.deck('getSlide', from).find('iframe').each ->
return unless /youtube\.com/.test $(@).attr('src')
@contentWindow.postMessage '{"event":"command","func":"pauseVideo","args":""}', '*'
), TRANSITION
# Preload nearby iframes.
$IFRAME_INDEX[to].forEach (iframe) ->
setTimeout (-> enableIframe(iframe)), TRANSITION
# Unload non-nearby iframes.
$('iframe').not($IFRAME_INDEX[to]).each ->
iframe = @
setTimeout (-> disableIframe(iframe)), TRANSITION
$ ->
# Build index of which iframes are active per slide
$('.slide').each (i) ->
$this = $(@)
$parents = $this.parents('.slide')
$this = $parents if $parents.length
[i-1, i, i+1].forEach (i) ->
$IFRAME_INDEX[i] or= []
$this.find('iframe').each -> $IFRAME_INDEX[i].push @
# Disable all iframes at first.
$('iframe').each -> disableIframe(@)
$(document).bind 'deck.change', changeSlide
| 161201 | # Code for pre-loading and post-unloading iframes. Most of this is taken from
# <NAME> (@unconed): https://github.com/unconed/fullfrontal, but I've
# tried to separate out the iframe handling from interactions with mathbox,
# since it's nice to have videos auto-load even if you're not using math.
TRANSITION = 300
$IFRAME_INDEX = {}
disableIframe = (iframe) ->
return if $(iframe).data('src')
src = $(iframe).attr('src')
$(iframe).data('src', src)
iframe.onload = null
iframe.src = 'about:blank'
enableIframe = (iframe) ->
src = $(iframe).data('src')
return unless src
iframe.src = src
$(iframe).data('src', null)
changeSlide = (e, from, to) ->
$subslide = $.deck('getSlide', to)
$parents = $subslide.parents('.slide')
$slide = if $parents.length then $parents else $subslide
# Start playing videos in our new slide.
$slide.find('video').each -> @play()
$slide.find('iframe').each ->
return unless $(@).hasClass('autoplay')
return unless /youtube\.com/.test $(@).attr('src')
@contentWindow.postMessage '{"event":"command","func":"playVideo","args":""}', '*'
# Stop videos in slide that we came from.
setTimeout (->
$.deck('getSlide', from).find('video').each -> @pause()
$.deck('getSlide', from).find('iframe').each ->
return unless /youtube\.com/.test $(@).attr('src')
@contentWindow.postMessage '{"event":"command","func":"pauseVideo","args":""}', '*'
), TRANSITION
# Preload nearby iframes.
$IFRAME_INDEX[to].forEach (iframe) ->
setTimeout (-> enableIframe(iframe)), TRANSITION
# Unload non-nearby iframes.
$('iframe').not($IFRAME_INDEX[to]).each ->
iframe = @
setTimeout (-> disableIframe(iframe)), TRANSITION
$ ->
# Build index of which iframes are active per slide
$('.slide').each (i) ->
$this = $(@)
$parents = $this.parents('.slide')
$this = $parents if $parents.length
[i-1, i, i+1].forEach (i) ->
$IFRAME_INDEX[i] or= []
$this.find('iframe').each -> $IFRAME_INDEX[i].push @
# Disable all iframes at first.
$('iframe').each -> disableIframe(@)
$(document).bind 'deck.change', changeSlide
| true | # Code for pre-loading and post-unloading iframes. Most of this is taken from
# PI:NAME:<NAME>END_PI (@unconed): https://github.com/unconed/fullfrontal, but I've
# tried to separate out the iframe handling from interactions with mathbox,
# since it's nice to have videos auto-load even if you're not using math.
TRANSITION = 300
$IFRAME_INDEX = {}
disableIframe = (iframe) ->
return if $(iframe).data('src')
src = $(iframe).attr('src')
$(iframe).data('src', src)
iframe.onload = null
iframe.src = 'about:blank'
enableIframe = (iframe) ->
src = $(iframe).data('src')
return unless src
iframe.src = src
$(iframe).data('src', null)
changeSlide = (e, from, to) ->
$subslide = $.deck('getSlide', to)
$parents = $subslide.parents('.slide')
$slide = if $parents.length then $parents else $subslide
# Start playing videos in our new slide.
$slide.find('video').each -> @play()
$slide.find('iframe').each ->
return unless $(@).hasClass('autoplay')
return unless /youtube\.com/.test $(@).attr('src')
@contentWindow.postMessage '{"event":"command","func":"playVideo","args":""}', '*'
# Stop videos in slide that we came from.
setTimeout (->
$.deck('getSlide', from).find('video').each -> @pause()
$.deck('getSlide', from).find('iframe').each ->
return unless /youtube\.com/.test $(@).attr('src')
@contentWindow.postMessage '{"event":"command","func":"pauseVideo","args":""}', '*'
), TRANSITION
# Preload nearby iframes.
$IFRAME_INDEX[to].forEach (iframe) ->
setTimeout (-> enableIframe(iframe)), TRANSITION
# Unload non-nearby iframes.
$('iframe').not($IFRAME_INDEX[to]).each ->
iframe = @
setTimeout (-> disableIframe(iframe)), TRANSITION
$ ->
# Build index of which iframes are active per slide
$('.slide').each (i) ->
$this = $(@)
$parents = $this.parents('.slide')
$this = $parents if $parents.length
[i-1, i, i+1].forEach (i) ->
$IFRAME_INDEX[i] or= []
$this.find('iframe').each -> $IFRAME_INDEX[i].push @
# Disable all iframes at first.
$('iframe').each -> disableIframe(@)
$(document).bind 'deck.change', changeSlide
|
[
{
"context": "penContact: ->\n window.location.href = \"mailto:info@are.na\"\n\n openPremium: (e) ->\n if sd.CURRENT_USER\n ",
"end": 938,
"score": 0.9998113512992859,
"start": 927,
"tag": "EMAIL",
"value": "info@are.na"
},
{
"context": "d.CURRENT_USER\n @handler.open\n name: 'Are.na'\n description: '1 year / Premium subscript",
"end": 1027,
"score": 0.9974760413169861,
"start": 1021,
"tag": "NAME",
"value": "Are.na"
}
] | apps/about/client/pricing.coffee | broskoski/ervell | 2 | sd = require("sharify").data
Backbone = require 'backbone'
mediator = require '../../../lib/mediator.coffee'
analytics = require '../../../lib/analytics.coffee'
class PricingView extends Backbone.View
price: 4500
events:
'click .premium-tiers__tier--basic .premium-tiers__tier__price' : 'openSignup'
'click .premium-tiers__tier--premium .premium-tiers__tier__price.selectable' : 'openPremium'
'click .premium-tiers__tier--enterprise .premium-tiers__tier__price' : 'openContact'
initialize: ->
if sd.CURRENT_USER
@handler = StripeCheckout.configure
key: sd.STRIPE_PUBLISHABLE_KEY
image: 'https://s3.amazonaws.com/stripe-uploads/acct_14Lg6j411YkgzhRMmerchant-icon-1432502887007-arena-mark.png'
token: @handleToken
email: sd.CURRENT_USER.email
openSignup: ->
window.location.href = "#{sd.APP_URL}/sign_up"
openContact: ->
window.location.href = "mailto:info@are.na"
openPremium: (e) ->
if sd.CURRENT_USER
@handler.open
name: 'Are.na'
description: '1 year / Premium subscription'
amount: @price
@$('.premium--status').addClass('is-active')
else
window.location.href = "#{sd.APP_URL}/log_in?redirect-to=/pricing"
e.preventDefault()
handleToken: (token) =>
@$('.premium--status .inner').text "Registering your premium account..."
$.ajax
url: "#{sd.API_URL}/charges"
type: 'POST'
data:
stripeToken: token
coupon: sd.COUPON
success: (response) =>
@$('.premium--status').addClass('is-successful')
@$('.premium--status .inner').text "Registration successful."
analytics.track.submit 'User paid for pro account'
$.ajax
url: '/me/refresh'
type: 'GET'
beforeSend: (xhr)->
xhr.setRequestHeader 'X-AUTH-TOKEN', sd.CURRENT_USER?.authentication_token
success: ->
location.reload()
error: (response) =>
analytics.exception "Error registering pro account: #{response}"
@$('.premium--status').addClass('is-error')
@$('.premium--status .inner').text "Sorry, error registering your account, please try again."
setTimeout (=> @$('.premium--status').removeClass('is-active')), 2000
module.exports.init = ->
new PricingView
el: $('body') | 108185 | sd = require("sharify").data
Backbone = require 'backbone'
mediator = require '../../../lib/mediator.coffee'
analytics = require '../../../lib/analytics.coffee'
class PricingView extends Backbone.View
price: 4500
events:
'click .premium-tiers__tier--basic .premium-tiers__tier__price' : 'openSignup'
'click .premium-tiers__tier--premium .premium-tiers__tier__price.selectable' : 'openPremium'
'click .premium-tiers__tier--enterprise .premium-tiers__tier__price' : 'openContact'
initialize: ->
if sd.CURRENT_USER
@handler = StripeCheckout.configure
key: sd.STRIPE_PUBLISHABLE_KEY
image: 'https://s3.amazonaws.com/stripe-uploads/acct_14Lg6j411YkgzhRMmerchant-icon-1432502887007-arena-mark.png'
token: @handleToken
email: sd.CURRENT_USER.email
openSignup: ->
window.location.href = "#{sd.APP_URL}/sign_up"
openContact: ->
window.location.href = "mailto:<EMAIL>"
openPremium: (e) ->
if sd.CURRENT_USER
@handler.open
name: '<NAME>'
description: '1 year / Premium subscription'
amount: @price
@$('.premium--status').addClass('is-active')
else
window.location.href = "#{sd.APP_URL}/log_in?redirect-to=/pricing"
e.preventDefault()
handleToken: (token) =>
@$('.premium--status .inner').text "Registering your premium account..."
$.ajax
url: "#{sd.API_URL}/charges"
type: 'POST'
data:
stripeToken: token
coupon: sd.COUPON
success: (response) =>
@$('.premium--status').addClass('is-successful')
@$('.premium--status .inner').text "Registration successful."
analytics.track.submit 'User paid for pro account'
$.ajax
url: '/me/refresh'
type: 'GET'
beforeSend: (xhr)->
xhr.setRequestHeader 'X-AUTH-TOKEN', sd.CURRENT_USER?.authentication_token
success: ->
location.reload()
error: (response) =>
analytics.exception "Error registering pro account: #{response}"
@$('.premium--status').addClass('is-error')
@$('.premium--status .inner').text "Sorry, error registering your account, please try again."
setTimeout (=> @$('.premium--status').removeClass('is-active')), 2000
module.exports.init = ->
new PricingView
el: $('body') | true | sd = require("sharify").data
Backbone = require 'backbone'
mediator = require '../../../lib/mediator.coffee'
analytics = require '../../../lib/analytics.coffee'
class PricingView extends Backbone.View
price: 4500
events:
'click .premium-tiers__tier--basic .premium-tiers__tier__price' : 'openSignup'
'click .premium-tiers__tier--premium .premium-tiers__tier__price.selectable' : 'openPremium'
'click .premium-tiers__tier--enterprise .premium-tiers__tier__price' : 'openContact'
initialize: ->
if sd.CURRENT_USER
@handler = StripeCheckout.configure
key: sd.STRIPE_PUBLISHABLE_KEY
image: 'https://s3.amazonaws.com/stripe-uploads/acct_14Lg6j411YkgzhRMmerchant-icon-1432502887007-arena-mark.png'
token: @handleToken
email: sd.CURRENT_USER.email
openSignup: ->
window.location.href = "#{sd.APP_URL}/sign_up"
openContact: ->
window.location.href = "mailto:PI:EMAIL:<EMAIL>END_PI"
openPremium: (e) ->
if sd.CURRENT_USER
@handler.open
name: 'PI:NAME:<NAME>END_PI'
description: '1 year / Premium subscription'
amount: @price
@$('.premium--status').addClass('is-active')
else
window.location.href = "#{sd.APP_URL}/log_in?redirect-to=/pricing"
e.preventDefault()
handleToken: (token) =>
@$('.premium--status .inner').text "Registering your premium account..."
$.ajax
url: "#{sd.API_URL}/charges"
type: 'POST'
data:
stripeToken: token
coupon: sd.COUPON
success: (response) =>
@$('.premium--status').addClass('is-successful')
@$('.premium--status .inner').text "Registration successful."
analytics.track.submit 'User paid for pro account'
$.ajax
url: '/me/refresh'
type: 'GET'
beforeSend: (xhr)->
xhr.setRequestHeader 'X-AUTH-TOKEN', sd.CURRENT_USER?.authentication_token
success: ->
location.reload()
error: (response) =>
analytics.exception "Error registering pro account: #{response}"
@$('.premium--status').addClass('is-error')
@$('.premium--status .inner').text "Sorry, error registering your account, please try again."
setTimeout (=> @$('.premium--status').removeClass('is-active')), 2000
module.exports.init = ->
new PricingView
el: $('body') |
[
{
"context": "###\n# @author Argi Karunia <arugikaru@yahoo.co.jp>\n# @link https://gihtu",
"end": 28,
"score": 0.9998661279678345,
"start": 16,
"tag": "NAME",
"value": "Argi Karunia"
},
{
"context": "###\n# @author Argi Karunia <arugikaru@yahoo.co.jp>\n# @link https://gihtub.com/tokopedia/Nodame\n",
"end": 51,
"score": 0.9999292492866516,
"start": 30,
"tag": "EMAIL",
"value": "arugikaru@yahoo.co.jp"
}
] | src/session.coffee | tokopedia/nodame | 2 | ###
# @author Argi Karunia <arugikaru@yahoo.co.jp>
# @link https://gihtub.com/tokopedia/Nodame
# @license http://opensource.org/licenses/maintenance
#
# @version 1.2.0
###
# CONFIGS
SESSION = nodame.config('session')
CACHE = nodame.config('cache')
COOKIE = nodame.config('cookie')
MODULES = nodame.config('module')
ASSETS = nodame.config('assets')
URL = nodame.config('url')
APP = nodame.config('app')
# MODULES
Render = require('./render')
Hash = require('js-sha512')
Redis = require('./redis')
Async = require('async')
class Session
###
# @constructor
###
constructor: (req, res) ->
@_key = SESSION.key
@_identifier = "#{APP.name}/session"
@_domain = ".#{COOKIE.domain}"
@_options =
domain : @_domain
httpOnly: true
expires : new Date(Date.now() + SESSION.expires * 1000)
signed : true
@_option_domain =
domain : @_domain
if req? and res?
@middleware(req, res)
return
###
# @method Check if session is enabled and ready
# @throw Error if not ready
# @return bool
###
_is_enable: ->
# Check if session is enable in configuration
unless SESSION.enable
return false
# Get db engine
db_server = CACHE.db_server
# Check if db engine is enable
unless CACHE.db[db_server].enable
throw new Error "#{db_server} is not enabled"
# Assign client configuration
client = CACHE.db[db_server]
# Check host and port configuration
if not client.host? or not client.port?
throw new Error "Missing host or port config for #{db_server}"
# Session is enable
return true
###
# @method Evaluate if session is enabled
# @private
# @throw error if session method is used when disabled
###
_evaluate_session_enable: ->
unless @_is_enable()
throw new Error "You are using session method while \
session isn't enabled by config"
return
###
# @method Register middleware function
# @public
# @param object request object
# @param object response object
# @param object optional next object
###
middleware: (@req, @res, next) =>
# NOTE: CHECKPOINT
# Check if session is enabled
unless @_is_enable()
return next() if next?
return
# Return if this wasn't requested from router
return unless next?
# NOTE: CHECKPOINT
# Check if path exists
return next() unless @req.path?
# Assign paths from req.path
@__paths = @req.path.split('/')
# NOTE: CHECKPOINT
# Check if route exists
return next() unless @__paths[1]?
# Set path depends on whether path is root
path_idx = if "/#{@__paths[1]}" is MODULES.root then 2 else 1
# Assign path
@__path = @__paths[path_idx] || ''
# Get real path for ajax
# TODO: Add config to disable session on xhr
@__path = @__paths[path_idx + 1] || '' if @__path is 'ajax'
# Set no path to default
@__path = MODULES.default if @__path is ''
# NOTE: CHECKPOINT
# Validate if path is module
return next() unless MODULES.items[@__path]?
# Assign module
@_mod = MODULES.items[@__path]
# Get redis key
redis_key = @_get_redis_key()
# Get redis client
redis = Redis.client()
Async.waterfall [
(cb) => redis.get(redis_key, cb)
], (err, reply) =>
# Validate error
unless err?
# Validate reply
if reply?
# Parse reply
session = JSON.parse(reply)
# Evaluate and register session
@_evaluate_session(session)
# Evaluate access
unless @_evaluate_access()
err = new Error('Unauthorized access.')
err.status = 404
return next(err)
else
return next()
return undefined
###
# @method Evaluate existence of session
# @private
###
_evaluate_session: (session) ->
# Check if session is alive
if @_is_alive()
# Register session
return @_register_session(session)
# Session isn't alive
# Unregister session
return @_register_session()
###
# @method Register session to environment
# @private
###
_register_session: (session) ->
# Register session
if session?
@req.session = session
@res.locals.session = session
@req.is_auth = true
@res.locals.is_auth = true
# Unregister session
else
@req.session = {}
@res.locals.session = {}
@req.is_auth = false
@res.locals.is_auth = false
return
###
# @method Evaluate access
# @private
# @return bool
###
_evaluate_access: ->
# Validate access if it's set in config
if @_mod.auth_only or @_mod.guest_only
# Validate auth only access
if @_mod.auth_only and not @req.is_auth
# Return revoke access
return false
# Validate guest only access
if @_mod.guest_only and @req.is_auth
# Return revoke access
return false
# Return permit access
return true
###
# @method Check session existence
# @private
# @return bool
###
_is_alive: ->
# Return whether session cookie does exist
return @req.signedCookies[@_key]?
###
# @method Generate session id
# @private
# @param object session
# @return string
###
_generate_session_id: (session) ->
# TODO: Validate session_id
session_id = Hash.sha384("#{JSON.stringify(session)}:#{COOKIE.secret}:#{new Date()}")
return session_id
###
# @method Generate redis key
# @private
# @return string
###
_generate_redis_key: (session_id) ->
return "#{@_identifier}-#{session_id}"
###
# @method Get session id
# @public
# @return string
###
get_session_id: ->
# Check if session is enabled
@_evaluate_session_enable()
# Return session id
return @req.signedCookies[@_key]
###
# @method Establish new session
# @public
# @param object
###
set: (session, callback) ->
# Check if session is enabled
@_evaluate_session_enable()
# Set session id
session_id = @_generate_session_id(session)
# Set redis key
redis_key = @_generate_redis_key(session_id)
# Set session and cookie
@res.cookie(@_key, session_id, @_options)
# Set to redis
redis = Redis.client()
redis.expire(redis_key, SESSION.expires)
redis.set [redis_key, JSON.stringify(session)], (err, result) ->
# Validate result
return callback(err, undefined) if err?
# rReturn callback
return callback(null, session_id)
return
###
# @method Get redis Keys
# @private
# @return string redis_key
###
_get_redis_key: ->
# Get session id
session_id = @get_session_id()
# Return redis key
return @_generate_redis_key(session_id)
###
# @method Get session
# @public
# @return callback session
###
get: (callback) ->
redis_key = @_get_redis_key()
redis = Redis.client()
redis.get redis_key, (err, reply) ->
callback(err, reply)
return undefined
return
###
# @method Destroy session
# @public
###
clear: ->
# Check if session is enabled
@_evaluate_session_enable()
# Get redis key
redis_key = @_get_redis_key()
# Clear session and cookie
@res.clearCookie(@_key, @_option_domain)
# Clear redis key
redis = Redis.client()
redis.del(redis_key)
return
# Export module as new object
module.exports = Session
| 186134 | ###
# @author <NAME> <<EMAIL>>
# @link https://gihtub.com/tokopedia/Nodame
# @license http://opensource.org/licenses/maintenance
#
# @version 1.2.0
###
# CONFIGS
SESSION = nodame.config('session')
CACHE = nodame.config('cache')
COOKIE = nodame.config('cookie')
MODULES = nodame.config('module')
ASSETS = nodame.config('assets')
URL = nodame.config('url')
APP = nodame.config('app')
# MODULES
Render = require('./render')
Hash = require('js-sha512')
Redis = require('./redis')
Async = require('async')
class Session
###
# @constructor
###
constructor: (req, res) ->
@_key = SESSION.key
@_identifier = "#{APP.name}/session"
@_domain = ".#{COOKIE.domain}"
@_options =
domain : @_domain
httpOnly: true
expires : new Date(Date.now() + SESSION.expires * 1000)
signed : true
@_option_domain =
domain : @_domain
if req? and res?
@middleware(req, res)
return
###
# @method Check if session is enabled and ready
# @throw Error if not ready
# @return bool
###
_is_enable: ->
# Check if session is enable in configuration
unless SESSION.enable
return false
# Get db engine
db_server = CACHE.db_server
# Check if db engine is enable
unless CACHE.db[db_server].enable
throw new Error "#{db_server} is not enabled"
# Assign client configuration
client = CACHE.db[db_server]
# Check host and port configuration
if not client.host? or not client.port?
throw new Error "Missing host or port config for #{db_server}"
# Session is enable
return true
###
# @method Evaluate if session is enabled
# @private
# @throw error if session method is used when disabled
###
_evaluate_session_enable: ->
unless @_is_enable()
throw new Error "You are using session method while \
session isn't enabled by config"
return
###
# @method Register middleware function
# @public
# @param object request object
# @param object response object
# @param object optional next object
###
middleware: (@req, @res, next) =>
# NOTE: CHECKPOINT
# Check if session is enabled
unless @_is_enable()
return next() if next?
return
# Return if this wasn't requested from router
return unless next?
# NOTE: CHECKPOINT
# Check if path exists
return next() unless @req.path?
# Assign paths from req.path
@__paths = @req.path.split('/')
# NOTE: CHECKPOINT
# Check if route exists
return next() unless @__paths[1]?
# Set path depends on whether path is root
path_idx = if "/#{@__paths[1]}" is MODULES.root then 2 else 1
# Assign path
@__path = @__paths[path_idx] || ''
# Get real path for ajax
# TODO: Add config to disable session on xhr
@__path = @__paths[path_idx + 1] || '' if @__path is 'ajax'
# Set no path to default
@__path = MODULES.default if @__path is ''
# NOTE: CHECKPOINT
# Validate if path is module
return next() unless MODULES.items[@__path]?
# Assign module
@_mod = MODULES.items[@__path]
# Get redis key
redis_key = @_get_redis_key()
# Get redis client
redis = Redis.client()
Async.waterfall [
(cb) => redis.get(redis_key, cb)
], (err, reply) =>
# Validate error
unless err?
# Validate reply
if reply?
# Parse reply
session = JSON.parse(reply)
# Evaluate and register session
@_evaluate_session(session)
# Evaluate access
unless @_evaluate_access()
err = new Error('Unauthorized access.')
err.status = 404
return next(err)
else
return next()
return undefined
###
# @method Evaluate existence of session
# @private
###
_evaluate_session: (session) ->
# Check if session is alive
if @_is_alive()
# Register session
return @_register_session(session)
# Session isn't alive
# Unregister session
return @_register_session()
###
# @method Register session to environment
# @private
###
_register_session: (session) ->
# Register session
if session?
@req.session = session
@res.locals.session = session
@req.is_auth = true
@res.locals.is_auth = true
# Unregister session
else
@req.session = {}
@res.locals.session = {}
@req.is_auth = false
@res.locals.is_auth = false
return
###
# @method Evaluate access
# @private
# @return bool
###
_evaluate_access: ->
# Validate access if it's set in config
if @_mod.auth_only or @_mod.guest_only
# Validate auth only access
if @_mod.auth_only and not @req.is_auth
# Return revoke access
return false
# Validate guest only access
if @_mod.guest_only and @req.is_auth
# Return revoke access
return false
# Return permit access
return true
###
# @method Check session existence
# @private
# @return bool
###
_is_alive: ->
# Return whether session cookie does exist
return @req.signedCookies[@_key]?
###
# @method Generate session id
# @private
# @param object session
# @return string
###
_generate_session_id: (session) ->
# TODO: Validate session_id
session_id = Hash.sha384("#{JSON.stringify(session)}:#{COOKIE.secret}:#{new Date()}")
return session_id
###
# @method Generate redis key
# @private
# @return string
###
_generate_redis_key: (session_id) ->
return "#{@_identifier}-#{session_id}"
###
# @method Get session id
# @public
# @return string
###
get_session_id: ->
# Check if session is enabled
@_evaluate_session_enable()
# Return session id
return @req.signedCookies[@_key]
###
# @method Establish new session
# @public
# @param object
###
set: (session, callback) ->
# Check if session is enabled
@_evaluate_session_enable()
# Set session id
session_id = @_generate_session_id(session)
# Set redis key
redis_key = @_generate_redis_key(session_id)
# Set session and cookie
@res.cookie(@_key, session_id, @_options)
# Set to redis
redis = Redis.client()
redis.expire(redis_key, SESSION.expires)
redis.set [redis_key, JSON.stringify(session)], (err, result) ->
# Validate result
return callback(err, undefined) if err?
# rReturn callback
return callback(null, session_id)
return
###
# @method Get redis Keys
# @private
# @return string redis_key
###
_get_redis_key: ->
# Get session id
session_id = @get_session_id()
# Return redis key
return @_generate_redis_key(session_id)
###
# @method Get session
# @public
# @return callback session
###
get: (callback) ->
redis_key = @_get_redis_key()
redis = Redis.client()
redis.get redis_key, (err, reply) ->
callback(err, reply)
return undefined
return
###
# @method Destroy session
# @public
###
clear: ->
# Check if session is enabled
@_evaluate_session_enable()
# Get redis key
redis_key = @_get_redis_key()
# Clear session and cookie
@res.clearCookie(@_key, @_option_domain)
# Clear redis key
redis = Redis.client()
redis.del(redis_key)
return
# Export module as new object
module.exports = Session
| true | ###
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @link https://gihtub.com/tokopedia/Nodame
# @license http://opensource.org/licenses/maintenance
#
# @version 1.2.0
###
# CONFIGS
SESSION = nodame.config('session')
CACHE = nodame.config('cache')
COOKIE = nodame.config('cookie')
MODULES = nodame.config('module')
ASSETS = nodame.config('assets')
URL = nodame.config('url')
APP = nodame.config('app')
# MODULES
Render = require('./render')
Hash = require('js-sha512')
Redis = require('./redis')
Async = require('async')
class Session
###
# @constructor
###
constructor: (req, res) ->
@_key = SESSION.key
@_identifier = "#{APP.name}/session"
@_domain = ".#{COOKIE.domain}"
@_options =
domain : @_domain
httpOnly: true
expires : new Date(Date.now() + SESSION.expires * 1000)
signed : true
@_option_domain =
domain : @_domain
if req? and res?
@middleware(req, res)
return
###
# @method Check if session is enabled and ready
# @throw Error if not ready
# @return bool
###
_is_enable: ->
# Check if session is enable in configuration
unless SESSION.enable
return false
# Get db engine
db_server = CACHE.db_server
# Check if db engine is enable
unless CACHE.db[db_server].enable
throw new Error "#{db_server} is not enabled"
# Assign client configuration
client = CACHE.db[db_server]
# Check host and port configuration
if not client.host? or not client.port?
throw new Error "Missing host or port config for #{db_server}"
# Session is enable
return true
###
# @method Evaluate if session is enabled
# @private
# @throw error if session method is used when disabled
###
_evaluate_session_enable: ->
unless @_is_enable()
throw new Error "You are using session method while \
session isn't enabled by config"
return
###
# @method Register middleware function
# @public
# @param object request object
# @param object response object
# @param object optional next object
###
middleware: (@req, @res, next) =>
# NOTE: CHECKPOINT
# Check if session is enabled
unless @_is_enable()
return next() if next?
return
# Return if this wasn't requested from router
return unless next?
# NOTE: CHECKPOINT
# Check if path exists
return next() unless @req.path?
# Assign paths from req.path
@__paths = @req.path.split('/')
# NOTE: CHECKPOINT
# Check if route exists
return next() unless @__paths[1]?
# Set path depends on whether path is root
path_idx = if "/#{@__paths[1]}" is MODULES.root then 2 else 1
# Assign path
@__path = @__paths[path_idx] || ''
# Get real path for ajax
# TODO: Add config to disable session on xhr
@__path = @__paths[path_idx + 1] || '' if @__path is 'ajax'
# Set no path to default
@__path = MODULES.default if @__path is ''
# NOTE: CHECKPOINT
# Validate if path is module
return next() unless MODULES.items[@__path]?
# Assign module
@_mod = MODULES.items[@__path]
# Get redis key
redis_key = @_get_redis_key()
# Get redis client
redis = Redis.client()
Async.waterfall [
(cb) => redis.get(redis_key, cb)
], (err, reply) =>
# Validate error
unless err?
# Validate reply
if reply?
# Parse reply
session = JSON.parse(reply)
# Evaluate and register session
@_evaluate_session(session)
# Evaluate access
unless @_evaluate_access()
err = new Error('Unauthorized access.')
err.status = 404
return next(err)
else
return next()
return undefined
###
# @method Evaluate existence of session
# @private
###
_evaluate_session: (session) ->
# Check if session is alive
if @_is_alive()
# Register session
return @_register_session(session)
# Session isn't alive
# Unregister session
return @_register_session()
###
# @method Register session to environment
# @private
###
_register_session: (session) ->
# Register session
if session?
@req.session = session
@res.locals.session = session
@req.is_auth = true
@res.locals.is_auth = true
# Unregister session
else
@req.session = {}
@res.locals.session = {}
@req.is_auth = false
@res.locals.is_auth = false
return
###
# @method Evaluate access
# @private
# @return bool
###
_evaluate_access: ->
# Validate access if it's set in config
if @_mod.auth_only or @_mod.guest_only
# Validate auth only access
if @_mod.auth_only and not @req.is_auth
# Return revoke access
return false
# Validate guest only access
if @_mod.guest_only and @req.is_auth
# Return revoke access
return false
# Return permit access
return true
###
# @method Check session existence
# @private
# @return bool
###
_is_alive: ->
# Return whether session cookie does exist
return @req.signedCookies[@_key]?
###
# @method Generate session id
# @private
# @param object session
# @return string
###
_generate_session_id: (session) ->
# TODO: Validate session_id
session_id = Hash.sha384("#{JSON.stringify(session)}:#{COOKIE.secret}:#{new Date()}")
return session_id
###
# @method Generate redis key
# @private
# @return string
###
_generate_redis_key: (session_id) ->
return "#{@_identifier}-#{session_id}"
###
# @method Get session id
# @public
# @return string
###
get_session_id: ->
# Check if session is enabled
@_evaluate_session_enable()
# Return session id
return @req.signedCookies[@_key]
###
# @method Establish new session
# @public
# @param object
###
set: (session, callback) ->
# Check if session is enabled
@_evaluate_session_enable()
# Set session id
session_id = @_generate_session_id(session)
# Set redis key
redis_key = @_generate_redis_key(session_id)
# Set session and cookie
@res.cookie(@_key, session_id, @_options)
# Set to redis
redis = Redis.client()
redis.expire(redis_key, SESSION.expires)
redis.set [redis_key, JSON.stringify(session)], (err, result) ->
# Validate result
return callback(err, undefined) if err?
# rReturn callback
return callback(null, session_id)
return
###
# @method Get redis Keys
# @private
# @return string redis_key
###
_get_redis_key: ->
# Get session id
session_id = @get_session_id()
# Return redis key
return @_generate_redis_key(session_id)
###
# @method Get session
# @public
# @return callback session
###
get: (callback) ->
redis_key = @_get_redis_key()
redis = Redis.client()
redis.get redis_key, (err, reply) ->
callback(err, reply)
return undefined
return
###
# @method Destroy session
# @public
###
clear: ->
# Check if session is enabled
@_evaluate_session_enable()
# Get redis key
redis_key = @_get_redis_key()
# Clear session and cookie
@res.clearCookie(@_key, @_option_domain)
# Clear redis key
redis = Redis.client()
redis.del(redis_key)
return
# Export module as new object
module.exports = Session
|
[
{
"context": " invitation: 'common'\n password_reset: 'common'\n upload: 'common'\n color: ",
"end": 445,
"score": 0.9931247234344482,
"start": 439,
"tag": "PASSWORD",
"value": "common"
}
] | src/thinkspace/client/thinkspace-common/addon/_config.coffee | sixthedge/cellar | 6 | export default {
env: {modulePrefix: 'thinkspace-common'}
ns:
namespaces: {common: 'thinkspace/common'}
type_to_namespace:
user: 'common'
owner: 'common'
space: 'common'
space_type: 'common'
space_user: 'common'
configuration: 'common'
configurable: 'common'
component: 'common'
invitation: 'common'
password_reset: 'common'
upload: 'common'
color: 'common'
}
| 133649 | export default {
env: {modulePrefix: 'thinkspace-common'}
ns:
namespaces: {common: 'thinkspace/common'}
type_to_namespace:
user: 'common'
owner: 'common'
space: 'common'
space_type: 'common'
space_user: 'common'
configuration: 'common'
configurable: 'common'
component: 'common'
invitation: 'common'
password_reset: '<PASSWORD>'
upload: 'common'
color: 'common'
}
| true | export default {
env: {modulePrefix: 'thinkspace-common'}
ns:
namespaces: {common: 'thinkspace/common'}
type_to_namespace:
user: 'common'
owner: 'common'
space: 'common'
space_type: 'common'
space_user: 'common'
configuration: 'common'
configurable: 'common'
component: 'common'
invitation: 'common'
password_reset: 'PI:PASSWORD:<PASSWORD>END_PI'
upload: 'common'
color: 'common'
}
|
[
{
"context": " = (id, password) ->\n options =\n username: id\n password: password\n\n login(options).then",
"end": 2641,
"score": 0.5679617524147034,
"start": 2639,
"tag": "USERNAME",
"value": "id"
},
{
"context": ">\n options =\n username: id\n password: password\n\n login(options).then(loginSuccess, loginFailu",
"end": 2666,
"score": 0.9968639612197876,
"start": 2658,
"tag": "PASSWORD",
"value": "password"
}
] | app/scripts/connect/login.controller.coffee | appirio-tech/accounts-app | 3 | 'use strict'
{ DOMAIN } = require '../../../core/constants.js'
{ getFreshToken, login } = require '../../../core/auth.js'
{ getV3Jwt } = require '../../../core/auth.js'
{ getLoginConnection, isEmail } = require '../../../core/utils.js'
{ generateReturnUrl, redirectTo } = require '../../../core/url.js'
ConnectLoginController = (
$scope
$log
$state
$stateParams
UserService
) ->
vm = this
vm.username = ''
vm.password = ''
vm.error = false
vm.loading = false
vm.init = false
vm.$stateParams = $stateParams
vm.passwordReset = vm.$stateParams.passwordReset == true
vm.loginErrors =
USERNAME_NONEXISTANT: false
WRONG_PASSWORD: false
ACCOUNT_INACTIVE: false
vm.baseUrl = "https://connect.#{DOMAIN}"
vm.registrationUrl = $state.href('CONNECT_REGISTRATION', { activated: true }, { absolute: true })
vm.forgotPasswordUrl = $state.href('CONNECT_FORGOT_PASSWORD', { absolute: true })
vm.retUrl = if $stateParams.retUrl then decodeURIComponent($stateParams.retUrl) else vm.baseUrl
vm.ssoLoginUrl = $state.href('SSO_LOGIN', { absolute: true, app: 'connect', retUrl: vm.retUrl })
vm.hasPasswordError = ->
vm.loginErrors.WRONG_PASSWORD
vm.submit = ->
vm.loading = true
# clear error flags
vm.loginErrors.USERNAME_NONEXISTANT = false
vm.loginErrors.WRONG_PASSWORD = false
vm.loginErrors.ACCOUNT_INACTIVE = false
if vm.username == ''
vm.loginErrors.USERNAME_NONEXISTANT = true
vm.loading = false
else
validateUsername(vm.username)
.then (result) ->
# if username/email is available for registration, it means it is a non existant user
if result
vm.loginErrors.USERNAME_NONEXISTANT = true
vm.loading = false
vm.reRender()
else
callLogin(vm.username, vm.password)
.catch (err) ->
vm.loginErrors.USERNAME_NONEXISTANT = false
callLogin(vm.username, vm.password)
vm.reRender()
vm.reRender()
loginFailure = (error) ->
if error?.message?.toLowerCase() == 'account inactive'
# redirect to the page to prompt activation
vm.loginErrors.ACCOUNT_INACTIVE = true
else
vm.loginErrors.WRONG_PASSWORD = true
$scope.$apply ->
vm.error = true
vm.loading = false
vm.reRender()
loginSuccess = ->
jwt = getV3Jwt()
unless jwt
vm.error = true
else if vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
else
$state.go 'CONNECT_WELCOME'
vm.reRender()
callLogin = (id, password) ->
options =
username: id
password: password
login(options).then(loginSuccess, loginFailure)
validateUsername = (username) ->
validator = if isEmail(username) then UserService.validateEmail else UserService.validateHandle
validator username
.then (res) ->
res?.valid || res.reasonCode != 'ALREADY_TAKEN'
init = ->
{ handle, email, password } = $stateParams
getJwtSuccess = (jwt) ->
if jwt && vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
else if (handle || email) && password
callLogin(handle || email, password)
getFreshToken().then(getJwtSuccess).catch(() => {
# ignore, to stop angular complaining about unhandled promise
})
vm
init()
ConnectLoginController.$inject = [
'$scope'
'$log'
'$state'
'$stateParams'
'UserService'
]
angular.module('accounts').controller 'ConnectLoginController', ConnectLoginController
| 151541 | 'use strict'
{ DOMAIN } = require '../../../core/constants.js'
{ getFreshToken, login } = require '../../../core/auth.js'
{ getV3Jwt } = require '../../../core/auth.js'
{ getLoginConnection, isEmail } = require '../../../core/utils.js'
{ generateReturnUrl, redirectTo } = require '../../../core/url.js'
ConnectLoginController = (
$scope
$log
$state
$stateParams
UserService
) ->
vm = this
vm.username = ''
vm.password = ''
vm.error = false
vm.loading = false
vm.init = false
vm.$stateParams = $stateParams
vm.passwordReset = vm.$stateParams.passwordReset == true
vm.loginErrors =
USERNAME_NONEXISTANT: false
WRONG_PASSWORD: false
ACCOUNT_INACTIVE: false
vm.baseUrl = "https://connect.#{DOMAIN}"
vm.registrationUrl = $state.href('CONNECT_REGISTRATION', { activated: true }, { absolute: true })
vm.forgotPasswordUrl = $state.href('CONNECT_FORGOT_PASSWORD', { absolute: true })
vm.retUrl = if $stateParams.retUrl then decodeURIComponent($stateParams.retUrl) else vm.baseUrl
vm.ssoLoginUrl = $state.href('SSO_LOGIN', { absolute: true, app: 'connect', retUrl: vm.retUrl })
vm.hasPasswordError = ->
vm.loginErrors.WRONG_PASSWORD
vm.submit = ->
vm.loading = true
# clear error flags
vm.loginErrors.USERNAME_NONEXISTANT = false
vm.loginErrors.WRONG_PASSWORD = false
vm.loginErrors.ACCOUNT_INACTIVE = false
if vm.username == ''
vm.loginErrors.USERNAME_NONEXISTANT = true
vm.loading = false
else
validateUsername(vm.username)
.then (result) ->
# if username/email is available for registration, it means it is a non existant user
if result
vm.loginErrors.USERNAME_NONEXISTANT = true
vm.loading = false
vm.reRender()
else
callLogin(vm.username, vm.password)
.catch (err) ->
vm.loginErrors.USERNAME_NONEXISTANT = false
callLogin(vm.username, vm.password)
vm.reRender()
vm.reRender()
loginFailure = (error) ->
if error?.message?.toLowerCase() == 'account inactive'
# redirect to the page to prompt activation
vm.loginErrors.ACCOUNT_INACTIVE = true
else
vm.loginErrors.WRONG_PASSWORD = true
$scope.$apply ->
vm.error = true
vm.loading = false
vm.reRender()
loginSuccess = ->
jwt = getV3Jwt()
unless jwt
vm.error = true
else if vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
else
$state.go 'CONNECT_WELCOME'
vm.reRender()
callLogin = (id, password) ->
options =
username: id
password: <PASSWORD>
login(options).then(loginSuccess, loginFailure)
validateUsername = (username) ->
validator = if isEmail(username) then UserService.validateEmail else UserService.validateHandle
validator username
.then (res) ->
res?.valid || res.reasonCode != 'ALREADY_TAKEN'
init = ->
{ handle, email, password } = $stateParams
getJwtSuccess = (jwt) ->
if jwt && vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
else if (handle || email) && password
callLogin(handle || email, password)
getFreshToken().then(getJwtSuccess).catch(() => {
# ignore, to stop angular complaining about unhandled promise
})
vm
init()
ConnectLoginController.$inject = [
'$scope'
'$log'
'$state'
'$stateParams'
'UserService'
]
angular.module('accounts').controller 'ConnectLoginController', ConnectLoginController
| true | 'use strict'
{ DOMAIN } = require '../../../core/constants.js'
{ getFreshToken, login } = require '../../../core/auth.js'
{ getV3Jwt } = require '../../../core/auth.js'
{ getLoginConnection, isEmail } = require '../../../core/utils.js'
{ generateReturnUrl, redirectTo } = require '../../../core/url.js'
ConnectLoginController = (
$scope
$log
$state
$stateParams
UserService
) ->
vm = this
vm.username = ''
vm.password = ''
vm.error = false
vm.loading = false
vm.init = false
vm.$stateParams = $stateParams
vm.passwordReset = vm.$stateParams.passwordReset == true
vm.loginErrors =
USERNAME_NONEXISTANT: false
WRONG_PASSWORD: false
ACCOUNT_INACTIVE: false
vm.baseUrl = "https://connect.#{DOMAIN}"
vm.registrationUrl = $state.href('CONNECT_REGISTRATION', { activated: true }, { absolute: true })
vm.forgotPasswordUrl = $state.href('CONNECT_FORGOT_PASSWORD', { absolute: true })
vm.retUrl = if $stateParams.retUrl then decodeURIComponent($stateParams.retUrl) else vm.baseUrl
vm.ssoLoginUrl = $state.href('SSO_LOGIN', { absolute: true, app: 'connect', retUrl: vm.retUrl })
vm.hasPasswordError = ->
vm.loginErrors.WRONG_PASSWORD
vm.submit = ->
vm.loading = true
# clear error flags
vm.loginErrors.USERNAME_NONEXISTANT = false
vm.loginErrors.WRONG_PASSWORD = false
vm.loginErrors.ACCOUNT_INACTIVE = false
if vm.username == ''
vm.loginErrors.USERNAME_NONEXISTANT = true
vm.loading = false
else
validateUsername(vm.username)
.then (result) ->
# if username/email is available for registration, it means it is a non existant user
if result
vm.loginErrors.USERNAME_NONEXISTANT = true
vm.loading = false
vm.reRender()
else
callLogin(vm.username, vm.password)
.catch (err) ->
vm.loginErrors.USERNAME_NONEXISTANT = false
callLogin(vm.username, vm.password)
vm.reRender()
vm.reRender()
loginFailure = (error) ->
if error?.message?.toLowerCase() == 'account inactive'
# redirect to the page to prompt activation
vm.loginErrors.ACCOUNT_INACTIVE = true
else
vm.loginErrors.WRONG_PASSWORD = true
$scope.$apply ->
vm.error = true
vm.loading = false
vm.reRender()
loginSuccess = ->
jwt = getV3Jwt()
unless jwt
vm.error = true
else if vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
else
$state.go 'CONNECT_WELCOME'
vm.reRender()
callLogin = (id, password) ->
options =
username: id
password: PI:PASSWORD:<PASSWORD>END_PI
login(options).then(loginSuccess, loginFailure)
validateUsername = (username) ->
validator = if isEmail(username) then UserService.validateEmail else UserService.validateHandle
validator username
.then (res) ->
res?.valid || res.reasonCode != 'ALREADY_TAKEN'
init = ->
{ handle, email, password } = $stateParams
getJwtSuccess = (jwt) ->
if jwt && vm.retUrl
redirectTo generateReturnUrl(vm.retUrl)
else if (handle || email) && password
callLogin(handle || email, password)
getFreshToken().then(getJwtSuccess).catch(() => {
# ignore, to stop angular complaining about unhandled promise
})
vm
init()
ConnectLoginController.$inject = [
'$scope'
'$log'
'$state'
'$stateParams'
'UserService'
]
angular.module('accounts').controller 'ConnectLoginController', ConnectLoginController
|
[
{
"context": "Parser()\n app.use express.cookieSession secret: \"f51a8xlc3efeb869acbd7c2d962a4100x00a01f\"\n app.use express.static \"#{__dirname}/public\"\n\n",
"end": 357,
"score": 0.9759376645088196,
"start": 318,
"tag": "KEY",
"value": "f51a8xlc3efeb869acbd7c2d962a4100x00a01f"
}
] | clients/web/index.coffee | makeusabrew/freezer | 0 | express = require "express"
swig = require "swig"
app = express()
# app config
swig.init
root: "#{__dirname}/views"
allowErrors: true
cache: false
app.configure ->
app.use express.favicon()
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.cookieSession secret: "f51a8xlc3efeb869acbd7c2d962a4100x00a01f"
app.use express.static "#{__dirname}/public"
# app includes
require("./routes")(app)
app.listen 8888
console.log "server listening on port 8888"
| 138700 | express = require "express"
swig = require "swig"
app = express()
# app config
swig.init
root: "#{__dirname}/views"
allowErrors: true
cache: false
app.configure ->
app.use express.favicon()
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.cookieSession secret: "<KEY>"
app.use express.static "#{__dirname}/public"
# app includes
require("./routes")(app)
app.listen 8888
console.log "server listening on port 8888"
| true | express = require "express"
swig = require "swig"
app = express()
# app config
swig.init
root: "#{__dirname}/views"
allowErrors: true
cache: false
app.configure ->
app.use express.favicon()
app.use express.bodyParser()
app.use express.cookieParser()
app.use express.cookieSession secret: "PI:KEY:<KEY>END_PI"
app.use express.static "#{__dirname}/public"
# app includes
require("./routes")(app)
app.listen 8888
console.log "server listening on port 8888"
|
[
{
"context": "# Copyright © 2013 All rights reserved\n# Author: nhim175@gmail.com\n\nconfig = require './config.coffee'\n\nclass Button",
"end": 66,
"score": 0.9999151229858398,
"start": 49,
"tag": "EMAIL",
"value": "nhim175@gmail.com"
}
] | src/lib/button.coffee | nhim175/scorpionsmasher | 0 | # Copyright © 2013 All rights reserved
# Author: nhim175@gmail.com
config = require './config.coffee'
class Button extends Phaser.Button
constructor: (game, x, y, key, callback) ->
super(game, x, y, key, callback)
@clickSound = new Phaser.Sound game, 'click', 1
@onInputUp.add @onInputUpListener
onInputUpListener: =>
if window.plugins?.NativeAudio
window.plugins.NativeAudio.play('click')
else
@clickSound.play()
module.exports = Button
| 6625 | # Copyright © 2013 All rights reserved
# Author: <EMAIL>
config = require './config.coffee'
class Button extends Phaser.Button
constructor: (game, x, y, key, callback) ->
super(game, x, y, key, callback)
@clickSound = new Phaser.Sound game, 'click', 1
@onInputUp.add @onInputUpListener
onInputUpListener: =>
if window.plugins?.NativeAudio
window.plugins.NativeAudio.play('click')
else
@clickSound.play()
module.exports = Button
| true | # Copyright © 2013 All rights reserved
# Author: PI:EMAIL:<EMAIL>END_PI
config = require './config.coffee'
class Button extends Phaser.Button
constructor: (game, x, y, key, callback) ->
super(game, x, y, key, callback)
@clickSound = new Phaser.Sound game, 'click', 1
@onInputUp.add @onInputUpListener
onInputUpListener: =>
if window.plugins?.NativeAudio
window.plugins.NativeAudio.play('click')
else
@clickSound.play()
module.exports = Button
|
[
{
"context": "d, at the cost of combat statistics.\n *\n * @name Hasty\n * @prerequisite Play for 2 hours\n * @effect +2",
"end": 165,
"score": 0.9756442904472351,
"start": 160,
"tag": "NAME",
"value": "Hasty"
}
] | src/character/personalities/Hasty.coffee | sadbear-/IdleLands | 3 |
Personality = require "../base/Personality"
`/**
* This personality makes you move faster around the world, at the cost of combat statistics.
*
* @name Hasty
* @prerequisite Play for 2 hours
* @effect +2 haste
* @effect -2 offense
* @effect -2 defense
* @category Personalities
* @package Player
*/`
class Hasty extends Personality
constructor: ->
haste: -> 2
offense: -> -2
defense: -> -2
@canUse = (player) ->
hoursPlayed = (Math.abs player.registrationDate.getTime()-Date.now()) / 36e5
hoursPlayed >= 2
@desc = "Play for 2 hours"
module.exports = exports = Hasty
| 67945 |
Personality = require "../base/Personality"
`/**
* This personality makes you move faster around the world, at the cost of combat statistics.
*
* @name <NAME>
* @prerequisite Play for 2 hours
* @effect +2 haste
* @effect -2 offense
* @effect -2 defense
* @category Personalities
* @package Player
*/`
class Hasty extends Personality
constructor: ->
haste: -> 2
offense: -> -2
defense: -> -2
@canUse = (player) ->
hoursPlayed = (Math.abs player.registrationDate.getTime()-Date.now()) / 36e5
hoursPlayed >= 2
@desc = "Play for 2 hours"
module.exports = exports = Hasty
| true |
Personality = require "../base/Personality"
`/**
* This personality makes you move faster around the world, at the cost of combat statistics.
*
* @name PI:NAME:<NAME>END_PI
* @prerequisite Play for 2 hours
* @effect +2 haste
* @effect -2 offense
* @effect -2 defense
* @category Personalities
* @package Player
*/`
class Hasty extends Personality
constructor: ->
haste: -> 2
offense: -> -2
defense: -> -2
@canUse = (player) ->
hoursPlayed = (Math.abs player.registrationDate.getTime()-Date.now()) / 36e5
hoursPlayed >= 2
@desc = "Play for 2 hours"
module.exports = exports = Hasty
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999136924743652,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/forum.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.
class @Forum
boot: =>
@refreshCounter()
@refreshLoadMoreLinks()
# Scroll last because other actions may change page's height.
@initialScrollTo()
constructor: ->
@_totalPostsDiv = document.getElementsByClassName('js-forum__total-count')
@_deletedPostsDiv = document.getElementsByClassName('js-forum__deleted-count')
@_firstPostDiv = document.getElementsByClassName('js-forum__topic-first-post-id')
@_userCanModerateDiv = document.getElementsByClassName('js-forum__topic-user-can-moderate')
@_postsCounter = document.getElementsByClassName('js-forum__posts-counter')
@_postsProgress = document.getElementsByClassName('js-forum__posts-progress')
@posts = document.getElementsByClassName('js-forum-post')
@loadMoreLinks = document.getElementsByClassName('js-forum-posts-show-more')
@maxPosts = 250
$(document).on 'turbolinks:load osu:page:change', @boot
$(window).on 'throttled-scroll', @refreshCounter
$(document).on 'click', '.js-forum-posts-show-more', @showMore
$(document).on 'click', '.js-post-url', @postUrlClick
$(document).on 'submit', '.js-forum-posts-jump-to', @jumpToSubmit
$(document).on 'keyup', @keyboardNavigation
$(document).on 'click', '.js-forum-topic-moderate--toggle-deleted', @toggleDeleted
userCanModerate: ->
@_userCanModerateDiv[0].getAttribute('data-user-can-moderate') == '1'
postPosition: (el) =>
parseInt(el.getAttribute('data-post-position'), 10)
firstPostId: ->
parseInt @_firstPostDiv[0].getAttribute('data-first-post-id'), 10
postId: (el) ->
parseInt el.getAttribute('data-post-id'), 10
totalPosts: =>
return null if @_totalPostsDiv.length == 0
parseInt @_totalPostsDiv[0].dataset.total, 10
# null if option not available (not moderator), false/true accordingly otherwise
showDeleted: =>
toggle = document.querySelector('.js-forum-topic-moderate--toggle-deleted')
return unless toggle?
toggle.dataset.showDeleted == '1'
setTotalPosts: (n) =>
$(@_totalPostsDiv)
.text osu.formatNumber(n)
.attr 'data-total', n
deletedPosts: ->
return null if @_deletedPostsDiv.length == 0
parseInt @_deletedPostsDiv[0].dataset.total, 10
setDeletedPosts: (n) ->
$(@_deletedPostsDiv)
.text osu.formatNumber(n)
.attr 'data-total', n
setCounter: (currentPost) =>
@currentPostPosition = @postPosition(currentPost)
@setTotalPosts(@currentPostPosition) if @currentPostPosition > @totalPosts()
window.reloadUrl = @postUrlN @currentPostPosition
@_postsCounter[0].textContent = osu.formatNumber @currentPostPosition
@_postsProgress[0].style.width = "#{100 * @currentPostPosition / @totalPosts()}%"
endPost: => @posts[@posts.length - 1]
firstPostLoaded: =>
@postId(@posts[0]) == @firstPostId()
lastPostLoaded: =>
@postPosition(@endPost()) == @totalPosts()
refreshLoadMoreLinks: =>
return unless @loadMoreLinks.length
firstPostLoaded = @firstPostLoaded()
$('.js-header--main').toggleClass 'hidden', !firstPostLoaded
$('.js-header--alt').toggleClass 'hidden', firstPostLoaded
lastPostLoaded = @lastPostLoaded()
$('.js-forum__posts-show-more--next')
.toggleClass 'hidden', lastPostLoaded
if !@userCanModerate()
$('.js-post-delete-toggle').hide()
if lastPostLoaded
$(@endPost()).find('.js-post-delete-toggle').css(display: '')
refreshCounter: =>
return if @_postsCounter.length == 0
currentPost = null
if osu.bottomPage()
currentPost = @posts[@posts.length - 1]
else
for post in @posts
postTop = post.getBoundingClientRect().top
if Math.floor(window.stickyHeader.scrollOffset(postTop)) <= 0
currentPost = post
else
break
# no post visible?
currentPost ?= @posts[0]
@setCounter(currentPost)
jumpTo: (postN) =>
postN = parseInt postN, 10
return false unless isFinite(postN)
postN = Math.max(postN, 1)
postN = Math.min(postN, @totalPosts())
$post = $(".js-forum-post[data-post-position='#{postN}']")
@_postsCounter[0].textContent = osu.formatNumber postN
if $post.length
@scrollTo $post.attr('data-post-id')
else
Turbolinks.visit @postUrlN(postN)
true
keyboardNavigation: (e) =>
return if osu.isInputElement(e.target) or not @_postsCounter.length
e.preventDefault()
n = switch e.which
when 37 then @currentPostPosition - 1
when 39 then @currentPostPosition + 1
try @jumpTo n
scrollTo: (postId) =>
post = document.querySelector(".js-forum-post[data-post-id='#{postId}']")
return unless post
postTop = if @postPosition(post) == 1
0
else
$(post).offset().top
postTop = window.stickyHeader.scrollOffset(postTop) if postTop != 0
# using jquery smooth scrollTo will cause unwanted events to trigger on the way down.
window.scrollTo window.pageXOffset, postTop
@highlightPost post
highlightPost: (post) ->
$('.js-forum-post--highlighted').removeClass('js-forum-post--highlighted')
$(post).addClass('js-forum-post--highlighted')
toggleDeleted: =>
Turbolinks.visit osu.updateQueryString @postUrlN(@currentPostPosition),
with_deleted: +!@showDeleted()
initialScrollTo: =>
return if location.hash != '' ||
!window.postJumpTo? ||
window.postJumpTo == 0
@scrollTo window.postJumpTo
window.postJumpTo = 0
postUrlClick: (e) =>
e.preventDefault()
id = $(e.target).closest('.js-forum-post').attr('data-post-id')
@scrollTo id
postUrlN: (postN) ->
url = "#{document.location.pathname}?n=#{postN}"
if @showDeleted() == false
url += "&with_deleted=0"
url
showMore: (e) =>
e.preventDefault()
return if e.currentTarget.classList.contains('js-disabled')
$link = $(e.currentTarget)
mode = $link.data('mode')
options =
start: null
end: null
skip_layout: 1
with_deleted: +@showDeleted()
if mode == 'previous'
$refPost = $('.js-forum-post').first()
options['end'] = $refPost.data('post-id') - 1
else
$refPost = $('.js-forum-post').last()
options['start'] = $refPost.data('post-id') + 1
$link.addClass 'js-disabled'
$.get(window.canonicalUrl, options)
.done (data) =>
scrollReference = $refPost[0]
scrollReferenceTop = scrollReference.getBoundingClientRect().top
if mode == 'previous'
$link.after data
toRemoveStart = @maxPosts
toRemoveEnd = @posts.length
else
$link.before data
toRemoveStart = 0
toRemoveEnd = @posts.length - @maxPosts
if toRemoveStart < toRemoveEnd
parent = @posts[0].parentNode
parent.removeChild(post) for post in _.slice(@posts, toRemoveStart, toRemoveEnd)
@refreshLoadMoreLinks()
# Restore scroll position after adding/removing posts.
# Called after refreshLoadMoreLinks to allow header changes
# to be included in calculation.
x = window.pageXOffset
currentScrollReferenceTop = scrollReference.getBoundingClientRect().top
currentDocumentScrollTop = window.pageYOffset
targetDocumentScrollTop = currentDocumentScrollTop + currentScrollReferenceTop - scrollReferenceTop
window.scrollTo x, targetDocumentScrollTop
osu.pageChange()
$link.attr 'data-failed', '0'
.always ->
$link.removeClass 'js-disabled'
.fail ->
$link.attr 'data-failed', '1'
jumpToSubmit: (e) =>
e.preventDefault()
LoadingOverlay.hide()
if @jumpTo $(e.target).find('[name="n"]').val()
$.publish 'forum:topic:jumpTo'
| 140277 | # 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.
class @Forum
boot: =>
@refreshCounter()
@refreshLoadMoreLinks()
# Scroll last because other actions may change page's height.
@initialScrollTo()
constructor: ->
@_totalPostsDiv = document.getElementsByClassName('js-forum__total-count')
@_deletedPostsDiv = document.getElementsByClassName('js-forum__deleted-count')
@_firstPostDiv = document.getElementsByClassName('js-forum__topic-first-post-id')
@_userCanModerateDiv = document.getElementsByClassName('js-forum__topic-user-can-moderate')
@_postsCounter = document.getElementsByClassName('js-forum__posts-counter')
@_postsProgress = document.getElementsByClassName('js-forum__posts-progress')
@posts = document.getElementsByClassName('js-forum-post')
@loadMoreLinks = document.getElementsByClassName('js-forum-posts-show-more')
@maxPosts = 250
$(document).on 'turbolinks:load osu:page:change', @boot
$(window).on 'throttled-scroll', @refreshCounter
$(document).on 'click', '.js-forum-posts-show-more', @showMore
$(document).on 'click', '.js-post-url', @postUrlClick
$(document).on 'submit', '.js-forum-posts-jump-to', @jumpToSubmit
$(document).on 'keyup', @keyboardNavigation
$(document).on 'click', '.js-forum-topic-moderate--toggle-deleted', @toggleDeleted
userCanModerate: ->
@_userCanModerateDiv[0].getAttribute('data-user-can-moderate') == '1'
postPosition: (el) =>
parseInt(el.getAttribute('data-post-position'), 10)
firstPostId: ->
parseInt @_firstPostDiv[0].getAttribute('data-first-post-id'), 10
postId: (el) ->
parseInt el.getAttribute('data-post-id'), 10
totalPosts: =>
return null if @_totalPostsDiv.length == 0
parseInt @_totalPostsDiv[0].dataset.total, 10
# null if option not available (not moderator), false/true accordingly otherwise
showDeleted: =>
toggle = document.querySelector('.js-forum-topic-moderate--toggle-deleted')
return unless toggle?
toggle.dataset.showDeleted == '1'
setTotalPosts: (n) =>
$(@_totalPostsDiv)
.text osu.formatNumber(n)
.attr 'data-total', n
deletedPosts: ->
return null if @_deletedPostsDiv.length == 0
parseInt @_deletedPostsDiv[0].dataset.total, 10
setDeletedPosts: (n) ->
$(@_deletedPostsDiv)
.text osu.formatNumber(n)
.attr 'data-total', n
setCounter: (currentPost) =>
@currentPostPosition = @postPosition(currentPost)
@setTotalPosts(@currentPostPosition) if @currentPostPosition > @totalPosts()
window.reloadUrl = @postUrlN @currentPostPosition
@_postsCounter[0].textContent = osu.formatNumber @currentPostPosition
@_postsProgress[0].style.width = "#{100 * @currentPostPosition / @totalPosts()}%"
endPost: => @posts[@posts.length - 1]
firstPostLoaded: =>
@postId(@posts[0]) == @firstPostId()
lastPostLoaded: =>
@postPosition(@endPost()) == @totalPosts()
refreshLoadMoreLinks: =>
return unless @loadMoreLinks.length
firstPostLoaded = @firstPostLoaded()
$('.js-header--main').toggleClass 'hidden', !firstPostLoaded
$('.js-header--alt').toggleClass 'hidden', firstPostLoaded
lastPostLoaded = @lastPostLoaded()
$('.js-forum__posts-show-more--next')
.toggleClass 'hidden', lastPostLoaded
if !@userCanModerate()
$('.js-post-delete-toggle').hide()
if lastPostLoaded
$(@endPost()).find('.js-post-delete-toggle').css(display: '')
refreshCounter: =>
return if @_postsCounter.length == 0
currentPost = null
if osu.bottomPage()
currentPost = @posts[@posts.length - 1]
else
for post in @posts
postTop = post.getBoundingClientRect().top
if Math.floor(window.stickyHeader.scrollOffset(postTop)) <= 0
currentPost = post
else
break
# no post visible?
currentPost ?= @posts[0]
@setCounter(currentPost)
jumpTo: (postN) =>
postN = parseInt postN, 10
return false unless isFinite(postN)
postN = Math.max(postN, 1)
postN = Math.min(postN, @totalPosts())
$post = $(".js-forum-post[data-post-position='#{postN}']")
@_postsCounter[0].textContent = osu.formatNumber postN
if $post.length
@scrollTo $post.attr('data-post-id')
else
Turbolinks.visit @postUrlN(postN)
true
keyboardNavigation: (e) =>
return if osu.isInputElement(e.target) or not @_postsCounter.length
e.preventDefault()
n = switch e.which
when 37 then @currentPostPosition - 1
when 39 then @currentPostPosition + 1
try @jumpTo n
scrollTo: (postId) =>
post = document.querySelector(".js-forum-post[data-post-id='#{postId}']")
return unless post
postTop = if @postPosition(post) == 1
0
else
$(post).offset().top
postTop = window.stickyHeader.scrollOffset(postTop) if postTop != 0
# using jquery smooth scrollTo will cause unwanted events to trigger on the way down.
window.scrollTo window.pageXOffset, postTop
@highlightPost post
highlightPost: (post) ->
$('.js-forum-post--highlighted').removeClass('js-forum-post--highlighted')
$(post).addClass('js-forum-post--highlighted')
toggleDeleted: =>
Turbolinks.visit osu.updateQueryString @postUrlN(@currentPostPosition),
with_deleted: +!@showDeleted()
initialScrollTo: =>
return if location.hash != '' ||
!window.postJumpTo? ||
window.postJumpTo == 0
@scrollTo window.postJumpTo
window.postJumpTo = 0
postUrlClick: (e) =>
e.preventDefault()
id = $(e.target).closest('.js-forum-post').attr('data-post-id')
@scrollTo id
postUrlN: (postN) ->
url = "#{document.location.pathname}?n=#{postN}"
if @showDeleted() == false
url += "&with_deleted=0"
url
showMore: (e) =>
e.preventDefault()
return if e.currentTarget.classList.contains('js-disabled')
$link = $(e.currentTarget)
mode = $link.data('mode')
options =
start: null
end: null
skip_layout: 1
with_deleted: +@showDeleted()
if mode == 'previous'
$refPost = $('.js-forum-post').first()
options['end'] = $refPost.data('post-id') - 1
else
$refPost = $('.js-forum-post').last()
options['start'] = $refPost.data('post-id') + 1
$link.addClass 'js-disabled'
$.get(window.canonicalUrl, options)
.done (data) =>
scrollReference = $refPost[0]
scrollReferenceTop = scrollReference.getBoundingClientRect().top
if mode == 'previous'
$link.after data
toRemoveStart = @maxPosts
toRemoveEnd = @posts.length
else
$link.before data
toRemoveStart = 0
toRemoveEnd = @posts.length - @maxPosts
if toRemoveStart < toRemoveEnd
parent = @posts[0].parentNode
parent.removeChild(post) for post in _.slice(@posts, toRemoveStart, toRemoveEnd)
@refreshLoadMoreLinks()
# Restore scroll position after adding/removing posts.
# Called after refreshLoadMoreLinks to allow header changes
# to be included in calculation.
x = window.pageXOffset
currentScrollReferenceTop = scrollReference.getBoundingClientRect().top
currentDocumentScrollTop = window.pageYOffset
targetDocumentScrollTop = currentDocumentScrollTop + currentScrollReferenceTop - scrollReferenceTop
window.scrollTo x, targetDocumentScrollTop
osu.pageChange()
$link.attr 'data-failed', '0'
.always ->
$link.removeClass 'js-disabled'
.fail ->
$link.attr 'data-failed', '1'
jumpToSubmit: (e) =>
e.preventDefault()
LoadingOverlay.hide()
if @jumpTo $(e.target).find('[name="n"]').val()
$.publish 'forum:topic:jumpTo'
| 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.
class @Forum
boot: =>
@refreshCounter()
@refreshLoadMoreLinks()
# Scroll last because other actions may change page's height.
@initialScrollTo()
constructor: ->
@_totalPostsDiv = document.getElementsByClassName('js-forum__total-count')
@_deletedPostsDiv = document.getElementsByClassName('js-forum__deleted-count')
@_firstPostDiv = document.getElementsByClassName('js-forum__topic-first-post-id')
@_userCanModerateDiv = document.getElementsByClassName('js-forum__topic-user-can-moderate')
@_postsCounter = document.getElementsByClassName('js-forum__posts-counter')
@_postsProgress = document.getElementsByClassName('js-forum__posts-progress')
@posts = document.getElementsByClassName('js-forum-post')
@loadMoreLinks = document.getElementsByClassName('js-forum-posts-show-more')
@maxPosts = 250
$(document).on 'turbolinks:load osu:page:change', @boot
$(window).on 'throttled-scroll', @refreshCounter
$(document).on 'click', '.js-forum-posts-show-more', @showMore
$(document).on 'click', '.js-post-url', @postUrlClick
$(document).on 'submit', '.js-forum-posts-jump-to', @jumpToSubmit
$(document).on 'keyup', @keyboardNavigation
$(document).on 'click', '.js-forum-topic-moderate--toggle-deleted', @toggleDeleted
userCanModerate: ->
@_userCanModerateDiv[0].getAttribute('data-user-can-moderate') == '1'
postPosition: (el) =>
parseInt(el.getAttribute('data-post-position'), 10)
firstPostId: ->
parseInt @_firstPostDiv[0].getAttribute('data-first-post-id'), 10
postId: (el) ->
parseInt el.getAttribute('data-post-id'), 10
totalPosts: =>
return null if @_totalPostsDiv.length == 0
parseInt @_totalPostsDiv[0].dataset.total, 10
# null if option not available (not moderator), false/true accordingly otherwise
showDeleted: =>
toggle = document.querySelector('.js-forum-topic-moderate--toggle-deleted')
return unless toggle?
toggle.dataset.showDeleted == '1'
setTotalPosts: (n) =>
$(@_totalPostsDiv)
.text osu.formatNumber(n)
.attr 'data-total', n
deletedPosts: ->
return null if @_deletedPostsDiv.length == 0
parseInt @_deletedPostsDiv[0].dataset.total, 10
setDeletedPosts: (n) ->
$(@_deletedPostsDiv)
.text osu.formatNumber(n)
.attr 'data-total', n
setCounter: (currentPost) =>
@currentPostPosition = @postPosition(currentPost)
@setTotalPosts(@currentPostPosition) if @currentPostPosition > @totalPosts()
window.reloadUrl = @postUrlN @currentPostPosition
@_postsCounter[0].textContent = osu.formatNumber @currentPostPosition
@_postsProgress[0].style.width = "#{100 * @currentPostPosition / @totalPosts()}%"
endPost: => @posts[@posts.length - 1]
firstPostLoaded: =>
@postId(@posts[0]) == @firstPostId()
lastPostLoaded: =>
@postPosition(@endPost()) == @totalPosts()
refreshLoadMoreLinks: =>
return unless @loadMoreLinks.length
firstPostLoaded = @firstPostLoaded()
$('.js-header--main').toggleClass 'hidden', !firstPostLoaded
$('.js-header--alt').toggleClass 'hidden', firstPostLoaded
lastPostLoaded = @lastPostLoaded()
$('.js-forum__posts-show-more--next')
.toggleClass 'hidden', lastPostLoaded
if !@userCanModerate()
$('.js-post-delete-toggle').hide()
if lastPostLoaded
$(@endPost()).find('.js-post-delete-toggle').css(display: '')
refreshCounter: =>
return if @_postsCounter.length == 0
currentPost = null
if osu.bottomPage()
currentPost = @posts[@posts.length - 1]
else
for post in @posts
postTop = post.getBoundingClientRect().top
if Math.floor(window.stickyHeader.scrollOffset(postTop)) <= 0
currentPost = post
else
break
# no post visible?
currentPost ?= @posts[0]
@setCounter(currentPost)
jumpTo: (postN) =>
postN = parseInt postN, 10
return false unless isFinite(postN)
postN = Math.max(postN, 1)
postN = Math.min(postN, @totalPosts())
$post = $(".js-forum-post[data-post-position='#{postN}']")
@_postsCounter[0].textContent = osu.formatNumber postN
if $post.length
@scrollTo $post.attr('data-post-id')
else
Turbolinks.visit @postUrlN(postN)
true
keyboardNavigation: (e) =>
return if osu.isInputElement(e.target) or not @_postsCounter.length
e.preventDefault()
n = switch e.which
when 37 then @currentPostPosition - 1
when 39 then @currentPostPosition + 1
try @jumpTo n
scrollTo: (postId) =>
post = document.querySelector(".js-forum-post[data-post-id='#{postId}']")
return unless post
postTop = if @postPosition(post) == 1
0
else
$(post).offset().top
postTop = window.stickyHeader.scrollOffset(postTop) if postTop != 0
# using jquery smooth scrollTo will cause unwanted events to trigger on the way down.
window.scrollTo window.pageXOffset, postTop
@highlightPost post
highlightPost: (post) ->
$('.js-forum-post--highlighted').removeClass('js-forum-post--highlighted')
$(post).addClass('js-forum-post--highlighted')
toggleDeleted: =>
Turbolinks.visit osu.updateQueryString @postUrlN(@currentPostPosition),
with_deleted: +!@showDeleted()
initialScrollTo: =>
return if location.hash != '' ||
!window.postJumpTo? ||
window.postJumpTo == 0
@scrollTo window.postJumpTo
window.postJumpTo = 0
postUrlClick: (e) =>
e.preventDefault()
id = $(e.target).closest('.js-forum-post').attr('data-post-id')
@scrollTo id
postUrlN: (postN) ->
url = "#{document.location.pathname}?n=#{postN}"
if @showDeleted() == false
url += "&with_deleted=0"
url
showMore: (e) =>
e.preventDefault()
return if e.currentTarget.classList.contains('js-disabled')
$link = $(e.currentTarget)
mode = $link.data('mode')
options =
start: null
end: null
skip_layout: 1
with_deleted: +@showDeleted()
if mode == 'previous'
$refPost = $('.js-forum-post').first()
options['end'] = $refPost.data('post-id') - 1
else
$refPost = $('.js-forum-post').last()
options['start'] = $refPost.data('post-id') + 1
$link.addClass 'js-disabled'
$.get(window.canonicalUrl, options)
.done (data) =>
scrollReference = $refPost[0]
scrollReferenceTop = scrollReference.getBoundingClientRect().top
if mode == 'previous'
$link.after data
toRemoveStart = @maxPosts
toRemoveEnd = @posts.length
else
$link.before data
toRemoveStart = 0
toRemoveEnd = @posts.length - @maxPosts
if toRemoveStart < toRemoveEnd
parent = @posts[0].parentNode
parent.removeChild(post) for post in _.slice(@posts, toRemoveStart, toRemoveEnd)
@refreshLoadMoreLinks()
# Restore scroll position after adding/removing posts.
# Called after refreshLoadMoreLinks to allow header changes
# to be included in calculation.
x = window.pageXOffset
currentScrollReferenceTop = scrollReference.getBoundingClientRect().top
currentDocumentScrollTop = window.pageYOffset
targetDocumentScrollTop = currentDocumentScrollTop + currentScrollReferenceTop - scrollReferenceTop
window.scrollTo x, targetDocumentScrollTop
osu.pageChange()
$link.attr 'data-failed', '0'
.always ->
$link.removeClass 'js-disabled'
.fail ->
$link.attr 'data-failed', '1'
jumpToSubmit: (e) =>
e.preventDefault()
LoadingOverlay.hide()
if @jumpTo $(e.target).find('[name="n"]').val()
$.publish 'forum:topic:jumpTo'
|
[
{
"context": "re 'moment'\nopenSale = fabricate 'sale',\n name: 'Awesome Sale'\n is_auction: true\n auction_state: 'open'\n sta",
"end": 282,
"score": 0.9925919771194458,
"start": 270,
"tag": "NAME",
"value": "Awesome Sale"
},
{
"context": ".sync.args[0][2].success fabricate 'sale', name: 'Awesome Sale', is_auction: true, auction_state: 'closed'\n",
"end": 3474,
"score": 0.5381906628608704,
"start": 3467,
"tag": "NAME",
"value": "Awesome"
},
{
"context": ".sync.args[0][2].success fabricate 'sale', name: 'Awesome Sale', is_auction: false\n\n @next.args[0][0].statu",
"end": 4195,
"score": 0.8060407042503357,
"start": 4183,
"tag": "NAME",
"value": "Awesome Sale"
}
] | src/mobile/apps/auction_support/test/routes.coffee | kanaabe/force | 0 | _ = require 'underscore'
routes = require '../routes'
sinon = require 'sinon'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../../models/current_user.coffee'
moment = require 'moment'
openSale = fabricate 'sale',
name: 'Awesome Sale'
is_auction: true
auction_state: 'open'
start_at: moment().subtract(1, 'minutes').format()
end_at: moment().add(3, 'minutes').format()
describe '#auctionRegistration', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@req =
params: { id: 'awesome-sale' }
query: {}
@res =
status: sinon.stub()
render: sinon.stub()
redirect: sinon.stub()
locals:
sd:
API_URL: 'http://localhost:5000'
asset: ->
@next = sinon.stub()
afterEach ->
Backbone.sync.restore()
it 'redirects to login without user', ->
routes.auctionRegistration @req, @res
@res.redirect.args[0][0].should.equal "/log_in?redirect_uri=/auction-registration/awesome-sale?redirect_uri=undefined"
describe 'with current user', ->
beforeEach ->
@req.user = new CurrentUser()
it 'redirects to success url if sale is registerable and user has already registered', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success [{foo: 'bar'}]
routes.auctionRegistration @req, @res
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/confirm-registration"
it 'renders registration form if sale is registerable and user has no credit cards on file', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success []
@res.render.args[0][0].should.equal 'registration'
@res.render.args[0][1].sale.get('name').should.equal 'Awesome Sale'
it 'creates bidder and redirects to sale if sale is registerable and user has credit card on file and user has accepted conditions', ->
@req.query = {'accepted-conditions': 'true' }
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
Backbone.sync.args[3][2].success [{}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/confirm-registration"
it 'redirects to modal if user has credit card on file and has not accepted conditions', ->
@req.query = {'accepted-conditions': 'false' } # explicitly passed as false
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/registration-flow"
it 'redirects to modal if user has credit card on file and has not accepted conditions', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/registration-flow"
it 'renders registration error page if sale is an auction and is not registerable', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success fabricate 'sale', name: 'Awesome Sale', is_auction: true, auction_state: 'closed'
@res.render.args[0][0].should.equal 'registration-error'
@res.render.args[0][1].sale.get('name').should.equal 'Awesome Sale'
it 'redirects to url if redirect_uri param is passed', ->
@req.query =
redirect_uri: '/auction/whtney-art-party/artwork-cool/bid'
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal @req.query.redirect_uri
it '404 if sale is not auction', ->
routes.auctionRegistration @req, @res, @next
Backbone.sync.args[0][2].success fabricate 'sale', name: 'Awesome Sale', is_auction: false
@next.args[0][0].status.should.equal 404
@next.args[0][0].message.should.equal 'Not Found'
| 207340 | _ = require 'underscore'
routes = require '../routes'
sinon = require 'sinon'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../../models/current_user.coffee'
moment = require 'moment'
openSale = fabricate 'sale',
name: '<NAME>'
is_auction: true
auction_state: 'open'
start_at: moment().subtract(1, 'minutes').format()
end_at: moment().add(3, 'minutes').format()
describe '#auctionRegistration', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@req =
params: { id: 'awesome-sale' }
query: {}
@res =
status: sinon.stub()
render: sinon.stub()
redirect: sinon.stub()
locals:
sd:
API_URL: 'http://localhost:5000'
asset: ->
@next = sinon.stub()
afterEach ->
Backbone.sync.restore()
it 'redirects to login without user', ->
routes.auctionRegistration @req, @res
@res.redirect.args[0][0].should.equal "/log_in?redirect_uri=/auction-registration/awesome-sale?redirect_uri=undefined"
describe 'with current user', ->
beforeEach ->
@req.user = new CurrentUser()
it 'redirects to success url if sale is registerable and user has already registered', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success [{foo: 'bar'}]
routes.auctionRegistration @req, @res
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/confirm-registration"
it 'renders registration form if sale is registerable and user has no credit cards on file', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success []
@res.render.args[0][0].should.equal 'registration'
@res.render.args[0][1].sale.get('name').should.equal 'Awesome Sale'
it 'creates bidder and redirects to sale if sale is registerable and user has credit card on file and user has accepted conditions', ->
@req.query = {'accepted-conditions': 'true' }
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
Backbone.sync.args[3][2].success [{}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/confirm-registration"
it 'redirects to modal if user has credit card on file and has not accepted conditions', ->
@req.query = {'accepted-conditions': 'false' } # explicitly passed as false
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/registration-flow"
it 'redirects to modal if user has credit card on file and has not accepted conditions', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/registration-flow"
it 'renders registration error page if sale is an auction and is not registerable', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success fabricate 'sale', name: '<NAME> Sale', is_auction: true, auction_state: 'closed'
@res.render.args[0][0].should.equal 'registration-error'
@res.render.args[0][1].sale.get('name').should.equal 'Awesome Sale'
it 'redirects to url if redirect_uri param is passed', ->
@req.query =
redirect_uri: '/auction/whtney-art-party/artwork-cool/bid'
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal @req.query.redirect_uri
it '404 if sale is not auction', ->
routes.auctionRegistration @req, @res, @next
Backbone.sync.args[0][2].success fabricate 'sale', name: '<NAME>', is_auction: false
@next.args[0][0].status.should.equal 404
@next.args[0][0].message.should.equal 'Not Found'
| true | _ = require 'underscore'
routes = require '../routes'
sinon = require 'sinon'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
CurrentUser = require '../../../models/current_user.coffee'
moment = require 'moment'
openSale = fabricate 'sale',
name: 'PI:NAME:<NAME>END_PI'
is_auction: true
auction_state: 'open'
start_at: moment().subtract(1, 'minutes').format()
end_at: moment().add(3, 'minutes').format()
describe '#auctionRegistration', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@req =
params: { id: 'awesome-sale' }
query: {}
@res =
status: sinon.stub()
render: sinon.stub()
redirect: sinon.stub()
locals:
sd:
API_URL: 'http://localhost:5000'
asset: ->
@next = sinon.stub()
afterEach ->
Backbone.sync.restore()
it 'redirects to login without user', ->
routes.auctionRegistration @req, @res
@res.redirect.args[0][0].should.equal "/log_in?redirect_uri=/auction-registration/awesome-sale?redirect_uri=undefined"
describe 'with current user', ->
beforeEach ->
@req.user = new CurrentUser()
it 'redirects to success url if sale is registerable and user has already registered', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success [{foo: 'bar'}]
routes.auctionRegistration @req, @res
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/confirm-registration"
it 'renders registration form if sale is registerable and user has no credit cards on file', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success []
@res.render.args[0][0].should.equal 'registration'
@res.render.args[0][1].sale.get('name').should.equal 'Awesome Sale'
it 'creates bidder and redirects to sale if sale is registerable and user has credit card on file and user has accepted conditions', ->
@req.query = {'accepted-conditions': 'true' }
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
Backbone.sync.args[3][2].success [{}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/confirm-registration"
it 'redirects to modal if user has credit card on file and has not accepted conditions', ->
@req.query = {'accepted-conditions': 'false' } # explicitly passed as false
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/registration-flow"
it 'redirects to modal if user has credit card on file and has not accepted conditions', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success []
Backbone.sync.args[2][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal "/auction/whtney-art-party/registration-flow"
it 'renders registration error page if sale is an auction and is not registerable', ->
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success fabricate 'sale', name: 'PI:NAME:<NAME>END_PI Sale', is_auction: true, auction_state: 'closed'
@res.render.args[0][0].should.equal 'registration-error'
@res.render.args[0][1].sale.get('name').should.equal 'Awesome Sale'
it 'redirects to url if redirect_uri param is passed', ->
@req.query =
redirect_uri: '/auction/whtney-art-party/artwork-cool/bid'
routes.auctionRegistration @req, @res
Backbone.sync.args[0][2].success openSale
Backbone.sync.args[1][2].success [{foo: 'bar'}]
@res.redirect.args[0][0].should.equal @req.query.redirect_uri
it '404 if sale is not auction', ->
routes.auctionRegistration @req, @res, @next
Backbone.sync.args[0][2].success fabricate 'sale', name: 'PI:NAME:<NAME>END_PI', is_auction: false
@next.args[0][0].status.should.equal 404
@next.args[0][0].message.should.equal 'Not Found'
|
[
{
"context": "gqueries.find_or_create_by_key('installed_capacity_solar_and_wind')\n\n can_be_shown_as_table: -> false\n\n ",
"end": 199,
"score": 0.5302073955535889,
"start": 193,
"tag": "KEY",
"value": "solar_"
}
] | app/assets/javascripts/d3/import_export_cwe.coffee | Abeer-AlHasan/Abu-Dhabi-Model | 21 | D3.import_export_cwe =
View: class extends D3ChartView
initialize: ->
D3ChartView.prototype.initialize.call(this)
@gquery = gqueries.find_or_create_by_key('installed_capacity_solar_and_wind')
can_be_shown_as_table: -> false
margins :
top: 20
bottom: 50
left: 50
right: 20
filter_on_y_values = (data, max) =>
result = []
result.push(d) for d in data when d.y <= max
return result
formatDay = (d,i) -> if i <= 13 then i + 8 else ""
draw: =>
# Set maximum x and y values
@maximum_x = 28
@maximum_y = 60
# Prepare chart data
APX_DAM = [{"x": "1", "y": "47.01"}, {"x": "3", "y": "49.14"}, {"x": "5", "y": "50.98"}, {"x": "7", "y": "46.17"}, {"x": "9", "y": "38.06"}, {"x": "11", "y": "47.25"}, {"x": "13", "y": "49.81"}, {"x": "15", "y": "46.60"}, {"x": "17", "y": "45.58"}, {"x": "19", "y": "43.19"}, {"x": "21", "y": "40.68"}, {"x": "23", "y": "43.99"}, {"x": "25", "y": "52.66"}, {"x": "27", "y": "51.36"}]
Belpex_DAM = [{"x": "1", "y": "42.40"}, {"x": "3", "y": "41.21"}, {"x": "5", "y": "49.75"}, {"x": "7", "y": "42.32"}, {"x": "9", "y": "30.34"}, {"x": "11", "y": "46.20"}, {"x": "13", "y": "49.20"}, {"x": "15", "y": "46.36"}, {"x": "17", "y": "44.04"}, {"x": "19", "y": "39.54"}, {"x": "21", "y": "32.24"}, {"x": "23", "y": "34.75"}, {"x": "25", "y": "51.90"}, {"x": "27", "y": "51.36"}]
EPEX_Spot_FR = [{"x": "1", "y": "41.6"}, {"x": "3", "y": "41.21"}, {"x": "5", "y": "48.97"}, {"x": "7", "y": "42.32"}, {"x": "9", "y": "29.98"}, {"x": "11", "y": "44.43"}, {"x": "13", "y": "49.2"}, {"x": "15", "y": "46.36"}, {"x": "17", "y": "41.83"}, {"x": "19", "y": "38.19"}, {"x": "21", "y": "31.63"}, {"x": "23", "y": "33.25"}, {"x": "25", "y": "50.88"}, {"x": "27", "y": "51.36"}]
EPEX_Spot_DE = [{"x": "1", "y": "33.49"}, {"x": "3", "y": "31.13"}, {"x": "5", "y": "28.31"}, {"x": "7", "y": "29.66"}, {"x": "9", "y": "19.59"}, {"x": "11", "y": "41.94"}, {"x": "13", "y": "49.35"}, {"x": "15", "y": "45.69"}, {"x": "17", "y": "40.75"}, {"x": "19", "y": "39.58"}, {"x": "21", "y": "31.87"}, {"x": "23", "y": "24.69"}, {"x": "25", "y": "48.52"}, {"x": "27", "y": "49.51"}]
theData = [{color: "#00BFFF", values: APX_DAM, label: "APX DAM (NL)"}, {color: "#1947A8", values: Belpex_DAM , label: "Belpex DAM (BE)"}, {color: "#F5C400", values: EPEX_Spot_FR, label: "EPEX Spot FR"}, {color: "#DB2C18", values: EPEX_Spot_DE, label: "EPEX Spot DE"}]
# Create SVG convas and set related variables
[@width, @height] = @available_size()
legend_columns = 2
legend_rows = theData.length / legend_columns
legend_column_width = @width/ legend_columns
legend_margin = 50
cell_height = @legend_cell_height
@series_height = @height - legend_margin
@svg = @create_svg_container @width, @height, @margins
# Define scales and create axes
xScale = d3.scale.linear()
.domain([0, @maximum_x])
.range([0, @width])
yScale = d3.scale.linear()
.domain([10, @maximum_y])
.range([@series_height, 0])
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickFormat(formatDay)
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickValues([10,20,30,40,50,60])
.tickSize(0)
xAxisGroup = @svg.append("g")
.attr("class", "x_axis")
.attr("transform", "translate(0,#{@series_height})")
.call(xAxis)
yAxisGroup = @svg.append("g")
.attr("class", "y_axis")
.call(yAxis)
xAxisGroup.selectAll('text').attr('transform', 'translate(20,0)')
xAxisLabel = xAxisGroup.append("text")
.attr("class","label")
.attr("x", @width/ 2)
.attr("y", 35)
.text("#{I18n.t('output_elements.cwe_chart.date')}")
.attr("text-anchor","middle")
yAxisLabel = yAxisGroup.append("text")
.attr("class","label")
.attr("x", 0 - (@series_height/ 2))
.attr("y", 0 - 25)
.text("#{I18n.t('output_elements.cwe_chart.DAM_price')}")
.attr("text-anchor","middle")
.attr("transform", (d) -> "rotate(-90)" )
lineFunction = d3.svg.line()
.x( (d) -> xScale(d.x) )
.y( (d) -> yScale(d.y) )
.interpolate("none")
# Draw lines, using data binding
@svg.selectAll('path.serie')
.data(theData)
.enter()
.append('g')
.attr('id', (d,i) -> 'path_' + i)
.append('path')
.attr("d", (d) -> lineFunction(d.values) )
.attr("stroke", (d) -> d.color )
.attr("stroke-width", 3)
.attr("fill", "none")
markers = for data, i in theData
@svg.select('g#path_' + i).selectAll('circle')
.data(data.values)
.enter()
.append('circle')
.attr(
cx: (d) -> parseInt(xScale(d.x)),
cy: (d) -> parseInt(yScale(d.y)),
r: 5,
fill: data.color,
stroke: 'rgb(255,255,255)',
'stroke-width': 2
)
# Draw 'Indicative' label
@svg.append("text")
.attr("class", "indicative_label")
.text("#{I18n.t('output_elements.storage_chart.indicative')}")
.attr("transform", "translate(#{@width - 80},0) rotate(45)" )
# Create legend
legendGroup = @svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(0,#{@series_height + legend_margin})")
legendItem = legendGroup.append("svg")
# legendItem.selectAll('rect')
# .data(theData)
# .enter()
# .append('rect')
# .attr("x", (d,i) -> i%2 * legend_column_width + 5)
# .attr("y", (d,i) -> Math.floor(i / 2) * cell_height )
# .attr("width", "10")
# .attr("height", "10")
# .attr("fill", (d) -> d.color )
legendItem.selectAll('line')
.data(theData)
.enter()
.append('line')
.attr("x1", (d,i) -> i%2 * legend_column_width )
.attr("y1", (d,i) -> Math.floor(i / 2) * cell_height + 5)
.attr("x2", (d,i) -> i%2 * legend_column_width + 20)
.attr("y2", (d,i) -> Math.floor(i / 2) * cell_height + 5)
.attr("stroke-width", 3)
.attr("stroke", (d) -> d.color)
.attr("fill", "none")
legendItem.selectAll('circle')
.data(theData)
.enter()
.append('circle')
.attr(
cx: (d,i) -> i%2 * legend_column_width + 10,
cy: (d,i) -> Math.floor(i / 2) * cell_height + 5,
r: 5,
fill: (d) -> d.color,
stroke: "rgb(255,255,255)",
'stroke-width': 2
)
legendItem.selectAll('text')
.data(theData)
.enter()
.append('text')
.attr("class", "legend_label")
.attr("x", (d,i) -> i%2 * legend_column_width + 35 )
.attr("y", (d,i) -> Math.floor(i / 2) * cell_height + 10 )
.text((d) -> "#{d.label}" )
refresh: =>
# Define scales and line function
xScale = d3.scale.linear()
.domain([0, @maximum_x])
.range([0, @width])
yScale = d3.scale.linear()
.domain([0, @maximum_y])
.range([@series_height, 0])
lineFunction = d3.svg.line()
.x( (d) -> xScale(d.x) )
.y( (d) -> yScale(d.y) )
.interpolate("basis")
| 103808 | D3.import_export_cwe =
View: class extends D3ChartView
initialize: ->
D3ChartView.prototype.initialize.call(this)
@gquery = gqueries.find_or_create_by_key('installed_capacity_<KEY>and_wind')
can_be_shown_as_table: -> false
margins :
top: 20
bottom: 50
left: 50
right: 20
filter_on_y_values = (data, max) =>
result = []
result.push(d) for d in data when d.y <= max
return result
formatDay = (d,i) -> if i <= 13 then i + 8 else ""
draw: =>
# Set maximum x and y values
@maximum_x = 28
@maximum_y = 60
# Prepare chart data
APX_DAM = [{"x": "1", "y": "47.01"}, {"x": "3", "y": "49.14"}, {"x": "5", "y": "50.98"}, {"x": "7", "y": "46.17"}, {"x": "9", "y": "38.06"}, {"x": "11", "y": "47.25"}, {"x": "13", "y": "49.81"}, {"x": "15", "y": "46.60"}, {"x": "17", "y": "45.58"}, {"x": "19", "y": "43.19"}, {"x": "21", "y": "40.68"}, {"x": "23", "y": "43.99"}, {"x": "25", "y": "52.66"}, {"x": "27", "y": "51.36"}]
Belpex_DAM = [{"x": "1", "y": "42.40"}, {"x": "3", "y": "41.21"}, {"x": "5", "y": "49.75"}, {"x": "7", "y": "42.32"}, {"x": "9", "y": "30.34"}, {"x": "11", "y": "46.20"}, {"x": "13", "y": "49.20"}, {"x": "15", "y": "46.36"}, {"x": "17", "y": "44.04"}, {"x": "19", "y": "39.54"}, {"x": "21", "y": "32.24"}, {"x": "23", "y": "34.75"}, {"x": "25", "y": "51.90"}, {"x": "27", "y": "51.36"}]
EPEX_Spot_FR = [{"x": "1", "y": "41.6"}, {"x": "3", "y": "41.21"}, {"x": "5", "y": "48.97"}, {"x": "7", "y": "42.32"}, {"x": "9", "y": "29.98"}, {"x": "11", "y": "44.43"}, {"x": "13", "y": "49.2"}, {"x": "15", "y": "46.36"}, {"x": "17", "y": "41.83"}, {"x": "19", "y": "38.19"}, {"x": "21", "y": "31.63"}, {"x": "23", "y": "33.25"}, {"x": "25", "y": "50.88"}, {"x": "27", "y": "51.36"}]
EPEX_Spot_DE = [{"x": "1", "y": "33.49"}, {"x": "3", "y": "31.13"}, {"x": "5", "y": "28.31"}, {"x": "7", "y": "29.66"}, {"x": "9", "y": "19.59"}, {"x": "11", "y": "41.94"}, {"x": "13", "y": "49.35"}, {"x": "15", "y": "45.69"}, {"x": "17", "y": "40.75"}, {"x": "19", "y": "39.58"}, {"x": "21", "y": "31.87"}, {"x": "23", "y": "24.69"}, {"x": "25", "y": "48.52"}, {"x": "27", "y": "49.51"}]
theData = [{color: "#00BFFF", values: APX_DAM, label: "APX DAM (NL)"}, {color: "#1947A8", values: Belpex_DAM , label: "Belpex DAM (BE)"}, {color: "#F5C400", values: EPEX_Spot_FR, label: "EPEX Spot FR"}, {color: "#DB2C18", values: EPEX_Spot_DE, label: "EPEX Spot DE"}]
# Create SVG convas and set related variables
[@width, @height] = @available_size()
legend_columns = 2
legend_rows = theData.length / legend_columns
legend_column_width = @width/ legend_columns
legend_margin = 50
cell_height = @legend_cell_height
@series_height = @height - legend_margin
@svg = @create_svg_container @width, @height, @margins
# Define scales and create axes
xScale = d3.scale.linear()
.domain([0, @maximum_x])
.range([0, @width])
yScale = d3.scale.linear()
.domain([10, @maximum_y])
.range([@series_height, 0])
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickFormat(formatDay)
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickValues([10,20,30,40,50,60])
.tickSize(0)
xAxisGroup = @svg.append("g")
.attr("class", "x_axis")
.attr("transform", "translate(0,#{@series_height})")
.call(xAxis)
yAxisGroup = @svg.append("g")
.attr("class", "y_axis")
.call(yAxis)
xAxisGroup.selectAll('text').attr('transform', 'translate(20,0)')
xAxisLabel = xAxisGroup.append("text")
.attr("class","label")
.attr("x", @width/ 2)
.attr("y", 35)
.text("#{I18n.t('output_elements.cwe_chart.date')}")
.attr("text-anchor","middle")
yAxisLabel = yAxisGroup.append("text")
.attr("class","label")
.attr("x", 0 - (@series_height/ 2))
.attr("y", 0 - 25)
.text("#{I18n.t('output_elements.cwe_chart.DAM_price')}")
.attr("text-anchor","middle")
.attr("transform", (d) -> "rotate(-90)" )
lineFunction = d3.svg.line()
.x( (d) -> xScale(d.x) )
.y( (d) -> yScale(d.y) )
.interpolate("none")
# Draw lines, using data binding
@svg.selectAll('path.serie')
.data(theData)
.enter()
.append('g')
.attr('id', (d,i) -> 'path_' + i)
.append('path')
.attr("d", (d) -> lineFunction(d.values) )
.attr("stroke", (d) -> d.color )
.attr("stroke-width", 3)
.attr("fill", "none")
markers = for data, i in theData
@svg.select('g#path_' + i).selectAll('circle')
.data(data.values)
.enter()
.append('circle')
.attr(
cx: (d) -> parseInt(xScale(d.x)),
cy: (d) -> parseInt(yScale(d.y)),
r: 5,
fill: data.color,
stroke: 'rgb(255,255,255)',
'stroke-width': 2
)
# Draw 'Indicative' label
@svg.append("text")
.attr("class", "indicative_label")
.text("#{I18n.t('output_elements.storage_chart.indicative')}")
.attr("transform", "translate(#{@width - 80},0) rotate(45)" )
# Create legend
legendGroup = @svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(0,#{@series_height + legend_margin})")
legendItem = legendGroup.append("svg")
# legendItem.selectAll('rect')
# .data(theData)
# .enter()
# .append('rect')
# .attr("x", (d,i) -> i%2 * legend_column_width + 5)
# .attr("y", (d,i) -> Math.floor(i / 2) * cell_height )
# .attr("width", "10")
# .attr("height", "10")
# .attr("fill", (d) -> d.color )
legendItem.selectAll('line')
.data(theData)
.enter()
.append('line')
.attr("x1", (d,i) -> i%2 * legend_column_width )
.attr("y1", (d,i) -> Math.floor(i / 2) * cell_height + 5)
.attr("x2", (d,i) -> i%2 * legend_column_width + 20)
.attr("y2", (d,i) -> Math.floor(i / 2) * cell_height + 5)
.attr("stroke-width", 3)
.attr("stroke", (d) -> d.color)
.attr("fill", "none")
legendItem.selectAll('circle')
.data(theData)
.enter()
.append('circle')
.attr(
cx: (d,i) -> i%2 * legend_column_width + 10,
cy: (d,i) -> Math.floor(i / 2) * cell_height + 5,
r: 5,
fill: (d) -> d.color,
stroke: "rgb(255,255,255)",
'stroke-width': 2
)
legendItem.selectAll('text')
.data(theData)
.enter()
.append('text')
.attr("class", "legend_label")
.attr("x", (d,i) -> i%2 * legend_column_width + 35 )
.attr("y", (d,i) -> Math.floor(i / 2) * cell_height + 10 )
.text((d) -> "#{d.label}" )
refresh: =>
# Define scales and line function
xScale = d3.scale.linear()
.domain([0, @maximum_x])
.range([0, @width])
yScale = d3.scale.linear()
.domain([0, @maximum_y])
.range([@series_height, 0])
lineFunction = d3.svg.line()
.x( (d) -> xScale(d.x) )
.y( (d) -> yScale(d.y) )
.interpolate("basis")
| true | D3.import_export_cwe =
View: class extends D3ChartView
initialize: ->
D3ChartView.prototype.initialize.call(this)
@gquery = gqueries.find_or_create_by_key('installed_capacity_PI:KEY:<KEY>END_PIand_wind')
can_be_shown_as_table: -> false
margins :
top: 20
bottom: 50
left: 50
right: 20
filter_on_y_values = (data, max) =>
result = []
result.push(d) for d in data when d.y <= max
return result
formatDay = (d,i) -> if i <= 13 then i + 8 else ""
draw: =>
# Set maximum x and y values
@maximum_x = 28
@maximum_y = 60
# Prepare chart data
APX_DAM = [{"x": "1", "y": "47.01"}, {"x": "3", "y": "49.14"}, {"x": "5", "y": "50.98"}, {"x": "7", "y": "46.17"}, {"x": "9", "y": "38.06"}, {"x": "11", "y": "47.25"}, {"x": "13", "y": "49.81"}, {"x": "15", "y": "46.60"}, {"x": "17", "y": "45.58"}, {"x": "19", "y": "43.19"}, {"x": "21", "y": "40.68"}, {"x": "23", "y": "43.99"}, {"x": "25", "y": "52.66"}, {"x": "27", "y": "51.36"}]
Belpex_DAM = [{"x": "1", "y": "42.40"}, {"x": "3", "y": "41.21"}, {"x": "5", "y": "49.75"}, {"x": "7", "y": "42.32"}, {"x": "9", "y": "30.34"}, {"x": "11", "y": "46.20"}, {"x": "13", "y": "49.20"}, {"x": "15", "y": "46.36"}, {"x": "17", "y": "44.04"}, {"x": "19", "y": "39.54"}, {"x": "21", "y": "32.24"}, {"x": "23", "y": "34.75"}, {"x": "25", "y": "51.90"}, {"x": "27", "y": "51.36"}]
EPEX_Spot_FR = [{"x": "1", "y": "41.6"}, {"x": "3", "y": "41.21"}, {"x": "5", "y": "48.97"}, {"x": "7", "y": "42.32"}, {"x": "9", "y": "29.98"}, {"x": "11", "y": "44.43"}, {"x": "13", "y": "49.2"}, {"x": "15", "y": "46.36"}, {"x": "17", "y": "41.83"}, {"x": "19", "y": "38.19"}, {"x": "21", "y": "31.63"}, {"x": "23", "y": "33.25"}, {"x": "25", "y": "50.88"}, {"x": "27", "y": "51.36"}]
EPEX_Spot_DE = [{"x": "1", "y": "33.49"}, {"x": "3", "y": "31.13"}, {"x": "5", "y": "28.31"}, {"x": "7", "y": "29.66"}, {"x": "9", "y": "19.59"}, {"x": "11", "y": "41.94"}, {"x": "13", "y": "49.35"}, {"x": "15", "y": "45.69"}, {"x": "17", "y": "40.75"}, {"x": "19", "y": "39.58"}, {"x": "21", "y": "31.87"}, {"x": "23", "y": "24.69"}, {"x": "25", "y": "48.52"}, {"x": "27", "y": "49.51"}]
theData = [{color: "#00BFFF", values: APX_DAM, label: "APX DAM (NL)"}, {color: "#1947A8", values: Belpex_DAM , label: "Belpex DAM (BE)"}, {color: "#F5C400", values: EPEX_Spot_FR, label: "EPEX Spot FR"}, {color: "#DB2C18", values: EPEX_Spot_DE, label: "EPEX Spot DE"}]
# Create SVG convas and set related variables
[@width, @height] = @available_size()
legend_columns = 2
legend_rows = theData.length / legend_columns
legend_column_width = @width/ legend_columns
legend_margin = 50
cell_height = @legend_cell_height
@series_height = @height - legend_margin
@svg = @create_svg_container @width, @height, @margins
# Define scales and create axes
xScale = d3.scale.linear()
.domain([0, @maximum_x])
.range([0, @width])
yScale = d3.scale.linear()
.domain([10, @maximum_y])
.range([@series_height, 0])
xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickFormat(formatDay)
yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickValues([10,20,30,40,50,60])
.tickSize(0)
xAxisGroup = @svg.append("g")
.attr("class", "x_axis")
.attr("transform", "translate(0,#{@series_height})")
.call(xAxis)
yAxisGroup = @svg.append("g")
.attr("class", "y_axis")
.call(yAxis)
xAxisGroup.selectAll('text').attr('transform', 'translate(20,0)')
xAxisLabel = xAxisGroup.append("text")
.attr("class","label")
.attr("x", @width/ 2)
.attr("y", 35)
.text("#{I18n.t('output_elements.cwe_chart.date')}")
.attr("text-anchor","middle")
yAxisLabel = yAxisGroup.append("text")
.attr("class","label")
.attr("x", 0 - (@series_height/ 2))
.attr("y", 0 - 25)
.text("#{I18n.t('output_elements.cwe_chart.DAM_price')}")
.attr("text-anchor","middle")
.attr("transform", (d) -> "rotate(-90)" )
lineFunction = d3.svg.line()
.x( (d) -> xScale(d.x) )
.y( (d) -> yScale(d.y) )
.interpolate("none")
# Draw lines, using data binding
@svg.selectAll('path.serie')
.data(theData)
.enter()
.append('g')
.attr('id', (d,i) -> 'path_' + i)
.append('path')
.attr("d", (d) -> lineFunction(d.values) )
.attr("stroke", (d) -> d.color )
.attr("stroke-width", 3)
.attr("fill", "none")
markers = for data, i in theData
@svg.select('g#path_' + i).selectAll('circle')
.data(data.values)
.enter()
.append('circle')
.attr(
cx: (d) -> parseInt(xScale(d.x)),
cy: (d) -> parseInt(yScale(d.y)),
r: 5,
fill: data.color,
stroke: 'rgb(255,255,255)',
'stroke-width': 2
)
# Draw 'Indicative' label
@svg.append("text")
.attr("class", "indicative_label")
.text("#{I18n.t('output_elements.storage_chart.indicative')}")
.attr("transform", "translate(#{@width - 80},0) rotate(45)" )
# Create legend
legendGroup = @svg.append("g")
.attr("class", "legend")
.attr("transform", "translate(0,#{@series_height + legend_margin})")
legendItem = legendGroup.append("svg")
# legendItem.selectAll('rect')
# .data(theData)
# .enter()
# .append('rect')
# .attr("x", (d,i) -> i%2 * legend_column_width + 5)
# .attr("y", (d,i) -> Math.floor(i / 2) * cell_height )
# .attr("width", "10")
# .attr("height", "10")
# .attr("fill", (d) -> d.color )
legendItem.selectAll('line')
.data(theData)
.enter()
.append('line')
.attr("x1", (d,i) -> i%2 * legend_column_width )
.attr("y1", (d,i) -> Math.floor(i / 2) * cell_height + 5)
.attr("x2", (d,i) -> i%2 * legend_column_width + 20)
.attr("y2", (d,i) -> Math.floor(i / 2) * cell_height + 5)
.attr("stroke-width", 3)
.attr("stroke", (d) -> d.color)
.attr("fill", "none")
legendItem.selectAll('circle')
.data(theData)
.enter()
.append('circle')
.attr(
cx: (d,i) -> i%2 * legend_column_width + 10,
cy: (d,i) -> Math.floor(i / 2) * cell_height + 5,
r: 5,
fill: (d) -> d.color,
stroke: "rgb(255,255,255)",
'stroke-width': 2
)
legendItem.selectAll('text')
.data(theData)
.enter()
.append('text')
.attr("class", "legend_label")
.attr("x", (d,i) -> i%2 * legend_column_width + 35 )
.attr("y", (d,i) -> Math.floor(i / 2) * cell_height + 10 )
.text((d) -> "#{d.label}" )
refresh: =>
# Define scales and line function
xScale = d3.scale.linear()
.domain([0, @maximum_x])
.range([0, @width])
yScale = d3.scale.linear()
.domain([0, @maximum_y])
.range([@series_height, 0])
lineFunction = d3.svg.line()
.x( (d) -> xScale(d.x) )
.y( (d) -> yScale(d.y) )
.interpolate("basis")
|
[
{
"context": "UDY', path: '/case-study/'},\n ]\n\n members:\n yusuke:\n name_ja: '富永 勇亮'\n name_en: 'Yusuke",
"end": 339,
"score": 0.4005526006221771,
"start": 337,
"tag": "NAME",
"value": "us"
},
{
"context": "Y', path: '/case-study/'},\n ]\n\n members:\n yusuke:\n name_ja: '富永 勇亮'\n name_en: 'Yusuke To",
"end": 342,
"score": 0.4565361440181732,
"start": 339,
"tag": "USERNAME",
"value": "uke"
},
{
"context": "y/'},\n ]\n\n members:\n yusuke:\n name_ja: '富永 勇亮'\n name_en: 'Yusuke Tominaga'\n color: '#",
"end": 365,
"score": 0.9984078407287598,
"start": 360,
"tag": "NAME",
"value": "富永 勇亮"
},
{
"context": " yusuke:\n name_ja: '富永 勇亮'\n name_en: 'Yusuke Tominaga'\n color: '#EA62AA'\n\n saqoosha:\n name",
"end": 398,
"score": 0.9996922612190247,
"start": 383,
"tag": "NAME",
"value": "Yusuke Tominaga"
},
{
"context": " color: '#EA62AA'\n\n saqoosha:\n name_ja: 'Saqoosha'\n name_en: ''\n color: '#E50012'\n\n he",
"end": 462,
"score": 0.9992756843566895,
"start": 454,
"tag": "NAME",
"value": "Saqoosha"
},
{
"context": " color: '#E50012'\n\n heri:\n name_ja: '谷口 恭介'\n name_en: 'Kyosuke Taniguchi'\n color: ",
"end": 537,
"score": 0.9764544367790222,
"start": 532,
"tag": "NAME",
"value": "谷口 恭介"
},
{
"context": "\n heri:\n name_ja: '谷口 恭介'\n name_en: 'Kyosuke Taniguchi'\n color: '#FFF100'\n\n sfman:\n name_ja",
"end": 572,
"score": 0.9996880888938904,
"start": 555,
"tag": "NAME",
"value": "Kyosuke Taniguchi"
},
{
"context": " color: '#FFF100'\n\n sfman:\n name_ja: '藤原 愼哉'\n name_en: 'Shinnya Fujiwara'\n color: '",
"end": 630,
"score": 0.9919404983520508,
"start": 625,
"tag": "NAME",
"value": "藤原 愼哉"
},
{
"context": " sfman:\n name_ja: '藤原 愼哉'\n name_en: 'Shinnya Fujiwara'\n color: '#004D75'\n\n seki:\n name_ja:",
"end": 664,
"score": 0.9997066259384155,
"start": 648,
"tag": "NAME",
"value": "Shinnya Fujiwara"
},
{
"context": " color: '#004D75'\n\n seki:\n name_ja: '関 賢一'\n name_en: 'Kenichi Seki'\n color: '#14B",
"end": 720,
"score": 0.9948726892471313,
"start": 716,
"tag": "NAME",
"value": "関 賢一"
},
{
"context": "\n\n seki:\n name_ja: '関 賢一'\n name_en: 'Kenichi Seki'\n color: '#14B6B1'\n\n hige:\n name_ja:",
"end": 750,
"score": 0.999244213104248,
"start": 738,
"tag": "NAME",
"value": "Kenichi Seki"
},
{
"context": " color: '#14B6B1'\n\n hige:\n name_ja: 'イズカワ タカノブ'\n name_en: 'Takanobu Izukawa'\n color: '",
"end": 811,
"score": 0.9792602062225342,
"start": 802,
"tag": "NAME",
"value": "イズカワ タカノブ"
},
{
"context": " hige:\n name_ja: 'イズカワ タカノブ'\n name_en: 'Takanobu Izukawa'\n color: '#000000'\n\n jaguar:\n name_j",
"end": 845,
"score": 0.9994609355926514,
"start": 829,
"tag": "NAME",
"value": "Takanobu Izukawa"
},
{
"context": " color: '#000000'\n\n jaguar:\n name_ja: '高谷 優偉'\n name_en: 'Yuichi Takatani'\n color: '#",
"end": 904,
"score": 0.993043065071106,
"start": 899,
"tag": "NAME",
"value": "高谷 優偉"
},
{
"context": " jaguar:\n name_ja: '高谷 優偉'\n name_en: 'Yuichi Takatani'\n color: '#2DC8F0'\n\n taichi:\n name_j",
"end": 937,
"score": 0.9996559023857117,
"start": 922,
"tag": "NAME",
"value": "Yuichi Takatani"
},
{
"context": " color: '#2DC8F0'\n\n taichi:\n name_ja: '伊藤 太一'\n name_en: 'Taichi Ito'\n color: '#003DA",
"end": 996,
"score": 0.9972276091575623,
"start": 991,
"tag": "NAME",
"value": "伊藤 太一"
},
{
"context": " taichi:\n name_ja: '伊藤 太一'\n name_en: 'Taichi Ito'\n color: '#003DA5'\n\n ibukuro:\n name_",
"end": 1024,
"score": 0.9990576505661011,
"start": 1014,
"tag": "NAME",
"value": "Taichi Ito"
},
{
"context": " color: '#003DA5'\n\n ibukuro:\n name_ja: '衣袋 宏輝'\n name_en: 'Koki Ibukuro'\n color: '#",
"end": 1081,
"score": 0.5839909911155701,
"start": 1080,
"tag": "NAME",
"value": "袋"
},
{
"context": "color: '#003DA5'\n\n ibukuro:\n name_ja: '衣袋 宏輝'\n name_en: 'Koki Ibukuro'\n color: '#FF8",
"end": 1084,
"score": 0.7900287508964539,
"start": 1082,
"tag": "NAME",
"value": "宏輝"
},
{
"context": " ibukuro:\n name_ja: '衣袋 宏輝'\n name_en: 'Koki Ibukuro'\n color: '#FF812C'\n\n minori:\n name_j",
"end": 1114,
"score": 0.9983778595924377,
"start": 1102,
"tag": "NAME",
"value": "Koki Ibukuro"
},
{
"context": " color: '#FF812C'\n\n minori:\n name_ja: 'ながしま みのり'\n name_en: 'Minori Nagashima'\n c",
"end": 1169,
"score": 0.5058457255363464,
"start": 1168,
"tag": "NAME",
"value": "な"
},
{
"context": "minori:\n name_ja: 'ながしま みのり'\n name_en: 'Minori Nagashima'\n color: '#B2203A'\n\n shizuho:\n name_",
"end": 1210,
"score": 0.9984311461448669,
"start": 1194,
"tag": "NAME",
"value": "Minori Nagashima"
},
{
"context": " color: '#B2203A'\n\n shizuho:\n name_ja: '佐藤 志都穂'\n name_en: 'Shizuho Sato'\n color: '#B8A",
"end": 1271,
"score": 0.9781382083892822,
"start": 1265,
"tag": "NAME",
"value": "佐藤 志都穂"
},
{
"context": " shizuho:\n name_ja: '佐藤 志都穂'\n name_en: 'Shizuho Sato'\n color: '#B8A9D6'\n hidden: true\n\n f",
"end": 1301,
"score": 0.9992639422416687,
"start": 1289,
"tag": "NAME",
"value": "Shizuho Sato"
},
{
"context": "\n hidden: true\n\n fukuchi:\n name_ja: '福地 諒'\n name_en: 'Makoto Fukuchi'\n color: '#8",
"end": 1379,
"score": 0.9713442921638489,
"start": 1375,
"tag": "NAME",
"value": "福地 諒"
},
{
"context": " fukuchi:\n name_ja: '福地 諒'\n name_en: 'Makoto Fukuchi'\n color: '#81A98A'\n\n kenta:\n name_ja",
"end": 1411,
"score": 0.9989129900932312,
"start": 1397,
"tag": "NAME",
"value": "Makoto Fukuchi"
},
{
"context": " color: '#81A98A'\n\n kenta:\n name_ja: '渡島 健太'\n name_en: 'Kenta Watashima'\n color: '#",
"end": 1469,
"score": 0.9780198931694031,
"start": 1464,
"tag": "NAME",
"value": "渡島 健太"
},
{
"context": " kenta:\n name_ja: '渡島 健太'\n name_en: 'Kenta Watashima'\n color: '#8F9294'\n\n # dice:\n # name",
"end": 1502,
"score": 0.9971356391906738,
"start": 1487,
"tag": "NAME",
"value": "Kenta Watashima"
},
{
"context": " color: '#8F9294'\n\n # dice:\n # name_ja: '油木田 大祐'\n # name_en: 'Daisuke Yukita'\n # color:",
"end": 1564,
"score": 0.9850777387619019,
"start": 1558,
"tag": "NAME",
"value": "油木田 大祐"
},
{
"context": "dice:\n # name_ja: '油木田 大祐'\n # name_en: 'Daisuke Yukita'\n # color: '#E6E3C5'\n\n masa:\n name_j",
"end": 1598,
"score": 0.9992198348045349,
"start": 1584,
"tag": "NAME",
"value": "Daisuke Yukita"
},
{
"context": " # color: '#E6E3C5'\n\n masa:\n name_ja: '川村 真司'\n name_en: 'Masashi Kawamura'\n color",
"end": 1654,
"score": 0.6906868815422058,
"start": 1653,
"tag": "NAME",
"value": "村"
},
{
"context": " color: '#E6E3C5'\n\n masa:\n name_ja: '川村 真司'\n name_en: 'Masashi Kawamura'\n color: '",
"end": 1657,
"score": 0.8170030117034912,
"start": 1655,
"tag": "NAME",
"value": "真司"
},
{
"context": "\n masa:\n name_ja: '川村 真司'\n name_en: 'Masashi Kawamura'\n color: '#837653'\n\n sachie:\n name_j",
"end": 1691,
"score": 0.998585045337677,
"start": 1675,
"tag": "NAME",
"value": "Masashi Kawamura"
},
{
"context": " color: '#837653'\n\n sachie:\n name_ja: '相原 幸絵'\n name_en: 'Sachie Aihara'\n color: '#25",
"end": 1750,
"score": 0.9765623211860657,
"start": 1745,
"tag": "NAME",
"value": "相原 幸絵"
},
{
"context": " sachie:\n name_ja: '相原 幸絵'\n name_en: 'Sachie Aihara'\n color: '#253956'\n\n onorika:\n name_",
"end": 1781,
"score": 0.9989469647407532,
"start": 1768,
"tag": "NAME",
"value": "Sachie Aihara"
},
{
"context": "color: '#253956'\n\n onorika:\n name_ja: '小野 里夏'\n name_en: 'Rika Ono'\n color: '#CADCE2'",
"end": 1841,
"score": 0.6131256222724915,
"start": 1839,
"tag": "NAME",
"value": "里夏"
},
{
"context": " onorika:\n name_ja: '小野 里夏'\n name_en: 'Rika Ono'\n color: '#CADCE2'\n\n keiko:\n name_ja",
"end": 1867,
"score": 0.9985476732254028,
"start": 1859,
"tag": "NAME",
"value": "Rika Ono"
},
{
"context": " color: '#CADCE2'\n\n keiko:\n name_ja: '織田 慶子'\n name_en: 'Keiko Oda'\n color: '#563D2A",
"end": 1925,
"score": 0.9618894457817078,
"start": 1920,
"tag": "NAME",
"value": "織田 慶子"
},
{
"context": " keiko:\n name_ja: '織田 慶子'\n name_en: 'Keiko Oda'\n color: '#563D2A'\n\n kida:\n name_ja:",
"end": 1952,
"score": 0.9976862668991089,
"start": 1943,
"tag": "NAME",
"value": "Keiko Oda"
},
{
"context": " color: '#563D2A'\n\n kida:\n name_ja: '貴田 達也'\n name_en: 'Tatsuya Kida'\n color: '#9dc",
"end": 2009,
"score": 0.9526309967041016,
"start": 2004,
"tag": "NAME",
"value": "貴田 達也"
},
{
"context": "\n kida:\n name_ja: '貴田 達也'\n name_en: 'Tatsuya Kida'\n color: '#9dc838'",
"end": 2039,
"score": 0.9946492314338684,
"start": 2027,
"tag": "NAME",
"value": "Tatsuya Kida"
}
] | src/data.coffee | dot-by-dot-inc/dotby.jp-2015 | 42 | module.exports =
menu: [
{name: 'TOP', path: '/'},
{name: 'ABOUT', path: '/about/'},
{name: 'MEMBERS', path: '/members/'},
{name: 'WORK', path: '/category/work/'},
{name: 'NEWS', path: '/category/news/'},
{name: 'AWARDS', path: '/awards/'},
{name: 'CASE STUDY', path: '/case-study/'},
]
members:
yusuke:
name_ja: '富永 勇亮'
name_en: 'Yusuke Tominaga'
color: '#EA62AA'
saqoosha:
name_ja: 'Saqoosha'
name_en: ''
color: '#E50012'
heri:
name_ja: '谷口 恭介'
name_en: 'Kyosuke Taniguchi'
color: '#FFF100'
sfman:
name_ja: '藤原 愼哉'
name_en: 'Shinnya Fujiwara'
color: '#004D75'
seki:
name_ja: '関 賢一'
name_en: 'Kenichi Seki'
color: '#14B6B1'
hige:
name_ja: 'イズカワ タカノブ'
name_en: 'Takanobu Izukawa'
color: '#000000'
jaguar:
name_ja: '高谷 優偉'
name_en: 'Yuichi Takatani'
color: '#2DC8F0'
taichi:
name_ja: '伊藤 太一'
name_en: 'Taichi Ito'
color: '#003DA5'
ibukuro:
name_ja: '衣袋 宏輝'
name_en: 'Koki Ibukuro'
color: '#FF812C'
minori:
name_ja: 'ながしま みのり'
name_en: 'Minori Nagashima'
color: '#B2203A'
shizuho:
name_ja: '佐藤 志都穂'
name_en: 'Shizuho Sato'
color: '#B8A9D6'
hidden: true
fukuchi:
name_ja: '福地 諒'
name_en: 'Makoto Fukuchi'
color: '#81A98A'
kenta:
name_ja: '渡島 健太'
name_en: 'Kenta Watashima'
color: '#8F9294'
# dice:
# name_ja: '油木田 大祐'
# name_en: 'Daisuke Yukita'
# color: '#E6E3C5'
masa:
name_ja: '川村 真司'
name_en: 'Masashi Kawamura'
color: '#837653'
sachie:
name_ja: '相原 幸絵'
name_en: 'Sachie Aihara'
color: '#253956'
onorika:
name_ja: '小野 里夏'
name_en: 'Rika Ono'
color: '#CADCE2'
keiko:
name_ja: '織田 慶子'
name_en: 'Keiko Oda'
color: '#563D2A'
kida:
name_ja: '貴田 達也'
name_en: 'Tatsuya Kida'
color: '#9dc838' | 186261 | module.exports =
menu: [
{name: 'TOP', path: '/'},
{name: 'ABOUT', path: '/about/'},
{name: 'MEMBERS', path: '/members/'},
{name: 'WORK', path: '/category/work/'},
{name: 'NEWS', path: '/category/news/'},
{name: 'AWARDS', path: '/awards/'},
{name: 'CASE STUDY', path: '/case-study/'},
]
members:
y<NAME>uke:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#EA62AA'
saqoosha:
name_ja: '<NAME>'
name_en: ''
color: '#E50012'
heri:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#FFF100'
sfman:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#004D75'
seki:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#14B6B1'
hige:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#000000'
jaguar:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#2DC8F0'
taichi:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#003DA5'
ibukuro:
name_ja: '衣<NAME> <NAME>'
name_en: '<NAME>'
color: '#FF812C'
minori:
name_ja: '<NAME>がしま みのり'
name_en: '<NAME>'
color: '#B2203A'
shizuho:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#B8A9D6'
hidden: true
fukuchi:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#81A98A'
kenta:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#8F9294'
# dice:
# name_ja: '<NAME>'
# name_en: '<NAME>'
# color: '#E6E3C5'
masa:
name_ja: '川<NAME> <NAME>'
name_en: '<NAME>'
color: '#837653'
sachie:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#253956'
onorika:
name_ja: '小野 <NAME>'
name_en: '<NAME>'
color: '#CADCE2'
keiko:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#563D2A'
kida:
name_ja: '<NAME>'
name_en: '<NAME>'
color: '#9dc838' | true | module.exports =
menu: [
{name: 'TOP', path: '/'},
{name: 'ABOUT', path: '/about/'},
{name: 'MEMBERS', path: '/members/'},
{name: 'WORK', path: '/category/work/'},
{name: 'NEWS', path: '/category/news/'},
{name: 'AWARDS', path: '/awards/'},
{name: 'CASE STUDY', path: '/case-study/'},
]
members:
yPI:NAME:<NAME>END_PIuke:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#EA62AA'
saqoosha:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: ''
color: '#E50012'
heri:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#FFF100'
sfman:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#004D75'
seki:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#14B6B1'
hige:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#000000'
jaguar:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#2DC8F0'
taichi:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#003DA5'
ibukuro:
name_ja: '衣PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#FF812C'
minori:
name_ja: 'PI:NAME:<NAME>END_PIがしま みのり'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#B2203A'
shizuho:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#B8A9D6'
hidden: true
fukuchi:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#81A98A'
kenta:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#8F9294'
# dice:
# name_ja: 'PI:NAME:<NAME>END_PI'
# name_en: 'PI:NAME:<NAME>END_PI'
# color: '#E6E3C5'
masa:
name_ja: '川PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#837653'
sachie:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#253956'
onorika:
name_ja: '小野 PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#CADCE2'
keiko:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#563D2A'
kida:
name_ja: 'PI:NAME:<NAME>END_PI'
name_en: 'PI:NAME:<NAME>END_PI'
color: '#9dc838' |
[
{
"context": " enum: [\n {value: 'a', description: 'Alice'},\n {value: 'b', description: 'Bob'}",
"end": 3417,
"score": 0.9997279047966003,
"start": 3412,
"tag": "NAME",
"value": "Alice"
},
{
"context": "Alice'},\n {value: 'b', description: 'Bob'}\n ]\n testZero:\n n",
"end": 3465,
"score": 0.9997443556785583,
"start": 3462,
"tag": "NAME",
"value": "Bob"
}
] | spec/settings-panel-spec.coffee | Aerijo/settings-view | 316 | SettingsPanel = require '../lib/settings-panel'
_ = require 'underscore-plus'
describe "SettingsPanel", ->
settingsPanel = null
describe "sorted settings", ->
beforeEach ->
config =
type: 'object'
properties:
bar:
title: 'Bar'
description: 'The bar setting'
type: 'boolean'
default: true
haz:
title: 'Haz'
description: 'The haz setting'
type: 'string'
default: 'haz'
zing:
title: 'Zing'
description: 'The zing setting'
type: 'string'
default: 'zing'
order: 1
zang:
title: 'Zang'
description: 'The baz setting'
type: 'string'
default: 'zang'
order: 100
enum:
title: 'An enum'
type: 'string'
default: 'one'
enum: [
{value: 'one', description: 'One'}
'Two'
]
radio:
title: 'An enum with radio buttons'
radio: true
type: 'string'
default: 'Two'
enum: [
{value: 'one', description: 'One'}
'Two'
]
atom.config.setSchema("foo", config)
atom.config.setDefaults("foo", gong: 'gong')
expect(_.size(atom.config.get('foo'))).toBe 7
settingsPanel = new SettingsPanel({namespace: "foo", includeTitle: false})
it "sorts settings by order and then alphabetically by the key", ->
settings = atom.config.get('foo')
expect(_.size(settings)).toBe 7
sortedSettings = settingsPanel.sortSettings("foo", settings)
expect(sortedSettings[0]).toBe 'zing'
expect(sortedSettings[1]).toBe 'zang'
expect(sortedSettings[2]).toBe 'bar'
expect(sortedSettings[3]).toBe 'enum'
expect(sortedSettings[4]).toBe 'gong'
expect(sortedSettings[5]).toBe 'haz'
expect(sortedSettings[6]).toBe 'radio'
it "gracefully deals with a null settings object", ->
sortedSettings = settingsPanel.sortSettings("foo", null)
expect(sortedSettings).not.toBeNull
expect(_.size(sortedSettings)).toBe 0
it "presents enum options with their descriptions", ->
select = settingsPanel.element.querySelector('#foo\\.enum')
pairs = ([opt.value, opt.innerText] for opt in select.children)
expect(pairs).toEqual([['one', 'One'], ['Two', 'Two']])
it "presents radio options with their descriptions", ->
radio = settingsPanel.element.querySelector('#foo\\.radio')
options = for label in radio.querySelectorAll 'label'
button = label.querySelector('input[type=radio][name="foo.radio"]')
[button.id, button.value, label.innerText]
expect(options).toEqual([['foo.radio[one]', 'one', 'One'], ['foo.radio[Two]', 'Two', 'Two']])
describe 'default settings', ->
beforeEach ->
config =
type: 'object'
properties:
haz:
name: 'haz'
title: 'Haz'
description: 'The haz setting'
type: 'string'
default: 'haz'
qux:
name: 'qux'
title: 'Qux'
description: 'The qux setting'
type: 'string'
default: 'a'
enum: [
{value: 'a', description: 'Alice'},
{value: 'b', description: 'Bob'}
]
testZero:
name: 'testZero'
title: 'Test Zero'
description: 'Setting for testing zero as a default'
type: 'integer'
default: 0
radio:
title: 'An enum with radio buttons'
radio: true
type: 'string'
default: 'Two'
enum: [
{value: 'one', description: 'One'}
'Two'
'Three'
]
atom.config.setSchema("foo", config)
atom.config.setDefaults("foo", gong: 'gong')
expect(_.size(atom.config.get('foo'))).toBe 5
settingsPanel = new SettingsPanel({namespace: "foo", includeTitle: false})
it 'ensures default stays default', ->
expect(settingsPanel.getDefault('foo.haz')).toBe 'haz'
expect(settingsPanel.isDefault('foo.haz')).toBe true
settingsPanel.set('foo.haz', 'haz')
expect(settingsPanel.isDefault('foo.haz')).toBe true
it 'can be overwritten', ->
expect(settingsPanel.getDefault('foo.haz')).toBe 'haz'
expect(settingsPanel.isDefault('foo.haz')).toBe true
settingsPanel.set('foo.haz', 'newhaz')
expect(settingsPanel.isDefault('foo.haz')).toBe false
expect(atom.config.get('foo.haz')).toBe 'newhaz'
it 'has a tooltip showing the default value', ->
hazEditor = settingsPanel.element.querySelector('[id="foo.haz"]')
tooltips = atom.tooltips.findTooltips(hazEditor)
expect(tooltips).toHaveLength 1
title = tooltips[0].options.title
expect(title).toBe "Default: haz"
it 'has a tooltip showing the description of the default value', ->
quxEditor = settingsPanel.element.querySelector('[id="foo.qux"]')
tooltips = atom.tooltips.findTooltips(quxEditor)
expect(tooltips).toHaveLength 1
title = tooltips[0].options.title
expect(title).toBe "Default: Alice"
# Regression test for #783
it 'allows 0 to be a default', ->
zeroEditor = settingsPanel.element.querySelector('[id="foo.testZero"]')
expect(zeroEditor.getModel().getText()).toBe('')
expect(zeroEditor.getModel().getPlaceholderText()).toBe('Default: 0')
expect(settingsPanel.getDefault('foo.testZero')).toBe 0
expect(settingsPanel.isDefault('foo.testZero')).toBe true
settingsPanel.set('foo.testZero', 15)
expect(settingsPanel.isDefault('foo.testZero')).toBe false
settingsPanel.set('foo.testZero', 0)
expect(settingsPanel.isDefault('foo.testZero')).toBe true
it "selects the default choice for radio options", ->
expect(settingsPanel.getDefault 'foo.radio').toBe 'Two'
settingsPanel.set 'foo.radio', 'Two'
expect(settingsPanel.element.querySelector '#foo\\.radio\\[Two\\]').toBeChecked()
describe 'scoped settings', ->
beforeEach ->
schema =
scopes:
'.source.python':
default: 4
atom.config.setScopedDefaultsFromSchema('editor.tabLength', schema)
expect(atom.config.get('editor.tabLength')).toBe(2)
it 'displays the scoped default', ->
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.python'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 4')
it 'allows the scoped setting to be changed to its normal default if the unscoped value is different', ->
atom.config.set('editor.tabLength', 8)
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.js'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 8')
# This is the unscoped default, but it differs from the current unscoped value
settingsPanel.set('editor.tabLength', 2)
expect(tabLengthEditor.getModel().getText()).toBe('2')
expect(atom.config.get('editor.tabLength', {scope: ['source.js']})).toBe(2)
it 'allows the scoped setting to be changed to the unscoped default if it is different', ->
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.python'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 4')
# This is the unscoped default, but it differs from the scoped default
settingsPanel.set('editor.tabLength', 2)
expect(tabLengthEditor.getModel().getText()).toBe('2')
expect(atom.config.get('editor.tabLength', {scope: ['source.python']})).toBe(2)
describe 'grouped settings', ->
beforeEach ->
config =
type: 'object'
properties:
barGroup:
type: 'object'
title: 'Bar group'
description: 'description of bar group'
properties:
bar:
title: 'Bar'
description: 'The bar setting'
type: 'boolean'
default: false
bazGroup:
type: 'object'
collapsed: true
properties:
baz:
title: 'Baz'
description: 'The baz setting'
type: 'boolean'
default: false
zing:
type: 'string'
default: ''
atom.config.setSchema('foo', config)
expect(_.size(atom.config.get('foo'))).toBe 3
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false})
it 'ensures that only grouped settings have a group title', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section .sub-section-heading').textContent).toBe 'Bar group'
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-body')).toHaveLength 1
subsectionBody = controlGroups[0].querySelector('.sub-section .sub-section-body')
expect(subsectionBody.querySelectorAll('.control-group')).toHaveLength 1
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').textContent).toBe 'Baz Group'
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-body')).toHaveLength 1
subsectionBody = controlGroups[1].querySelector('.sub-section .sub-section-body')
expect(subsectionBody.querySelectorAll('.control-group')).toHaveLength 1
expect(controlGroups[2].querySelectorAll('.sub-section')).toHaveLength 0
expect(controlGroups[2].querySelectorAll('.sub-section-heading')).toHaveLength 0
it 'ensures grouped settings are collapsable', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
# Bar group
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section .sub-section-heading').classList.contains('has-items')).toBe true
# Baz Group
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').classList.contains('has-items')).toBe true
# Should be already collapsed
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').parentElement.classList.contains('collapsed')).toBe true
it 'ensures grouped settings can have a description', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
expect(controlGroups[0].querySelectorAll('.sub-section > .setting-description')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section > .setting-description').textContent).toBe 'description of bar group'
describe 'settings validation', ->
beforeEach ->
config =
type: 'object'
properties:
minMax:
name: 'minMax'
title: 'Min max'
description: 'The minMax setting'
type: 'integer'
default: 10
minimum: 1
maximum: 100
commaValueArray:
name: 'commaValueArray'
title: 'Comma value in array'
description: 'An array with a comma value'
type: 'array'
default: []
atom.config.setSchema('foo', config)
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false})
it 'prevents setting a value below the minimum', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('0')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '1'
minMaxEditor.getModel().setText('-5')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '1'
it 'prevents setting a value above the maximum', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('1000')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '100'
minMaxEditor.getModel().setText('10000')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '100'
it 'prevents setting a value that cannot be coerced to the correct type', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('"abcde"')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '' # aka default
minMaxEditor.getModel().setText('15')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
minMaxEditor.getModel().setText('"abcde"')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
it 'allows setting a valid scoped value', ->
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false, scopeName: 'source.js'})
minMaxEditor = settingsPanel.element.querySelector('atom-text-editor')
minMaxEditor.getModel().setText('15')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
describe 'commaValueArray', ->
it 'comma in value is escaped', ->
commaValueArrayEditor = settingsPanel.element.querySelector('[id="foo.commaValueArray"]')
commaValueArrayEditor.getModel().setText('1, \\,, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get("foo.commaValueArray")).toEqual ['1', ',', '2']
commaValueArrayEditor.getModel().setText('1\\, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual ['1, 2']
commaValueArrayEditor.getModel().setText('1\\,')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual ['1,']
commaValueArrayEditor.getModel().setText('\\, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual [', 2']
it 'renders an escaped comma', ->
commaValueArrayEditor = settingsPanel.element.querySelector('[id="foo.commaValueArray"]')
atom.config.set('foo.commaValueArray', ['3', ',', '4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3, \\,, 4'
atom.config.set('foo.commaValueArray', ['3, 4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3\\, 4'
atom.config.set('foo.commaValueArray', ['3,'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3\\,'
atom.config.set('foo.commaValueArray', [', 4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '\\, 4'
| 82411 | SettingsPanel = require '../lib/settings-panel'
_ = require 'underscore-plus'
describe "SettingsPanel", ->
settingsPanel = null
describe "sorted settings", ->
beforeEach ->
config =
type: 'object'
properties:
bar:
title: 'Bar'
description: 'The bar setting'
type: 'boolean'
default: true
haz:
title: 'Haz'
description: 'The haz setting'
type: 'string'
default: 'haz'
zing:
title: 'Zing'
description: 'The zing setting'
type: 'string'
default: 'zing'
order: 1
zang:
title: 'Zang'
description: 'The baz setting'
type: 'string'
default: 'zang'
order: 100
enum:
title: 'An enum'
type: 'string'
default: 'one'
enum: [
{value: 'one', description: 'One'}
'Two'
]
radio:
title: 'An enum with radio buttons'
radio: true
type: 'string'
default: 'Two'
enum: [
{value: 'one', description: 'One'}
'Two'
]
atom.config.setSchema("foo", config)
atom.config.setDefaults("foo", gong: 'gong')
expect(_.size(atom.config.get('foo'))).toBe 7
settingsPanel = new SettingsPanel({namespace: "foo", includeTitle: false})
it "sorts settings by order and then alphabetically by the key", ->
settings = atom.config.get('foo')
expect(_.size(settings)).toBe 7
sortedSettings = settingsPanel.sortSettings("foo", settings)
expect(sortedSettings[0]).toBe 'zing'
expect(sortedSettings[1]).toBe 'zang'
expect(sortedSettings[2]).toBe 'bar'
expect(sortedSettings[3]).toBe 'enum'
expect(sortedSettings[4]).toBe 'gong'
expect(sortedSettings[5]).toBe 'haz'
expect(sortedSettings[6]).toBe 'radio'
it "gracefully deals with a null settings object", ->
sortedSettings = settingsPanel.sortSettings("foo", null)
expect(sortedSettings).not.toBeNull
expect(_.size(sortedSettings)).toBe 0
it "presents enum options with their descriptions", ->
select = settingsPanel.element.querySelector('#foo\\.enum')
pairs = ([opt.value, opt.innerText] for opt in select.children)
expect(pairs).toEqual([['one', 'One'], ['Two', 'Two']])
it "presents radio options with their descriptions", ->
radio = settingsPanel.element.querySelector('#foo\\.radio')
options = for label in radio.querySelectorAll 'label'
button = label.querySelector('input[type=radio][name="foo.radio"]')
[button.id, button.value, label.innerText]
expect(options).toEqual([['foo.radio[one]', 'one', 'One'], ['foo.radio[Two]', 'Two', 'Two']])
describe 'default settings', ->
beforeEach ->
config =
type: 'object'
properties:
haz:
name: 'haz'
title: 'Haz'
description: 'The haz setting'
type: 'string'
default: 'haz'
qux:
name: 'qux'
title: 'Qux'
description: 'The qux setting'
type: 'string'
default: 'a'
enum: [
{value: 'a', description: '<NAME>'},
{value: 'b', description: '<NAME>'}
]
testZero:
name: 'testZero'
title: 'Test Zero'
description: 'Setting for testing zero as a default'
type: 'integer'
default: 0
radio:
title: 'An enum with radio buttons'
radio: true
type: 'string'
default: 'Two'
enum: [
{value: 'one', description: 'One'}
'Two'
'Three'
]
atom.config.setSchema("foo", config)
atom.config.setDefaults("foo", gong: 'gong')
expect(_.size(atom.config.get('foo'))).toBe 5
settingsPanel = new SettingsPanel({namespace: "foo", includeTitle: false})
it 'ensures default stays default', ->
expect(settingsPanel.getDefault('foo.haz')).toBe 'haz'
expect(settingsPanel.isDefault('foo.haz')).toBe true
settingsPanel.set('foo.haz', 'haz')
expect(settingsPanel.isDefault('foo.haz')).toBe true
it 'can be overwritten', ->
expect(settingsPanel.getDefault('foo.haz')).toBe 'haz'
expect(settingsPanel.isDefault('foo.haz')).toBe true
settingsPanel.set('foo.haz', 'newhaz')
expect(settingsPanel.isDefault('foo.haz')).toBe false
expect(atom.config.get('foo.haz')).toBe 'newhaz'
it 'has a tooltip showing the default value', ->
hazEditor = settingsPanel.element.querySelector('[id="foo.haz"]')
tooltips = atom.tooltips.findTooltips(hazEditor)
expect(tooltips).toHaveLength 1
title = tooltips[0].options.title
expect(title).toBe "Default: haz"
it 'has a tooltip showing the description of the default value', ->
quxEditor = settingsPanel.element.querySelector('[id="foo.qux"]')
tooltips = atom.tooltips.findTooltips(quxEditor)
expect(tooltips).toHaveLength 1
title = tooltips[0].options.title
expect(title).toBe "Default: Alice"
# Regression test for #783
it 'allows 0 to be a default', ->
zeroEditor = settingsPanel.element.querySelector('[id="foo.testZero"]')
expect(zeroEditor.getModel().getText()).toBe('')
expect(zeroEditor.getModel().getPlaceholderText()).toBe('Default: 0')
expect(settingsPanel.getDefault('foo.testZero')).toBe 0
expect(settingsPanel.isDefault('foo.testZero')).toBe true
settingsPanel.set('foo.testZero', 15)
expect(settingsPanel.isDefault('foo.testZero')).toBe false
settingsPanel.set('foo.testZero', 0)
expect(settingsPanel.isDefault('foo.testZero')).toBe true
it "selects the default choice for radio options", ->
expect(settingsPanel.getDefault 'foo.radio').toBe 'Two'
settingsPanel.set 'foo.radio', 'Two'
expect(settingsPanel.element.querySelector '#foo\\.radio\\[Two\\]').toBeChecked()
describe 'scoped settings', ->
beforeEach ->
schema =
scopes:
'.source.python':
default: 4
atom.config.setScopedDefaultsFromSchema('editor.tabLength', schema)
expect(atom.config.get('editor.tabLength')).toBe(2)
it 'displays the scoped default', ->
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.python'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 4')
it 'allows the scoped setting to be changed to its normal default if the unscoped value is different', ->
atom.config.set('editor.tabLength', 8)
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.js'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 8')
# This is the unscoped default, but it differs from the current unscoped value
settingsPanel.set('editor.tabLength', 2)
expect(tabLengthEditor.getModel().getText()).toBe('2')
expect(atom.config.get('editor.tabLength', {scope: ['source.js']})).toBe(2)
it 'allows the scoped setting to be changed to the unscoped default if it is different', ->
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.python'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 4')
# This is the unscoped default, but it differs from the scoped default
settingsPanel.set('editor.tabLength', 2)
expect(tabLengthEditor.getModel().getText()).toBe('2')
expect(atom.config.get('editor.tabLength', {scope: ['source.python']})).toBe(2)
describe 'grouped settings', ->
beforeEach ->
config =
type: 'object'
properties:
barGroup:
type: 'object'
title: 'Bar group'
description: 'description of bar group'
properties:
bar:
title: 'Bar'
description: 'The bar setting'
type: 'boolean'
default: false
bazGroup:
type: 'object'
collapsed: true
properties:
baz:
title: 'Baz'
description: 'The baz setting'
type: 'boolean'
default: false
zing:
type: 'string'
default: ''
atom.config.setSchema('foo', config)
expect(_.size(atom.config.get('foo'))).toBe 3
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false})
it 'ensures that only grouped settings have a group title', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section .sub-section-heading').textContent).toBe 'Bar group'
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-body')).toHaveLength 1
subsectionBody = controlGroups[0].querySelector('.sub-section .sub-section-body')
expect(subsectionBody.querySelectorAll('.control-group')).toHaveLength 1
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').textContent).toBe 'Baz Group'
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-body')).toHaveLength 1
subsectionBody = controlGroups[1].querySelector('.sub-section .sub-section-body')
expect(subsectionBody.querySelectorAll('.control-group')).toHaveLength 1
expect(controlGroups[2].querySelectorAll('.sub-section')).toHaveLength 0
expect(controlGroups[2].querySelectorAll('.sub-section-heading')).toHaveLength 0
it 'ensures grouped settings are collapsable', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
# Bar group
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section .sub-section-heading').classList.contains('has-items')).toBe true
# Baz Group
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').classList.contains('has-items')).toBe true
# Should be already collapsed
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').parentElement.classList.contains('collapsed')).toBe true
it 'ensures grouped settings can have a description', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
expect(controlGroups[0].querySelectorAll('.sub-section > .setting-description')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section > .setting-description').textContent).toBe 'description of bar group'
describe 'settings validation', ->
beforeEach ->
config =
type: 'object'
properties:
minMax:
name: 'minMax'
title: 'Min max'
description: 'The minMax setting'
type: 'integer'
default: 10
minimum: 1
maximum: 100
commaValueArray:
name: 'commaValueArray'
title: 'Comma value in array'
description: 'An array with a comma value'
type: 'array'
default: []
atom.config.setSchema('foo', config)
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false})
it 'prevents setting a value below the minimum', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('0')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '1'
minMaxEditor.getModel().setText('-5')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '1'
it 'prevents setting a value above the maximum', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('1000')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '100'
minMaxEditor.getModel().setText('10000')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '100'
it 'prevents setting a value that cannot be coerced to the correct type', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('"abcde"')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '' # aka default
minMaxEditor.getModel().setText('15')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
minMaxEditor.getModel().setText('"abcde"')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
it 'allows setting a valid scoped value', ->
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false, scopeName: 'source.js'})
minMaxEditor = settingsPanel.element.querySelector('atom-text-editor')
minMaxEditor.getModel().setText('15')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
describe 'commaValueArray', ->
it 'comma in value is escaped', ->
commaValueArrayEditor = settingsPanel.element.querySelector('[id="foo.commaValueArray"]')
commaValueArrayEditor.getModel().setText('1, \\,, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get("foo.commaValueArray")).toEqual ['1', ',', '2']
commaValueArrayEditor.getModel().setText('1\\, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual ['1, 2']
commaValueArrayEditor.getModel().setText('1\\,')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual ['1,']
commaValueArrayEditor.getModel().setText('\\, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual [', 2']
it 'renders an escaped comma', ->
commaValueArrayEditor = settingsPanel.element.querySelector('[id="foo.commaValueArray"]')
atom.config.set('foo.commaValueArray', ['3', ',', '4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3, \\,, 4'
atom.config.set('foo.commaValueArray', ['3, 4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3\\, 4'
atom.config.set('foo.commaValueArray', ['3,'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3\\,'
atom.config.set('foo.commaValueArray', [', 4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '\\, 4'
| true | SettingsPanel = require '../lib/settings-panel'
_ = require 'underscore-plus'
describe "SettingsPanel", ->
settingsPanel = null
describe "sorted settings", ->
beforeEach ->
config =
type: 'object'
properties:
bar:
title: 'Bar'
description: 'The bar setting'
type: 'boolean'
default: true
haz:
title: 'Haz'
description: 'The haz setting'
type: 'string'
default: 'haz'
zing:
title: 'Zing'
description: 'The zing setting'
type: 'string'
default: 'zing'
order: 1
zang:
title: 'Zang'
description: 'The baz setting'
type: 'string'
default: 'zang'
order: 100
enum:
title: 'An enum'
type: 'string'
default: 'one'
enum: [
{value: 'one', description: 'One'}
'Two'
]
radio:
title: 'An enum with radio buttons'
radio: true
type: 'string'
default: 'Two'
enum: [
{value: 'one', description: 'One'}
'Two'
]
atom.config.setSchema("foo", config)
atom.config.setDefaults("foo", gong: 'gong')
expect(_.size(atom.config.get('foo'))).toBe 7
settingsPanel = new SettingsPanel({namespace: "foo", includeTitle: false})
it "sorts settings by order and then alphabetically by the key", ->
settings = atom.config.get('foo')
expect(_.size(settings)).toBe 7
sortedSettings = settingsPanel.sortSettings("foo", settings)
expect(sortedSettings[0]).toBe 'zing'
expect(sortedSettings[1]).toBe 'zang'
expect(sortedSettings[2]).toBe 'bar'
expect(sortedSettings[3]).toBe 'enum'
expect(sortedSettings[4]).toBe 'gong'
expect(sortedSettings[5]).toBe 'haz'
expect(sortedSettings[6]).toBe 'radio'
it "gracefully deals with a null settings object", ->
sortedSettings = settingsPanel.sortSettings("foo", null)
expect(sortedSettings).not.toBeNull
expect(_.size(sortedSettings)).toBe 0
it "presents enum options with their descriptions", ->
select = settingsPanel.element.querySelector('#foo\\.enum')
pairs = ([opt.value, opt.innerText] for opt in select.children)
expect(pairs).toEqual([['one', 'One'], ['Two', 'Two']])
it "presents radio options with their descriptions", ->
radio = settingsPanel.element.querySelector('#foo\\.radio')
options = for label in radio.querySelectorAll 'label'
button = label.querySelector('input[type=radio][name="foo.radio"]')
[button.id, button.value, label.innerText]
expect(options).toEqual([['foo.radio[one]', 'one', 'One'], ['foo.radio[Two]', 'Two', 'Two']])
describe 'default settings', ->
beforeEach ->
config =
type: 'object'
properties:
haz:
name: 'haz'
title: 'Haz'
description: 'The haz setting'
type: 'string'
default: 'haz'
qux:
name: 'qux'
title: 'Qux'
description: 'The qux setting'
type: 'string'
default: 'a'
enum: [
{value: 'a', description: 'PI:NAME:<NAME>END_PI'},
{value: 'b', description: 'PI:NAME:<NAME>END_PI'}
]
testZero:
name: 'testZero'
title: 'Test Zero'
description: 'Setting for testing zero as a default'
type: 'integer'
default: 0
radio:
title: 'An enum with radio buttons'
radio: true
type: 'string'
default: 'Two'
enum: [
{value: 'one', description: 'One'}
'Two'
'Three'
]
atom.config.setSchema("foo", config)
atom.config.setDefaults("foo", gong: 'gong')
expect(_.size(atom.config.get('foo'))).toBe 5
settingsPanel = new SettingsPanel({namespace: "foo", includeTitle: false})
it 'ensures default stays default', ->
expect(settingsPanel.getDefault('foo.haz')).toBe 'haz'
expect(settingsPanel.isDefault('foo.haz')).toBe true
settingsPanel.set('foo.haz', 'haz')
expect(settingsPanel.isDefault('foo.haz')).toBe true
it 'can be overwritten', ->
expect(settingsPanel.getDefault('foo.haz')).toBe 'haz'
expect(settingsPanel.isDefault('foo.haz')).toBe true
settingsPanel.set('foo.haz', 'newhaz')
expect(settingsPanel.isDefault('foo.haz')).toBe false
expect(atom.config.get('foo.haz')).toBe 'newhaz'
it 'has a tooltip showing the default value', ->
hazEditor = settingsPanel.element.querySelector('[id="foo.haz"]')
tooltips = atom.tooltips.findTooltips(hazEditor)
expect(tooltips).toHaveLength 1
title = tooltips[0].options.title
expect(title).toBe "Default: haz"
it 'has a tooltip showing the description of the default value', ->
quxEditor = settingsPanel.element.querySelector('[id="foo.qux"]')
tooltips = atom.tooltips.findTooltips(quxEditor)
expect(tooltips).toHaveLength 1
title = tooltips[0].options.title
expect(title).toBe "Default: Alice"
# Regression test for #783
it 'allows 0 to be a default', ->
zeroEditor = settingsPanel.element.querySelector('[id="foo.testZero"]')
expect(zeroEditor.getModel().getText()).toBe('')
expect(zeroEditor.getModel().getPlaceholderText()).toBe('Default: 0')
expect(settingsPanel.getDefault('foo.testZero')).toBe 0
expect(settingsPanel.isDefault('foo.testZero')).toBe true
settingsPanel.set('foo.testZero', 15)
expect(settingsPanel.isDefault('foo.testZero')).toBe false
settingsPanel.set('foo.testZero', 0)
expect(settingsPanel.isDefault('foo.testZero')).toBe true
it "selects the default choice for radio options", ->
expect(settingsPanel.getDefault 'foo.radio').toBe 'Two'
settingsPanel.set 'foo.radio', 'Two'
expect(settingsPanel.element.querySelector '#foo\\.radio\\[Two\\]').toBeChecked()
describe 'scoped settings', ->
beforeEach ->
schema =
scopes:
'.source.python':
default: 4
atom.config.setScopedDefaultsFromSchema('editor.tabLength', schema)
expect(atom.config.get('editor.tabLength')).toBe(2)
it 'displays the scoped default', ->
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.python'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 4')
it 'allows the scoped setting to be changed to its normal default if the unscoped value is different', ->
atom.config.set('editor.tabLength', 8)
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.js'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 8')
# This is the unscoped default, but it differs from the current unscoped value
settingsPanel.set('editor.tabLength', 2)
expect(tabLengthEditor.getModel().getText()).toBe('2')
expect(atom.config.get('editor.tabLength', {scope: ['source.js']})).toBe(2)
it 'allows the scoped setting to be changed to the unscoped default if it is different', ->
settingsPanel = new SettingsPanel({namespace: "editor", includeTitle: false, scopeName: '.source.python'})
tabLengthEditor = settingsPanel.element.querySelector('[id="editor.tabLength"]')
expect(tabLengthEditor.getModel().getText()).toBe('')
expect(tabLengthEditor.getModel().getPlaceholderText()).toBe('Default: 4')
# This is the unscoped default, but it differs from the scoped default
settingsPanel.set('editor.tabLength', 2)
expect(tabLengthEditor.getModel().getText()).toBe('2')
expect(atom.config.get('editor.tabLength', {scope: ['source.python']})).toBe(2)
describe 'grouped settings', ->
beforeEach ->
config =
type: 'object'
properties:
barGroup:
type: 'object'
title: 'Bar group'
description: 'description of bar group'
properties:
bar:
title: 'Bar'
description: 'The bar setting'
type: 'boolean'
default: false
bazGroup:
type: 'object'
collapsed: true
properties:
baz:
title: 'Baz'
description: 'The baz setting'
type: 'boolean'
default: false
zing:
type: 'string'
default: ''
atom.config.setSchema('foo', config)
expect(_.size(atom.config.get('foo'))).toBe 3
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false})
it 'ensures that only grouped settings have a group title', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section .sub-section-heading').textContent).toBe 'Bar group'
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-body')).toHaveLength 1
subsectionBody = controlGroups[0].querySelector('.sub-section .sub-section-body')
expect(subsectionBody.querySelectorAll('.control-group')).toHaveLength 1
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').textContent).toBe 'Baz Group'
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-body')).toHaveLength 1
subsectionBody = controlGroups[1].querySelector('.sub-section .sub-section-body')
expect(subsectionBody.querySelectorAll('.control-group')).toHaveLength 1
expect(controlGroups[2].querySelectorAll('.sub-section')).toHaveLength 0
expect(controlGroups[2].querySelectorAll('.sub-section-heading')).toHaveLength 0
it 'ensures grouped settings are collapsable', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
# Bar group
expect(controlGroups[0].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section .sub-section-heading').classList.contains('has-items')).toBe true
# Baz Group
expect(controlGroups[1].querySelectorAll('.sub-section .sub-section-heading')).toHaveLength 1
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').classList.contains('has-items')).toBe true
# Should be already collapsed
expect(controlGroups[1].querySelector('.sub-section .sub-section-heading').parentElement.classList.contains('collapsed')).toBe true
it 'ensures grouped settings can have a description', ->
expect(settingsPanel.element.querySelectorAll('.section-container > .section-body')).toHaveLength 1
controlGroups = settingsPanel.element.querySelectorAll('.section-body > .control-group')
expect(controlGroups).toHaveLength 3
expect(controlGroups[0].querySelectorAll('.sub-section > .setting-description')).toHaveLength 1
expect(controlGroups[0].querySelector('.sub-section > .setting-description').textContent).toBe 'description of bar group'
describe 'settings validation', ->
beforeEach ->
config =
type: 'object'
properties:
minMax:
name: 'minMax'
title: 'Min max'
description: 'The minMax setting'
type: 'integer'
default: 10
minimum: 1
maximum: 100
commaValueArray:
name: 'commaValueArray'
title: 'Comma value in array'
description: 'An array with a comma value'
type: 'array'
default: []
atom.config.setSchema('foo', config)
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false})
it 'prevents setting a value below the minimum', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('0')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '1'
minMaxEditor.getModel().setText('-5')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '1'
it 'prevents setting a value above the maximum', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('1000')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '100'
minMaxEditor.getModel().setText('10000')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '100'
it 'prevents setting a value that cannot be coerced to the correct type', ->
minMaxEditor = settingsPanel.element.querySelector('[id="foo.minMax"]')
minMaxEditor.getModel().setText('"abcde"')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '' # aka default
minMaxEditor.getModel().setText('15')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
minMaxEditor.getModel().setText('"abcde"')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
it 'allows setting a valid scoped value', ->
settingsPanel = new SettingsPanel({namespace: 'foo', includeTitle: false, scopeName: 'source.js'})
minMaxEditor = settingsPanel.element.querySelector('atom-text-editor')
minMaxEditor.getModel().setText('15')
advanceClock(minMaxEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(minMaxEditor.getModel().getText()).toBe '15'
describe 'commaValueArray', ->
it 'comma in value is escaped', ->
commaValueArrayEditor = settingsPanel.element.querySelector('[id="foo.commaValueArray"]')
commaValueArrayEditor.getModel().setText('1, \\,, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get("foo.commaValueArray")).toEqual ['1', ',', '2']
commaValueArrayEditor.getModel().setText('1\\, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual ['1, 2']
commaValueArrayEditor.getModel().setText('1\\,')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual ['1,']
commaValueArrayEditor.getModel().setText('\\, 2')
advanceClock(commaValueArrayEditor.getModel().getBuffer().getStoppedChangingDelay())
expect(atom.config.get('foo.commaValueArray')).toEqual [', 2']
it 'renders an escaped comma', ->
commaValueArrayEditor = settingsPanel.element.querySelector('[id="foo.commaValueArray"]')
atom.config.set('foo.commaValueArray', ['3', ',', '4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3, \\,, 4'
atom.config.set('foo.commaValueArray', ['3, 4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3\\, 4'
atom.config.set('foo.commaValueArray', ['3,'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '3\\,'
atom.config.set('foo.commaValueArray', [', 4'])
advanceClock(1000)
expect(commaValueArrayEditor.getModel().getText()).toBe '\\, 4'
|
[
{
"context": "integration for contextmenu plugin (with help from Philip Weir)\nrcmail.addEventListener 'contextmenu_init', (men",
"end": 83,
"score": 0.9998860359191895,
"start": 72,
"tag": "NAME",
"value": "Philip Weir"
}
] | coffeescripts/contextmenu.coffee | helmo/roundcube-thunderbird_labels | 0 | # thunderbird_labels integration for contextmenu plugin (with help from Philip Weir)
rcmail.addEventListener 'contextmenu_init', (menu) ->
# dentify the folder list context menu
#console.log(menu.menu_name);
if menu.menu_name == 'messagelist'
menu.addEventListener 'init', (p) ->
if p.ref.menu_name == 'tb_label_popup'
# the thunderbird_labels popup menu is not a typical Roundcube popup
# intercept the menu creation and build our own
$(p.ref.container).children('ul').remove();
labels = $('#tb_label_popup ul').clone();
$(labels).find('a').click (ev) ->
# thunderbird_labels commands need message selection information
# code to simulate message selection taken from contextmenu core
if (p.ref.list_object)
prev_display_next = rcmail.env.display_next;
list_obj = rcmail[p.ref.list_object]
if (!(list_obj.selection.length == 1 && list_obj.in_selection(rcmail.env.context_menu_source_id)))
rcmail.env.display_next = false
# the thunderbird_labels command
rcm_tb_label_onclick($(ev.target))
if (p.ref.list_object)
rcmail.env.display_next = prev_display_next
return
$(p.ref.container).append(labels)
return
menu.addEventListener 'activate', (p) ->
# the thunderbird_labels commands do not match the pattern used in the Roundcube core so some custom handling is needed.
# overwrite the default command activation function
# setup a submenu and define the functions to show it
if p.btn == 'tb'
if (!$(p.el).parent('li').hasClass('submenu'))
ref = rcmail.env.contextmenus['messagelist'];
$(p.el).parent('li').addClass('submenu');
$(p.el).append("<span class='right-arrow'></span>");
$(p.el).data('command', 'tb_label_popup');
$(p.el).unbind('click'); # remove the default contextmenu click event
# code below taken from the contextmenu core for showing/hiding submenus
$(p.el).click (e) ->
if (!$(this).hasClass('active'))
return;
ref.submenu(this, e);
return false;
if (ref.mouseover_timeout > -1)
$(p.el).mouseover (e) ->
if (!$(this).hasClass('active'))
return;
ref.timers['submenu_show'] = window.setTimeout (a, e) ->
ref.submenu(a, e)
return
, ref.mouseover_timeout, $(p.el), e
return
$(p.el).mouseout (e) ->
$(this).blur()
clearTimeout(ref.timers['submenu_show'])
return
# contextmenu plugin automatically hide things that it does not think look like Roundcube commands
# make sure the labels command is visible
$(p.el).parent('li').show();
# check if the command is enabled
rcmail.commands['plugin.thunderbird_labels.rcm_tb_label_submenu']
return
| 140081 | # thunderbird_labels integration for contextmenu plugin (with help from <NAME>)
rcmail.addEventListener 'contextmenu_init', (menu) ->
# dentify the folder list context menu
#console.log(menu.menu_name);
if menu.menu_name == 'messagelist'
menu.addEventListener 'init', (p) ->
if p.ref.menu_name == 'tb_label_popup'
# the thunderbird_labels popup menu is not a typical Roundcube popup
# intercept the menu creation and build our own
$(p.ref.container).children('ul').remove();
labels = $('#tb_label_popup ul').clone();
$(labels).find('a').click (ev) ->
# thunderbird_labels commands need message selection information
# code to simulate message selection taken from contextmenu core
if (p.ref.list_object)
prev_display_next = rcmail.env.display_next;
list_obj = rcmail[p.ref.list_object]
if (!(list_obj.selection.length == 1 && list_obj.in_selection(rcmail.env.context_menu_source_id)))
rcmail.env.display_next = false
# the thunderbird_labels command
rcm_tb_label_onclick($(ev.target))
if (p.ref.list_object)
rcmail.env.display_next = prev_display_next
return
$(p.ref.container).append(labels)
return
menu.addEventListener 'activate', (p) ->
# the thunderbird_labels commands do not match the pattern used in the Roundcube core so some custom handling is needed.
# overwrite the default command activation function
# setup a submenu and define the functions to show it
if p.btn == 'tb'
if (!$(p.el).parent('li').hasClass('submenu'))
ref = rcmail.env.contextmenus['messagelist'];
$(p.el).parent('li').addClass('submenu');
$(p.el).append("<span class='right-arrow'></span>");
$(p.el).data('command', 'tb_label_popup');
$(p.el).unbind('click'); # remove the default contextmenu click event
# code below taken from the contextmenu core for showing/hiding submenus
$(p.el).click (e) ->
if (!$(this).hasClass('active'))
return;
ref.submenu(this, e);
return false;
if (ref.mouseover_timeout > -1)
$(p.el).mouseover (e) ->
if (!$(this).hasClass('active'))
return;
ref.timers['submenu_show'] = window.setTimeout (a, e) ->
ref.submenu(a, e)
return
, ref.mouseover_timeout, $(p.el), e
return
$(p.el).mouseout (e) ->
$(this).blur()
clearTimeout(ref.timers['submenu_show'])
return
# contextmenu plugin automatically hide things that it does not think look like Roundcube commands
# make sure the labels command is visible
$(p.el).parent('li').show();
# check if the command is enabled
rcmail.commands['plugin.thunderbird_labels.rcm_tb_label_submenu']
return
| true | # thunderbird_labels integration for contextmenu plugin (with help from PI:NAME:<NAME>END_PI)
rcmail.addEventListener 'contextmenu_init', (menu) ->
# dentify the folder list context menu
#console.log(menu.menu_name);
if menu.menu_name == 'messagelist'
menu.addEventListener 'init', (p) ->
if p.ref.menu_name == 'tb_label_popup'
# the thunderbird_labels popup menu is not a typical Roundcube popup
# intercept the menu creation and build our own
$(p.ref.container).children('ul').remove();
labels = $('#tb_label_popup ul').clone();
$(labels).find('a').click (ev) ->
# thunderbird_labels commands need message selection information
# code to simulate message selection taken from contextmenu core
if (p.ref.list_object)
prev_display_next = rcmail.env.display_next;
list_obj = rcmail[p.ref.list_object]
if (!(list_obj.selection.length == 1 && list_obj.in_selection(rcmail.env.context_menu_source_id)))
rcmail.env.display_next = false
# the thunderbird_labels command
rcm_tb_label_onclick($(ev.target))
if (p.ref.list_object)
rcmail.env.display_next = prev_display_next
return
$(p.ref.container).append(labels)
return
menu.addEventListener 'activate', (p) ->
# the thunderbird_labels commands do not match the pattern used in the Roundcube core so some custom handling is needed.
# overwrite the default command activation function
# setup a submenu and define the functions to show it
if p.btn == 'tb'
if (!$(p.el).parent('li').hasClass('submenu'))
ref = rcmail.env.contextmenus['messagelist'];
$(p.el).parent('li').addClass('submenu');
$(p.el).append("<span class='right-arrow'></span>");
$(p.el).data('command', 'tb_label_popup');
$(p.el).unbind('click'); # remove the default contextmenu click event
# code below taken from the contextmenu core for showing/hiding submenus
$(p.el).click (e) ->
if (!$(this).hasClass('active'))
return;
ref.submenu(this, e);
return false;
if (ref.mouseover_timeout > -1)
$(p.el).mouseover (e) ->
if (!$(this).hasClass('active'))
return;
ref.timers['submenu_show'] = window.setTimeout (a, e) ->
ref.submenu(a, e)
return
, ref.mouseover_timeout, $(p.el), e
return
$(p.el).mouseout (e) ->
$(this).blur()
clearTimeout(ref.timers['submenu_show'])
return
# contextmenu plugin automatically hide things that it does not think look like Roundcube commands
# make sure the labels command is visible
$(p.el).parent('li').show();
# check if the command is enabled
rcmail.commands['plugin.thunderbird_labels.rcm_tb_label_submenu']
return
|
[
{
"context": " basic templating\", () ->\n obj =\n a: {b: \"Hello\"}\n c: \"World\"\n d: {e: \"I\"}\n f: \"he",
"end": 2294,
"score": 0.639407217502594,
"start": 2289,
"tag": "NAME",
"value": "Hello"
}
] | src/test.coffee | typeduck/amqp-pool | 0 | ###############################################################################
# Tests out our local server
###############################################################################
should = require("should")
pool = require("./index")
AMQP = require("amqplib")
assign = require("lodash.assign")
When = require("when")
# HELPER METHODS FOR before/after test suite
setupLife = (setup) ->
return (done) ->
AMQP.connect().then((conn) ->
setup.conn = conn
conn.createConfirmChannel()
).then((ch) ->
setup.channel = ch
When.all([
ch.assertExchange("Animalia", "topic")
ch.assertExchange("Plantae", "topic")
]).then(() -> done())
).catch(done)
removeLife = (setup) ->
return (done) ->
When.all([
setup.channel.deleteExchange("Animalia")
setup.channel.deleteExchange("Plantae")
]).then(() -> setup.channel.close()
).then(() -> setup.conn.close()
).then(done).catch(done)
###############################################################################
# Tests that we can make a connection
###############################################################################
describe "Connection", () ->
# Set the conditions for life on our AMQP server
before(setupLife(setup = {}))
# Remove expected exchanges
after(removeLife(setup))
# Creates another (default) connection
it "should be able to create default connection", (done) ->
mypool = pool()
mypool.activate().then(() ->
mypool.deactivate()
).then(() -> done()).catch(done)
# Creates explicit connection
it "should be able to accept server URL", (done) ->
mypool = pool({server: "amqp://guest:guest@localhost"})
mypool.activate().then(() ->
mypool.deactivate()
).then(() -> done()).catch(done)
# Tests only the route templating
describe "Route [internal]", () ->
Route = require("./Route")
# Stupid test object
obj =
a: {b: "Hello"}
c: "World"
d: {e: "I", h: "NO", i: "NO"}
f: "here"
g: {h: {i: "now"}}
it "should handle direct to queue", () ->
obj = {}
route = new Route("direct-to-queue")
route.exchange(obj).should.equal("")
route.route(obj).should.equal("direct-to-queue")
it "should handle basic templating", () ->
obj =
a: {b: "Hello"}
c: "World"
d: {e: "I"}
f: "here"
route = new Route("{{a.b}}-{{c}}/{{d.e}}.is.{{f}}")
route.exchange(obj).should.equal("Hello-World")
route.route(obj).should.equal("I.is.here")
route = new Route("{{a.b}}-{{c}}", "{{d.e}}.is.{{f}}")
route.exchange(obj).should.equal("Hello-World")
route.route(obj).should.equal("I.is.here")
it "should create Queue-based routing", () ->
routes = Route.read("direct-to-queue")
routes[0].exchange(obj).should.equal("")
routes[0].route(obj).should.equal("direct-to-queue")
it "should create Queue-based routing (with arbitrary options)", () ->
routes = Route.read("direct-to-queue?edc-p")
routes[0].exchange(obj).should.equal("")
routes[0].route(obj).should.equal("direct-to-queue")
it "should read routes in a few ways", () ->
obj =
ex1: "Animalia"
rk1: "Chordata"
rk2: "Echinodermata"
ex2: "Plantae"
rk3: "Magnoliophyta"
rk4: "Chlorophyta"
# First way: as array
routes = Route.read(["{{ex1}}?d/{{rk1}}?c/{{rk2}}?c", "{{ex2}}/{{rk3}}/{{rk4}}"])
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Second way: as arguments
routes = Route.read("{{ex1}}/{{rk1}}/{{rk2}}", "{{ex2}}/{{rk3}}/{{rk4}}")
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Third way: arguments including array
routes = Route.read("{{ex1}}/{{rk1}}/{{rk2}}", ["{{ex2}}/{{rk3}}/{{rk4}}"])
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Publish/Consume
describe "Publisher", () ->
# Make sure that proper setup is acheived
before(setupLife(setup = {}))
after(removeLife(setup))
# Tests 500 messages
it "should be able to set up publisher/consumer", (done) ->
@timeout(5000)
maxHumans = 10
countDown = (maxHumans + 1) * (maxHumans / 2) * 3
gotMessage = (msg) ->
o = msg.json
o.kingdom.should.equal("Animalia")
o.phylum.should.equal("Chordata")
o["class"].should.equal("Mammalia")
o.order.should.equal("Primates")
o.family.should.equal("Hominadae")
o.genus.should.equal("Homo")
o.species.should.equal("sapiens")
countDown -= msg.json.id
if countDown is 0
P.deactivate().then(done).catch(done)
P = pool({
maxChannels: 8
publishers:
life: "{{kingdom}}/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
consumers:
apes:
routes: ["Animalia/Chordata.*.Primates.#"]
method: gotMessage
humans:
routes: ["Animalia/#.sapiens"]
method: gotMessage
generic:
routes: "Animalia/#"
method: gotMessage
})
P.activate().then(() ->
# publish a bunch of humans ;-)
for i in [1..maxHumans]
P.publish.life({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
})
)
# Test that publishing one bad route does not corrupt another
it "should multi-route publisher must continue in face of errors", (done) ->
@timeout(5000)
maxAnimals = 1000
countDown = (maxAnimals + 1) * (maxAnimals / 2)
gotMessage = (msg) ->
o = msg.json
o.kingdom.should.equal("Animalia")
countDown -= msg.json.id
if countDown is 0
P.deactivate().then(done).catch(done)
P = pool({
publishers:
life: "{{kingdom}}/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
bad: "Non-Existent/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
consumers:
living:
routes: "Animalia/#"
method: gotMessage
})
P.activate().then(() ->
for i in [1..maxAnimals]
P.publish.bad({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
})
P.publish.life({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
}, true)
)
| 110212 | ###############################################################################
# Tests out our local server
###############################################################################
should = require("should")
pool = require("./index")
AMQP = require("amqplib")
assign = require("lodash.assign")
When = require("when")
# HELPER METHODS FOR before/after test suite
setupLife = (setup) ->
return (done) ->
AMQP.connect().then((conn) ->
setup.conn = conn
conn.createConfirmChannel()
).then((ch) ->
setup.channel = ch
When.all([
ch.assertExchange("Animalia", "topic")
ch.assertExchange("Plantae", "topic")
]).then(() -> done())
).catch(done)
removeLife = (setup) ->
return (done) ->
When.all([
setup.channel.deleteExchange("Animalia")
setup.channel.deleteExchange("Plantae")
]).then(() -> setup.channel.close()
).then(() -> setup.conn.close()
).then(done).catch(done)
###############################################################################
# Tests that we can make a connection
###############################################################################
describe "Connection", () ->
# Set the conditions for life on our AMQP server
before(setupLife(setup = {}))
# Remove expected exchanges
after(removeLife(setup))
# Creates another (default) connection
it "should be able to create default connection", (done) ->
mypool = pool()
mypool.activate().then(() ->
mypool.deactivate()
).then(() -> done()).catch(done)
# Creates explicit connection
it "should be able to accept server URL", (done) ->
mypool = pool({server: "amqp://guest:guest@localhost"})
mypool.activate().then(() ->
mypool.deactivate()
).then(() -> done()).catch(done)
# Tests only the route templating
describe "Route [internal]", () ->
Route = require("./Route")
# Stupid test object
obj =
a: {b: "Hello"}
c: "World"
d: {e: "I", h: "NO", i: "NO"}
f: "here"
g: {h: {i: "now"}}
it "should handle direct to queue", () ->
obj = {}
route = new Route("direct-to-queue")
route.exchange(obj).should.equal("")
route.route(obj).should.equal("direct-to-queue")
it "should handle basic templating", () ->
obj =
a: {b: "<NAME>"}
c: "World"
d: {e: "I"}
f: "here"
route = new Route("{{a.b}}-{{c}}/{{d.e}}.is.{{f}}")
route.exchange(obj).should.equal("Hello-World")
route.route(obj).should.equal("I.is.here")
route = new Route("{{a.b}}-{{c}}", "{{d.e}}.is.{{f}}")
route.exchange(obj).should.equal("Hello-World")
route.route(obj).should.equal("I.is.here")
it "should create Queue-based routing", () ->
routes = Route.read("direct-to-queue")
routes[0].exchange(obj).should.equal("")
routes[0].route(obj).should.equal("direct-to-queue")
it "should create Queue-based routing (with arbitrary options)", () ->
routes = Route.read("direct-to-queue?edc-p")
routes[0].exchange(obj).should.equal("")
routes[0].route(obj).should.equal("direct-to-queue")
it "should read routes in a few ways", () ->
obj =
ex1: "Animalia"
rk1: "Chordata"
rk2: "Echinodermata"
ex2: "Plantae"
rk3: "Magnoliophyta"
rk4: "Chlorophyta"
# First way: as array
routes = Route.read(["{{ex1}}?d/{{rk1}}?c/{{rk2}}?c", "{{ex2}}/{{rk3}}/{{rk4}}"])
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Second way: as arguments
routes = Route.read("{{ex1}}/{{rk1}}/{{rk2}}", "{{ex2}}/{{rk3}}/{{rk4}}")
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Third way: arguments including array
routes = Route.read("{{ex1}}/{{rk1}}/{{rk2}}", ["{{ex2}}/{{rk3}}/{{rk4}}"])
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Publish/Consume
describe "Publisher", () ->
# Make sure that proper setup is acheived
before(setupLife(setup = {}))
after(removeLife(setup))
# Tests 500 messages
it "should be able to set up publisher/consumer", (done) ->
@timeout(5000)
maxHumans = 10
countDown = (maxHumans + 1) * (maxHumans / 2) * 3
gotMessage = (msg) ->
o = msg.json
o.kingdom.should.equal("Animalia")
o.phylum.should.equal("Chordata")
o["class"].should.equal("Mammalia")
o.order.should.equal("Primates")
o.family.should.equal("Hominadae")
o.genus.should.equal("Homo")
o.species.should.equal("sapiens")
countDown -= msg.json.id
if countDown is 0
P.deactivate().then(done).catch(done)
P = pool({
maxChannels: 8
publishers:
life: "{{kingdom}}/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
consumers:
apes:
routes: ["Animalia/Chordata.*.Primates.#"]
method: gotMessage
humans:
routes: ["Animalia/#.sapiens"]
method: gotMessage
generic:
routes: "Animalia/#"
method: gotMessage
})
P.activate().then(() ->
# publish a bunch of humans ;-)
for i in [1..maxHumans]
P.publish.life({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
})
)
# Test that publishing one bad route does not corrupt another
it "should multi-route publisher must continue in face of errors", (done) ->
@timeout(5000)
maxAnimals = 1000
countDown = (maxAnimals + 1) * (maxAnimals / 2)
gotMessage = (msg) ->
o = msg.json
o.kingdom.should.equal("Animalia")
countDown -= msg.json.id
if countDown is 0
P.deactivate().then(done).catch(done)
P = pool({
publishers:
life: "{{kingdom}}/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
bad: "Non-Existent/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
consumers:
living:
routes: "Animalia/#"
method: gotMessage
})
P.activate().then(() ->
for i in [1..maxAnimals]
P.publish.bad({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
})
P.publish.life({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
}, true)
)
| true | ###############################################################################
# Tests out our local server
###############################################################################
should = require("should")
pool = require("./index")
AMQP = require("amqplib")
assign = require("lodash.assign")
When = require("when")
# HELPER METHODS FOR before/after test suite
setupLife = (setup) ->
return (done) ->
AMQP.connect().then((conn) ->
setup.conn = conn
conn.createConfirmChannel()
).then((ch) ->
setup.channel = ch
When.all([
ch.assertExchange("Animalia", "topic")
ch.assertExchange("Plantae", "topic")
]).then(() -> done())
).catch(done)
removeLife = (setup) ->
return (done) ->
When.all([
setup.channel.deleteExchange("Animalia")
setup.channel.deleteExchange("Plantae")
]).then(() -> setup.channel.close()
).then(() -> setup.conn.close()
).then(done).catch(done)
###############################################################################
# Tests that we can make a connection
###############################################################################
describe "Connection", () ->
# Set the conditions for life on our AMQP server
before(setupLife(setup = {}))
# Remove expected exchanges
after(removeLife(setup))
# Creates another (default) connection
it "should be able to create default connection", (done) ->
mypool = pool()
mypool.activate().then(() ->
mypool.deactivate()
).then(() -> done()).catch(done)
# Creates explicit connection
it "should be able to accept server URL", (done) ->
mypool = pool({server: "amqp://guest:guest@localhost"})
mypool.activate().then(() ->
mypool.deactivate()
).then(() -> done()).catch(done)
# Tests only the route templating
describe "Route [internal]", () ->
Route = require("./Route")
# Stupid test object
obj =
a: {b: "Hello"}
c: "World"
d: {e: "I", h: "NO", i: "NO"}
f: "here"
g: {h: {i: "now"}}
it "should handle direct to queue", () ->
obj = {}
route = new Route("direct-to-queue")
route.exchange(obj).should.equal("")
route.route(obj).should.equal("direct-to-queue")
it "should handle basic templating", () ->
obj =
a: {b: "PI:NAME:<NAME>END_PI"}
c: "World"
d: {e: "I"}
f: "here"
route = new Route("{{a.b}}-{{c}}/{{d.e}}.is.{{f}}")
route.exchange(obj).should.equal("Hello-World")
route.route(obj).should.equal("I.is.here")
route = new Route("{{a.b}}-{{c}}", "{{d.e}}.is.{{f}}")
route.exchange(obj).should.equal("Hello-World")
route.route(obj).should.equal("I.is.here")
it "should create Queue-based routing", () ->
routes = Route.read("direct-to-queue")
routes[0].exchange(obj).should.equal("")
routes[0].route(obj).should.equal("direct-to-queue")
it "should create Queue-based routing (with arbitrary options)", () ->
routes = Route.read("direct-to-queue?edc-p")
routes[0].exchange(obj).should.equal("")
routes[0].route(obj).should.equal("direct-to-queue")
it "should read routes in a few ways", () ->
obj =
ex1: "Animalia"
rk1: "Chordata"
rk2: "Echinodermata"
ex2: "Plantae"
rk3: "Magnoliophyta"
rk4: "Chlorophyta"
# First way: as array
routes = Route.read(["{{ex1}}?d/{{rk1}}?c/{{rk2}}?c", "{{ex2}}/{{rk3}}/{{rk4}}"])
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Second way: as arguments
routes = Route.read("{{ex1}}/{{rk1}}/{{rk2}}", "{{ex2}}/{{rk3}}/{{rk4}}")
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Third way: arguments including array
routes = Route.read("{{ex1}}/{{rk1}}/{{rk2}}", ["{{ex2}}/{{rk3}}/{{rk4}}"])
routes.length.should.equal(4)
routes[0].exchange(obj).should.equal("Animalia")
routes[0].route(obj).should.equal("Chordata")
routes[1].exchange(obj).should.equal("Animalia")
routes[1].route(obj).should.equal("Echinodermata")
routes[2].exchange(obj).should.equal("Plantae")
routes[2].route(obj).should.equal("Magnoliophyta")
routes[3].exchange(obj).should.equal("Plantae")
routes[3].route(obj).should.equal("Chlorophyta")
# Publish/Consume
describe "Publisher", () ->
# Make sure that proper setup is acheived
before(setupLife(setup = {}))
after(removeLife(setup))
# Tests 500 messages
it "should be able to set up publisher/consumer", (done) ->
@timeout(5000)
maxHumans = 10
countDown = (maxHumans + 1) * (maxHumans / 2) * 3
gotMessage = (msg) ->
o = msg.json
o.kingdom.should.equal("Animalia")
o.phylum.should.equal("Chordata")
o["class"].should.equal("Mammalia")
o.order.should.equal("Primates")
o.family.should.equal("Hominadae")
o.genus.should.equal("Homo")
o.species.should.equal("sapiens")
countDown -= msg.json.id
if countDown is 0
P.deactivate().then(done).catch(done)
P = pool({
maxChannels: 8
publishers:
life: "{{kingdom}}/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
consumers:
apes:
routes: ["Animalia/Chordata.*.Primates.#"]
method: gotMessage
humans:
routes: ["Animalia/#.sapiens"]
method: gotMessage
generic:
routes: "Animalia/#"
method: gotMessage
})
P.activate().then(() ->
# publish a bunch of humans ;-)
for i in [1..maxHumans]
P.publish.life({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
})
)
# Test that publishing one bad route does not corrupt another
it "should multi-route publisher must continue in face of errors", (done) ->
@timeout(5000)
maxAnimals = 1000
countDown = (maxAnimals + 1) * (maxAnimals / 2)
gotMessage = (msg) ->
o = msg.json
o.kingdom.should.equal("Animalia")
countDown -= msg.json.id
if countDown is 0
P.deactivate().then(done).catch(done)
P = pool({
publishers:
life: "{{kingdom}}/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
bad: "Non-Existent/{{phylum}}.{{class}}.{{order}}.{{family}}.{{genus}}.{{species}}"
consumers:
living:
routes: "Animalia/#"
method: gotMessage
})
P.activate().then(() ->
for i in [1..maxAnimals]
P.publish.bad({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
})
P.publish.life({
kingdom: "Animalia"
phylum: "Chordata"
class: "Mammalia"
order: "Primates"
family: "Hominadae"
genus: "Homo"
species: "sapiens"
id: i
}, true)
)
|
[
{
"context": "hars and rules\n * @source_code https://github.com/chentianwen/password_wizard\n *\n * @copyright 2011, Tianwen Ch",
"end": 149,
"score": 0.9995483160018921,
"start": 138,
"tag": "USERNAME",
"value": "chentianwen"
},
{
"context": "chentianwen/password_wizard\n *\n * @copyright 2011, Tianwen Chen\n * @website https://github.tian.im\n *\n * Licensed",
"end": 201,
"score": 0.9998278617858887,
"start": 189,
"tag": "NAME",
"value": "Tianwen Chen"
}
] | lib/jquery.password_wizard.coffee | tian-im/password_wizard | 1 | ###
* Password Wizard v0.0.1
* @summary generate the password using different set of chars and rules
* @source_code https://github.com/chentianwen/password_wizard
*
* @copyright 2011, Tianwen Chen
* @website https://github.tian.im
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
###
"use_strict"
class window.PasswordGenerator
# @param length [ Integer ] length of the password
# @param candidates [ String, Array ] character candidates, could be string or array of string
constructor: (@length = PasswordWizard.DEFAULT_LENGTH, @candidates = PasswordWizard.ALPHANUMBERS) ->
@candidates = @candidates.join('') if @candidates instanceof Array
one_char: ->
@candidates.charAt(Math.floor(Math.random() * @candidates.length))
generate: ->
result = (@one_char() for len in [ 1..@length ])
result.join('')
class window.PasswordFrequencyChecker
# @param candidates [ String, Array ] character candidates, could be string or array of string
# @param frequency [ Integer ] minimum occurance frequency
constructor: (@candidates, @frequency) ->
@candidates = @candidates.join('') if @candidates instanceof Array
@pattern = new RegExp("[#{ @candidates }]", RegExp.global)
check: (password)->
password_phrase = password
for frequency in [ 1..@frequency ]
return false if (position = password_phrase.search(@pattern)) < 0
# slice the string to get ready for the next test
password_phrase = password_phrase.substring(position + 1)
true
class window.DigitsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.DIGITS, frequency
class window.AlphabetsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.ALPHABETS, frequency
class window.SymbolsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.SYMBOLS, frequency
class window.PasswordWatchdog
# @param rules [ Array ]
# @example Rules will be the following format
# [ [ DigitsFrequencyChecker, 2 ] ]
# [ [ PasswordFrequencyChecker, '0123456', 10 ] ]
constructor: (@rules = []) ->
@rules = (new rule[0](rule.slice(1)...) for rule in @rules)
test: (password)->
return false unless password?
(return false unless rule.check(password)) for rule in @rules
true
class window.PasswordWizard
@TITLE: 'Password Wizard'
@VERSION: '0.0.1'
@DIGITS: '0123456789'
@DOWNCASE_ALPHABETS: 'abcdefghijklmnopqrstuvwxyz'
@SYMBOLS: '~`!@#$%^&*()-_+={[}]|\\:;"\'<,>.?/'
@UPCASE_ALPHABETS: @DOWNCASE_ALPHABETS.toUpperCase()
@DOWNCASE_ALPHANUMBERS: @DOWNCASE_ALPHABETS + @DIGITS
@ALPHABETS: @DOWNCASE_ALPHABETS + @UPCASE_ALPHABETS
@ALPHANUMBERS: @DOWNCASE_ALPHANUMBERS + @UPCASE_ALPHABETS
@TYPE_SAFES: 'iIl1|oO0'
@DEFAULT_LENGTH: 8
@MAX_ATTAMPTS: 88
constructor: ->
@rules = []
@candidates = []
length: (length = undefined) ->
if length?
@len = length
@
else
@len ?= PasswordWizard.DEFAULT_LENGTH
add_rule: (checker, args...) ->
@rules.push([ checker, args... ])
add_candidate: (candidate) ->
@candidates.push(candidate)
generate: ->
attampts = 0
watchdog = new PasswordWatchdog(@rules)
# unless the test passes
until watchdog.test(password)
# or max attampts reaches
return '' if attampts++ >= PasswordWizard.MAX_ATTAMPTS
password = new PasswordGenerator(@len, @candidates).generate()
password
| 41699 | ###
* Password Wizard v0.0.1
* @summary generate the password using different set of chars and rules
* @source_code https://github.com/chentianwen/password_wizard
*
* @copyright 2011, <NAME>
* @website https://github.tian.im
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
###
"use_strict"
class window.PasswordGenerator
# @param length [ Integer ] length of the password
# @param candidates [ String, Array ] character candidates, could be string or array of string
constructor: (@length = PasswordWizard.DEFAULT_LENGTH, @candidates = PasswordWizard.ALPHANUMBERS) ->
@candidates = @candidates.join('') if @candidates instanceof Array
one_char: ->
@candidates.charAt(Math.floor(Math.random() * @candidates.length))
generate: ->
result = (@one_char() for len in [ 1..@length ])
result.join('')
class window.PasswordFrequencyChecker
# @param candidates [ String, Array ] character candidates, could be string or array of string
# @param frequency [ Integer ] minimum occurance frequency
constructor: (@candidates, @frequency) ->
@candidates = @candidates.join('') if @candidates instanceof Array
@pattern = new RegExp("[#{ @candidates }]", RegExp.global)
check: (password)->
password_phrase = password
for frequency in [ 1..@frequency ]
return false if (position = password_phrase.search(@pattern)) < 0
# slice the string to get ready for the next test
password_phrase = password_phrase.substring(position + 1)
true
class window.DigitsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.DIGITS, frequency
class window.AlphabetsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.ALPHABETS, frequency
class window.SymbolsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.SYMBOLS, frequency
class window.PasswordWatchdog
# @param rules [ Array ]
# @example Rules will be the following format
# [ [ DigitsFrequencyChecker, 2 ] ]
# [ [ PasswordFrequencyChecker, '0123456', 10 ] ]
constructor: (@rules = []) ->
@rules = (new rule[0](rule.slice(1)...) for rule in @rules)
test: (password)->
return false unless password?
(return false unless rule.check(password)) for rule in @rules
true
class window.PasswordWizard
@TITLE: 'Password Wizard'
@VERSION: '0.0.1'
@DIGITS: '0123456789'
@DOWNCASE_ALPHABETS: 'abcdefghijklmnopqrstuvwxyz'
@SYMBOLS: '~`!@#$%^&*()-_+={[}]|\\:;"\'<,>.?/'
@UPCASE_ALPHABETS: @DOWNCASE_ALPHABETS.toUpperCase()
@DOWNCASE_ALPHANUMBERS: @DOWNCASE_ALPHABETS + @DIGITS
@ALPHABETS: @DOWNCASE_ALPHABETS + @UPCASE_ALPHABETS
@ALPHANUMBERS: @DOWNCASE_ALPHANUMBERS + @UPCASE_ALPHABETS
@TYPE_SAFES: 'iIl1|oO0'
@DEFAULT_LENGTH: 8
@MAX_ATTAMPTS: 88
constructor: ->
@rules = []
@candidates = []
length: (length = undefined) ->
if length?
@len = length
@
else
@len ?= PasswordWizard.DEFAULT_LENGTH
add_rule: (checker, args...) ->
@rules.push([ checker, args... ])
add_candidate: (candidate) ->
@candidates.push(candidate)
generate: ->
attampts = 0
watchdog = new PasswordWatchdog(@rules)
# unless the test passes
until watchdog.test(password)
# or max attampts reaches
return '' if attampts++ >= PasswordWizard.MAX_ATTAMPTS
password = new PasswordGenerator(@len, @candidates).generate()
password
| true | ###
* Password Wizard v0.0.1
* @summary generate the password using different set of chars and rules
* @source_code https://github.com/chentianwen/password_wizard
*
* @copyright 2011, PI:NAME:<NAME>END_PI
* @website https://github.tian.im
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
###
"use_strict"
class window.PasswordGenerator
# @param length [ Integer ] length of the password
# @param candidates [ String, Array ] character candidates, could be string or array of string
constructor: (@length = PasswordWizard.DEFAULT_LENGTH, @candidates = PasswordWizard.ALPHANUMBERS) ->
@candidates = @candidates.join('') if @candidates instanceof Array
one_char: ->
@candidates.charAt(Math.floor(Math.random() * @candidates.length))
generate: ->
result = (@one_char() for len in [ 1..@length ])
result.join('')
class window.PasswordFrequencyChecker
# @param candidates [ String, Array ] character candidates, could be string or array of string
# @param frequency [ Integer ] minimum occurance frequency
constructor: (@candidates, @frequency) ->
@candidates = @candidates.join('') if @candidates instanceof Array
@pattern = new RegExp("[#{ @candidates }]", RegExp.global)
check: (password)->
password_phrase = password
for frequency in [ 1..@frequency ]
return false if (position = password_phrase.search(@pattern)) < 0
# slice the string to get ready for the next test
password_phrase = password_phrase.substring(position + 1)
true
class window.DigitsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.DIGITS, frequency
class window.AlphabetsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.ALPHABETS, frequency
class window.SymbolsFrequencyChecker extends PasswordFrequencyChecker
constructor: (frequency) ->
super PasswordWizard.SYMBOLS, frequency
class window.PasswordWatchdog
# @param rules [ Array ]
# @example Rules will be the following format
# [ [ DigitsFrequencyChecker, 2 ] ]
# [ [ PasswordFrequencyChecker, '0123456', 10 ] ]
constructor: (@rules = []) ->
@rules = (new rule[0](rule.slice(1)...) for rule in @rules)
test: (password)->
return false unless password?
(return false unless rule.check(password)) for rule in @rules
true
class window.PasswordWizard
@TITLE: 'Password Wizard'
@VERSION: '0.0.1'
@DIGITS: '0123456789'
@DOWNCASE_ALPHABETS: 'abcdefghijklmnopqrstuvwxyz'
@SYMBOLS: '~`!@#$%^&*()-_+={[}]|\\:;"\'<,>.?/'
@UPCASE_ALPHABETS: @DOWNCASE_ALPHABETS.toUpperCase()
@DOWNCASE_ALPHANUMBERS: @DOWNCASE_ALPHABETS + @DIGITS
@ALPHABETS: @DOWNCASE_ALPHABETS + @UPCASE_ALPHABETS
@ALPHANUMBERS: @DOWNCASE_ALPHANUMBERS + @UPCASE_ALPHABETS
@TYPE_SAFES: 'iIl1|oO0'
@DEFAULT_LENGTH: 8
@MAX_ATTAMPTS: 88
constructor: ->
@rules = []
@candidates = []
length: (length = undefined) ->
if length?
@len = length
@
else
@len ?= PasswordWizard.DEFAULT_LENGTH
add_rule: (checker, args...) ->
@rules.push([ checker, args... ])
add_candidate: (candidate) ->
@candidates.push(candidate)
generate: ->
attampts = 0
watchdog = new PasswordWatchdog(@rules)
# unless the test passes
until watchdog.test(password)
# or max attampts reaches
return '' if attampts++ >= PasswordWizard.MAX_ATTAMPTS
password = new PasswordGenerator(@len, @candidates).generate()
password
|
[
{
"context": "exp: ///(^|#{bcv_parser::regexps.pre_book})(\n\t\t(?:Joel)\n\t\t\t)(?:(?=[\\d\\s\\xa0.:,;\\x1e\\x1f&\\(\\)\\uff08\\uff",
"end": 16459,
"score": 0.7859866619110107,
"start": 16457,
"tag": "NAME",
"value": "Jo"
},
{
"context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"Matt\"]\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book}",
"end": 18450,
"score": 0.6664522886276245,
"start": 18446,
"tag": "NAME",
"value": "Matt"
},
{
"context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"Mark\"]\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book}",
"end": 18704,
"score": 0.8763443231582642,
"start": 18700,
"tag": "NAME",
"value": "Mark"
}
] | src/sk/regexps.coffee | phillipb/Bible-Passage-Reference-Parser | 149 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| title (?! [a-z] ) #could be followed by a number
| ver[šs]ov | kapitoly | kapitole | kapitolu | kapitol | hlavy | a[žz] | porov | pozri | alebo | kap | ff | - | a
| [b-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* title
| \d \W* ff (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [b-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Prv[áa]#{bcv_parser::regexps.space}+kniha|Prv[ýy]#{bcv_parser::regexps.space}+list|Prv[áa]|Prv[ýy]|1#{bcv_parser::regexps.space}+k|I|1)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Druh[áa]#{bcv_parser::regexps.space}+kniha|Druh[ýy]#{bcv_parser::regexps.space}+list|Druh[áa]|Druh[ýy]|2#{bcv_parser::regexps.space}+k|II|2)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Tretia#{bcv_parser::regexps.space}+kniha|Tretia|Tret[íi]|3#{bcv_parser::regexps.space}+k|III|3)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:porov|pozri|alebo|a)|(?:a[žz]|-))"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|(?:a[žz]|-))"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Moj[zž]i[sš]ova)|(?:K(?:\.[\s\xa0]*p[o\xF4]|[\s\xa0]*p[o\xF4]|niha[\s\xa0]*p[o\xF4])vodu|G(?:enezis|n)|1[\s\xa0]*M|Gen|K(?:niha|\.)?[\s\xa0]*stvorenia|(?:1[\s\xa0]*k|I)[\s\xa0]*Moj[zž]i[sš]ova|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Moj[zž]i[sš]ova|Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Moj[zž]i[sš]|[y\xFD][\s\xa0]*Moj[zž]i[sš]|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš]))ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Moj[zž]i[sš]ova|Exodus)|(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Moj[zž]i[sš]|[y\xFD][\s\xa0]*Moj[zž]i[sš]|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš]))ova|(?:2[\s\xa0]*k|II)[\s\xa0]*Moj[zž]i[sš]ova|Exod|2[\s\xa0]*M|Ex|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Moj[zž]i[sš]ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[e\xE9]l(?:[\s\xa0]*a[\s\xa0]*drak)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Moj[zž]i[sš]ova)|(?:(?:3[\s\xa0]*k|III)[\s\xa0]*Moj[zž]i[sš]ova|L(?:evitikus|v)|3[\s\xa0]*M|Lev|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*Moj[zž]i[sš]ova|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])|[\s\xa0]*Moj[zž]i[sš])|\xED[\s\xa0]*Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Moj[zž]i[sš]ova)|(?:(?:4[\s\xa0]*k|IV)[\s\xa0]*Moj[zž]i[sš]ova|N(?:umeri|m)|4[\s\xa0]*M|Num|(?:4(?:[\s\xa0]*k)?|IV)\.[\s\xa0]*Moj[zž]i[sš]ova|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus)|[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus)|niha[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus))|Sir(?:achovcova|achovec)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M[u\xFA]d(?:ros(?:ti?|ť))?|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*n[a\xE1]|[\s\xa0]*n[a\xE1]|niha[\s\xa0]*n[a\xE1])rekov|N[a\xE1]reky|Lam|[ZŽ]alospevy|Pla[cč][\s\xa0]*Jeremi[a\xE1][sš]ov|[ZŽ]alosp|N[a\xE1]r|Jeremi[a\xE1][sš]ov[\s\xa0]*Pla[cč])|(?:Pla[cč])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jeremi[a\xE1][sš]ov[\s\xa0]*list|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zj(?:av(?:enie(?:[\s\xa0]*(?:sv[a\xE4]t[e\xE9]ho[\s\xa0]*J[a\xE1]|J[a\xE1]|Apo[sš]tola[\s\xa0]*J[a\xE1])na)?)?|v)?|Apokalypsa|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Manasesova[\s\xa0]*modlitba|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:5[\s\xa0]*Moj[zž]i[sš]ova)|(?:D(?:euteron[o\xF3]mium|t)|5[\s\xa0]*M|Deut|(?:5[\s\xa0]*k|V)[\s\xa0]*Moj[zž]i[sš]ova|(?:5(?:[\s\xa0]*k)?|V)\.[\s\xa0]*Moj[zž]i[sš]ova|Piata[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o(?:z(?:u[ae]|uova)?|šu(?:ov)?a|s(?:u(?:ov)?a|h))|\xF3zu(?:ov)?a)|Iosua)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:udcovia|dc)|Judg|Sud(?:cov)?|K\.?[\s\xa0]*sudcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:\xFAt|uth?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[y\xFD][\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Ezdr[a\xE1][sš](?:ova)?))|(?:1[\s\xa0]*k|I)[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|1(?:[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Esd)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[y\xFD][\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Ezdr[a\xE1][sš](?:ova)?))|(?:2[\s\xa0]*k|II)[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|2(?:[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Esd)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:z(?:a[ij][a\xE1][sš])?|sa))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Samuelova)|(?:(?:2[\s\xa0]*k|II)[\s\xa0]*Samuelova|2(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Samuelova|Druh(?:(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?)Samuelova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Samuelova)|(?:(?:1[\s\xa0]*k|I)[\s\xa0]*Samuelova|1(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Samuelova|Prv(?:(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?)Samuelova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Kr[a\xE1][lľ]ov|[\s\xa0]*Kr[lľ]|Kgs|[\s\xa0]*Kr)|(?:Druh[y\xFD]|4)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:I[IV]|4[\s\xa0]*k|2[\s\xa0]*k)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:(?:I[IV]|4[\s\xa0]*k|4|2(?:[\s\xa0]*k)?)\.|Druh[y\xFD][\s\xa0]*list)[\s\xa0]*Kr[a\xE1][lľ]ov|Druh[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Kr[a\xE1][lľ]ov|[\s\xa0]*Kr[lľ]|Kgs|[\s\xa0]*Kr)|(?:Prv[y\xFD]|3)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:3[\s\xa0]*k|III|I|1[\s\xa0]*k)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:(?:3[\s\xa0]*k|III|[3I]|1(?:[\s\xa0]*k)?)\.|Prv[y\xFD][\s\xa0]*list)[\s\xa0]*Kr[a\xE1][lľ]ov|Prv[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])|[\s\xa0]*Kr[a\xE1][lľ])|\xED[\s\xa0]*Kr[a\xE1][lľ])ov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|[y\xFD][\s\xa0]*Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|[y\xFD][\s\xa0]*Paralipomenon|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))|2(?:[\s\xa0]*Kroni(?:ck[a\xE1]|k)|[\s\xa0]*Kron\xEDk|[\s\xa0]*Krn|Chr|[\s\xa0]*Kron|[\s\xa0]*Paralipomenon)|(?:2[\s\xa0]*k|II)[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|[y\xFD][\s\xa0]*Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|[y\xFD][\s\xa0]*Paralipomenon|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))|1(?:[\s\xa0]*Kroni(?:ck[a\xE1]|k)|[\s\xa0]*Kron\xEDk|[\s\xa0]*Krn|Chr|[\s\xa0]*Kron|[\s\xa0]*Paralipomenon)|(?:1[\s\xa0]*k|I)[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:d(?:r[a\xE1][sš])?|ra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:emi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:r[e\xE9]cke[\s\xa0]*[cč]asti[\s\xa0]*knihy[\s\xa0]*Ester|kEsth)|Ester[\s\xa0]*gr)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*J[o\xF3]|[\s\xa0]*J[o\xF3]|niha[\s\xa0]*J[o\xF3])bova|J[o\xF3]b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[ZŽ]al(?:t[a\xE1]r|my)|Ps|[ZŽ](?:alm)?|K(?:\.[\s\xa0]*[zž]|[\s\xa0]*[zž]|niha[\s\xa0]*[zž])almov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarj[a\xE1][sš]ova[\s\xa0]*modlitba|PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*pr[i\xED]slov[i\xED]|[\s\xa0]*pr[i\xED]slov[i\xED]|niha[\s\xa0]*pr[i\xED]slov[i\xED])|Pr(?:[i\xED]slovia|ov|[i\xED]s)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kazate[lľ])|(?:K(?:[\s\xa0]*kazate[lľ]ova|az|\.[\s\xa0]*kazate[lľ]ova|niha[\s\xa0]*kazate[lľ]ova|oh(?:elet(?:[\s\xa0]*—[\s\xa0]*Kazate[lľ])?)?)|E(?:kleziastes|ccl))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Piese[nň][\s\xa0]*ml[a\xE1]dencov[\s\xa0]*v[\s\xa0]*ohnivej[\s\xa0]*peci|SgThree|Traja[\s\xa0]*ml[a\xE1]denci[\s\xa0]*v[\s\xa0]*rozp[a\xE1]lenej[\s\xa0]*peci)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Piese[nň][\s\xa0]*[SŠ]alam[u\xFA]nova)|(?:V(?:e[lľ]p(?:iese[nň][\s\xa0]*[SŠ]alam[u\xFA]nova)?|[lľ]p)|P(?:iese[nň][\s\xa0]*piesn[i\xED]|Š)|Song|Pies)|(?:Ve[lľ]piese[nň]|Piese[nň])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jer(?:emi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:chiel|k))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ho(?:ze[a\xE1][sš]|s)|Oz(?:e[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Joel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[A\xC1]m(?:os)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ob(?:ad(?:i[a\xE1][sš])?|edi[a\xE1][sš])|Abd(?:i[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:\xE1[sš]|a[hsš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mic(?:h(?:e[a\xE1][sš])?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:ah(?:um)?|\xE1hum))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:akuk)?|Ab(?:akuk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sof(?:oni[a\xE1][sš])?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:geus|eus)?|Hag(?:geus)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:ach(?:ari[a\xE1][sš])?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:achi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:[u\xFA][sš]a|t)|t|at[u\xFA][sš])|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Mat[u\xFA][sš]a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Marka|M(?:ar(?:ek|ka)|k|ark))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:uk(?:[a\xE1][sš]a|e)|k|uk[a\xE1][sš])|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Luk[a\xE1][sš]a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*J[a\xE1]nov)|(?:Prv(?:[y\xFD][\s\xa0]*J[a\xE1]nov[\s\xa0]*list|[y\xFD][\s\xa0]*list[\s\xa0]*J[a\xE1]nov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov)|(?:1[\s\xa0]*k|I)[\s\xa0]*J[a\xE1]nov|1(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*J[a\xE1]nov)|(?:Prv[y\xFD][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*J[a\xE1]nov)|(?:Druh(?:[y\xFD][\s\xa0]*J[a\xE1]nov[\s\xa0]*list|[y\xFD][\s\xa0]*list[\s\xa0]*J[a\xE1]nov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov)|(?:2[\s\xa0]*k|II)[\s\xa0]*J[a\xE1]nov|2(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*J[a\xE1]nov)|(?:Druh[y\xFD][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*J[a\xE1]nov)|(?:Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov|[\s\xa0]*J[a\xE1]nov[\s\xa0]*list)|\xED[\s\xa0]*J[a\xE1]nov[\s\xa0]*list)|(?:3[\s\xa0]*k|III)[\s\xa0]*J[a\xE1]nov|3(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*J[a\xE1]nov)|(?:Tret[i\xED][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:(?:oh)?n|[a\xE1]na|[a\xE1]n)|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*J[a\xE1]na)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sk(?:utky(?:[\s\xa0]*apo[sš]tolov)?)?|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Rimanom)|(?:(?:R(?:\xEDmsky|o|imsky|i)|List[\s\xa0]*Rimano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[y\xFD][\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|Korin(?:t(?:sk[y\xFD]|ano)|ťano)))m|2(?:[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:[\s\xa0]*K|C)or)|(?:2[\s\xa0]*k|II)[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[y\xFD][\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|Korin(?:t(?:sk[y\xFD]|ano)|ťano)))m|1(?:[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:[\s\xa0]*K|C)or)|(?:1[\s\xa0]*k|I)[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Gala[tť]anom)|(?:Ga(?:latsk[y\xFD]m|l)?|List[\s\xa0]*Gala[tť]anom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Efezanom)|(?:E(?:fezsk[y\xFD]m|ph|f)|List[\s\xa0]*Efezanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filipsk[y\xFD]m|Phil|Flp|Filipanom|List[\s\xa0]*Filipanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kolosanom)|(?:Kolosensk[y\xFD]m|[CK]ol|List[\s\xa0]*Kolosanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)|(?:Druh(?:[y\xFD][\s\xa0]*Sol[u\xFA]n[cč]ano|[y\xFD][\s\xa0]*Sol[u\xFA]nsky|[y\xFD][\s\xa0]*Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|[y\xFD][\s\xa0]*list[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky)))m|(?:2[\s\xa0]*k|II)[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m|2(?:[\s\xa0]*(?:Sol|Tes)|Thess)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)|(?:Prv(?:[y\xFD][\s\xa0]*Sol[u\xFA]n[cč]ano|[y\xFD][\s\xa0]*Sol[u\xFA]nsky|[y\xFD][\s\xa0]*Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|[y\xFD][\s\xa0]*list[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky)))m|(?:1[\s\xa0]*k|I)[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m|1(?:[\s\xa0]*(?:Sol|Tes)|Thess)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Timotej?|[y\xFD][\s\xa0]*Timotej?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Timotej?|Timotej?))ovi|2(?:[\s\xa0]*Timotej?ovi|[\s\xa0]*?Tim)|(?:2[\s\xa0]*k|II)[\s\xa0]*Timotej?ovi|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Timotej?ovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Timotej?|[y\xFD][\s\xa0]*Timotej?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Timotej?|Timotej?))ovi|1(?:[\s\xa0]*Timotej?ovi|[\s\xa0]*?Tim)|(?:1[\s\xa0]*k|I)[\s\xa0]*Timotej?ovi|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Timotej?ovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:it(?:ovi|us)|\xEDtovi))|(?:List[\s\xa0]*T[i\xED]tovi|T[i\xED]t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filemonovi)|(?:List[\s\xa0]*Filem[o\xF3]novi|(?:F(?:ile|l)|Phl)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Hebrej|[ZŽ]id)om)|(?:[ZŽ]id|Hebr|Heb|List[\s\xa0]*Hebrejom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:a(?:k(?:ubov(?:[\s\xa0]*List)?)?|s)|k))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*Petrov[\s\xa0]*list|[y\xFD][\s\xa0]*Petrov|[y\xFD][\s\xa0]*list[\s\xa0]*Petrov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Petrov)|2(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*Petrov)|(?:2[\s\xa0]*k|II)[\s\xa0]*Petrov|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Petrov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*Petrov[\s\xa0]*list|[y\xFD][\s\xa0]*Petrov|[y\xFD][\s\xa0]*list[\s\xa0]*Petrov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Petrov)|1(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*Petrov)|(?:1[\s\xa0]*k|I)[\s\xa0]*Petrov|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Petrov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:\xFAd(?:ov(?:[\s\xa0]*List)?)?|ud(?:ov(?:[\s\xa0]*List)?|e)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob(?:i[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:niha|\.)?[\s\xa0]*Juditina|J(?:udita|dt|udit))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Proroctvo[\s\xa0]*Baruchovo|Bar(?:uch)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zuzan[ae]|Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Ma(?:ch|k)abejcov|[\s\xa0]*Ma(?:ch|k)|Macc)|(?:2[\s\xa0]*k|II)[\s\xa0]*Ma(?:ch|k)abejcov|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Ma(?:ch|k)abejcov|Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ma(?:ch|k)|[y\xFD][\s\xa0]*Ma(?:ch|k)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ma(?:ch|k)|Ma(?:ch|k)))abejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Machabejcov)|(?:(?:3[\s\xa0]*k|III)[\s\xa0]*Machabejcov|3(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*Machabejcov|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*)?|[\s\xa0]*)|\xED[\s\xa0]*)Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Machabejcov)|(?:(?:4[\s\xa0]*k|IV)[\s\xa0]*Machabejcov|4(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:4(?:[\s\xa0]*k)?|IV)\.[\s\xa0]*Machabejcov|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Machabejcov)|(?:Prv(?:[a\xE1][\s\xa0]*(?:Ma(?:ch|k)|kniha[\s\xa0]*Mach)|(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*Mach)abejcov|(?:1[\s\xa0]*k|I)[\s\xa0]*Machabejcov|1(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| 144694 | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| title (?! [a-z] ) #could be followed by a number
| ver[šs]ov | kapitoly | kapitole | kapitolu | kapitol | hlavy | a[žz] | porov | pozri | alebo | kap | ff | - | a
| [b-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* title
| \d \W* ff (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [b-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Prv[áa]#{bcv_parser::regexps.space}+kniha|Prv[ýy]#{bcv_parser::regexps.space}+list|Prv[áa]|Prv[ýy]|1#{bcv_parser::regexps.space}+k|I|1)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Druh[áa]#{bcv_parser::regexps.space}+kniha|Druh[ýy]#{bcv_parser::regexps.space}+list|Druh[áa]|Druh[ýy]|2#{bcv_parser::regexps.space}+k|II|2)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Tretia#{bcv_parser::regexps.space}+kniha|Tretia|Tret[íi]|3#{bcv_parser::regexps.space}+k|III|3)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:porov|pozri|alebo|a)|(?:a[žz]|-))"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|(?:a[žz]|-))"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Moj[zž]i[sš]ova)|(?:K(?:\.[\s\xa0]*p[o\xF4]|[\s\xa0]*p[o\xF4]|niha[\s\xa0]*p[o\xF4])vodu|G(?:enezis|n)|1[\s\xa0]*M|Gen|K(?:niha|\.)?[\s\xa0]*stvorenia|(?:1[\s\xa0]*k|I)[\s\xa0]*Moj[zž]i[sš]ova|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Moj[zž]i[sš]ova|Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Moj[zž]i[sš]|[y\xFD][\s\xa0]*Moj[zž]i[sš]|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš]))ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Moj[zž]i[sš]ova|Exodus)|(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Moj[zž]i[sš]|[y\xFD][\s\xa0]*Moj[zž]i[sš]|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš]))ova|(?:2[\s\xa0]*k|II)[\s\xa0]*Moj[zž]i[sš]ova|Exod|2[\s\xa0]*M|Ex|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Moj[zž]i[sš]ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[e\xE9]l(?:[\s\xa0]*a[\s\xa0]*drak)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Moj[zž]i[sš]ova)|(?:(?:3[\s\xa0]*k|III)[\s\xa0]*Moj[zž]i[sš]ova|L(?:evitikus|v)|3[\s\xa0]*M|Lev|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*Moj[zž]i[sš]ova|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])|[\s\xa0]*Moj[zž]i[sš])|\xED[\s\xa0]*Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Moj[zž]i[sš]ova)|(?:(?:4[\s\xa0]*k|IV)[\s\xa0]*Moj[zž]i[sš]ova|N(?:umeri|m)|4[\s\xa0]*M|Num|(?:4(?:[\s\xa0]*k)?|IV)\.[\s\xa0]*Moj[zž]i[sš]ova|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus)|[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus)|niha[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus))|Sir(?:achovcova|achovec)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M[u\xFA]d(?:ros(?:ti?|ť))?|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*n[a\xE1]|[\s\xa0]*n[a\xE1]|niha[\s\xa0]*n[a\xE1])rekov|N[a\xE1]reky|Lam|[ZŽ]alospevy|Pla[cč][\s\xa0]*Jeremi[a\xE1][sš]ov|[ZŽ]alosp|N[a\xE1]r|Jeremi[a\xE1][sš]ov[\s\xa0]*Pla[cč])|(?:Pla[cč])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jeremi[a\xE1][sš]ov[\s\xa0]*list|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zj(?:av(?:enie(?:[\s\xa0]*(?:sv[a\xE4]t[e\xE9]ho[\s\xa0]*J[a\xE1]|J[a\xE1]|Apo[sš]tola[\s\xa0]*J[a\xE1])na)?)?|v)?|Apokalypsa|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Manasesova[\s\xa0]*modlitba|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:5[\s\xa0]*Moj[zž]i[sš]ova)|(?:D(?:euteron[o\xF3]mium|t)|5[\s\xa0]*M|Deut|(?:5[\s\xa0]*k|V)[\s\xa0]*Moj[zž]i[sš]ova|(?:5(?:[\s\xa0]*k)?|V)\.[\s\xa0]*Moj[zž]i[sš]ova|Piata[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o(?:z(?:u[ae]|uova)?|šu(?:ov)?a|s(?:u(?:ov)?a|h))|\xF3zu(?:ov)?a)|Iosua)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:udcovia|dc)|Judg|Sud(?:cov)?|K\.?[\s\xa0]*sudcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:\xFAt|uth?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[y\xFD][\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Ezdr[a\xE1][sš](?:ova)?))|(?:1[\s\xa0]*k|I)[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|1(?:[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Esd)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[y\xFD][\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Ezdr[a\xE1][sš](?:ova)?))|(?:2[\s\xa0]*k|II)[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|2(?:[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Esd)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:z(?:a[ij][a\xE1][sš])?|sa))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Samuelova)|(?:(?:2[\s\xa0]*k|II)[\s\xa0]*Samuelova|2(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Samuelova|Druh(?:(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?)Samuelova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Samuelova)|(?:(?:1[\s\xa0]*k|I)[\s\xa0]*Samuelova|1(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Samuelova|Prv(?:(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?)Samuelova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Kr[a\xE1][lľ]ov|[\s\xa0]*Kr[lľ]|Kgs|[\s\xa0]*Kr)|(?:Druh[y\xFD]|4)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:I[IV]|4[\s\xa0]*k|2[\s\xa0]*k)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:(?:I[IV]|4[\s\xa0]*k|4|2(?:[\s\xa0]*k)?)\.|Druh[y\xFD][\s\xa0]*list)[\s\xa0]*Kr[a\xE1][lľ]ov|Druh[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Kr[a\xE1][lľ]ov|[\s\xa0]*Kr[lľ]|Kgs|[\s\xa0]*Kr)|(?:Prv[y\xFD]|3)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:3[\s\xa0]*k|III|I|1[\s\xa0]*k)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:(?:3[\s\xa0]*k|III|[3I]|1(?:[\s\xa0]*k)?)\.|Prv[y\xFD][\s\xa0]*list)[\s\xa0]*Kr[a\xE1][lľ]ov|Prv[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])|[\s\xa0]*Kr[a\xE1][lľ])|\xED[\s\xa0]*Kr[a\xE1][lľ])ov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|[y\xFD][\s\xa0]*Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|[y\xFD][\s\xa0]*Paralipomenon|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))|2(?:[\s\xa0]*Kroni(?:ck[a\xE1]|k)|[\s\xa0]*Kron\xEDk|[\s\xa0]*Krn|Chr|[\s\xa0]*Kron|[\s\xa0]*Paralipomenon)|(?:2[\s\xa0]*k|II)[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|[y\xFD][\s\xa0]*Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|[y\xFD][\s\xa0]*Paralipomenon|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))|1(?:[\s\xa0]*Kroni(?:ck[a\xE1]|k)|[\s\xa0]*Kron\xEDk|[\s\xa0]*Krn|Chr|[\s\xa0]*Kron|[\s\xa0]*Paralipomenon)|(?:1[\s\xa0]*k|I)[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:d(?:r[a\xE1][sš])?|ra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:emi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:r[e\xE9]cke[\s\xa0]*[cč]asti[\s\xa0]*knihy[\s\xa0]*Ester|kEsth)|Ester[\s\xa0]*gr)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*J[o\xF3]|[\s\xa0]*J[o\xF3]|niha[\s\xa0]*J[o\xF3])bova|J[o\xF3]b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[ZŽ]al(?:t[a\xE1]r|my)|Ps|[ZŽ](?:alm)?|K(?:\.[\s\xa0]*[zž]|[\s\xa0]*[zž]|niha[\s\xa0]*[zž])almov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarj[a\xE1][sš]ova[\s\xa0]*modlitba|PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*pr[i\xED]slov[i\xED]|[\s\xa0]*pr[i\xED]slov[i\xED]|niha[\s\xa0]*pr[i\xED]slov[i\xED])|Pr(?:[i\xED]slovia|ov|[i\xED]s)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kazate[lľ])|(?:K(?:[\s\xa0]*kazate[lľ]ova|az|\.[\s\xa0]*kazate[lľ]ova|niha[\s\xa0]*kazate[lľ]ova|oh(?:elet(?:[\s\xa0]*—[\s\xa0]*Kazate[lľ])?)?)|E(?:kleziastes|ccl))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Piese[nň][\s\xa0]*ml[a\xE1]dencov[\s\xa0]*v[\s\xa0]*ohnivej[\s\xa0]*peci|SgThree|Traja[\s\xa0]*ml[a\xE1]denci[\s\xa0]*v[\s\xa0]*rozp[a\xE1]lenej[\s\xa0]*peci)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Piese[nň][\s\xa0]*[SŠ]alam[u\xFA]nova)|(?:V(?:e[lľ]p(?:iese[nň][\s\xa0]*[SŠ]alam[u\xFA]nova)?|[lľ]p)|P(?:iese[nň][\s\xa0]*piesn[i\xED]|Š)|Song|Pies)|(?:Ve[lľ]piese[nň]|Piese[nň])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jer(?:emi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:chiel|k))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ho(?:ze[a\xE1][sš]|s)|Oz(?:e[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:<NAME>el)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[A\xC1]m(?:os)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ob(?:ad(?:i[a\xE1][sš])?|edi[a\xE1][sš])|Abd(?:i[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:\xE1[sš]|a[hsš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mic(?:h(?:e[a\xE1][sš])?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:ah(?:um)?|\xE1hum))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:akuk)?|Ab(?:akuk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sof(?:oni[a\xE1][sš])?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:geus|eus)?|Hag(?:geus)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:ach(?:ari[a\xE1][sš])?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:achi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:[u\xFA][sš]a|t)|t|at[u\xFA][sš])|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Mat[u\xFA][sš]a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Marka|M(?:ar(?:ek|ka)|k|ark))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:uk(?:[a\xE1][sš]a|e)|k|uk[a\xE1][sš])|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Luk[a\xE1][sš]a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*J[a\xE1]nov)|(?:Prv(?:[y\xFD][\s\xa0]*J[a\xE1]nov[\s\xa0]*list|[y\xFD][\s\xa0]*list[\s\xa0]*J[a\xE1]nov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov)|(?:1[\s\xa0]*k|I)[\s\xa0]*J[a\xE1]nov|1(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*J[a\xE1]nov)|(?:Prv[y\xFD][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*J[a\xE1]nov)|(?:Druh(?:[y\xFD][\s\xa0]*J[a\xE1]nov[\s\xa0]*list|[y\xFD][\s\xa0]*list[\s\xa0]*J[a\xE1]nov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov)|(?:2[\s\xa0]*k|II)[\s\xa0]*J[a\xE1]nov|2(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*J[a\xE1]nov)|(?:Druh[y\xFD][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*J[a\xE1]nov)|(?:Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov|[\s\xa0]*J[a\xE1]nov[\s\xa0]*list)|\xED[\s\xa0]*J[a\xE1]nov[\s\xa0]*list)|(?:3[\s\xa0]*k|III)[\s\xa0]*J[a\xE1]nov|3(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*J[a\xE1]nov)|(?:Tret[i\xED][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:(?:oh)?n|[a\xE1]na|[a\xE1]n)|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*J[a\xE1]na)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sk(?:utky(?:[\s\xa0]*apo[sš]tolov)?)?|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Rimanom)|(?:(?:R(?:\xEDmsky|o|imsky|i)|List[\s\xa0]*Rimano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[y\xFD][\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|Korin(?:t(?:sk[y\xFD]|ano)|ťano)))m|2(?:[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:[\s\xa0]*K|C)or)|(?:2[\s\xa0]*k|II)[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[y\xFD][\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|Korin(?:t(?:sk[y\xFD]|ano)|ťano)))m|1(?:[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:[\s\xa0]*K|C)or)|(?:1[\s\xa0]*k|I)[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Gala[tť]anom)|(?:Ga(?:latsk[y\xFD]m|l)?|List[\s\xa0]*Gala[tť]anom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Efezanom)|(?:E(?:fezsk[y\xFD]m|ph|f)|List[\s\xa0]*Efezanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filipsk[y\xFD]m|Phil|Flp|Filipanom|List[\s\xa0]*Filipanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kolosanom)|(?:Kolosensk[y\xFD]m|[CK]ol|List[\s\xa0]*Kolosanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)|(?:Druh(?:[y\xFD][\s\xa0]*Sol[u\xFA]n[cč]ano|[y\xFD][\s\xa0]*Sol[u\xFA]nsky|[y\xFD][\s\xa0]*Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|[y\xFD][\s\xa0]*list[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky)))m|(?:2[\s\xa0]*k|II)[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m|2(?:[\s\xa0]*(?:Sol|Tes)|Thess)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)|(?:Prv(?:[y\xFD][\s\xa0]*Sol[u\xFA]n[cč]ano|[y\xFD][\s\xa0]*Sol[u\xFA]nsky|[y\xFD][\s\xa0]*Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|[y\xFD][\s\xa0]*list[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky)))m|(?:1[\s\xa0]*k|I)[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m|1(?:[\s\xa0]*(?:Sol|Tes)|Thess)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Timotej?|[y\xFD][\s\xa0]*Timotej?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Timotej?|Timotej?))ovi|2(?:[\s\xa0]*Timotej?ovi|[\s\xa0]*?Tim)|(?:2[\s\xa0]*k|II)[\s\xa0]*Timotej?ovi|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Timotej?ovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Timotej?|[y\xFD][\s\xa0]*Timotej?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Timotej?|Timotej?))ovi|1(?:[\s\xa0]*Timotej?ovi|[\s\xa0]*?Tim)|(?:1[\s\xa0]*k|I)[\s\xa0]*Timotej?ovi|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Timotej?ovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:it(?:ovi|us)|\xEDtovi))|(?:List[\s\xa0]*T[i\xED]tovi|T[i\xED]t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filemonovi)|(?:List[\s\xa0]*Filem[o\xF3]novi|(?:F(?:ile|l)|Phl)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Hebrej|[ZŽ]id)om)|(?:[ZŽ]id|Hebr|Heb|List[\s\xa0]*Hebrejom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:a(?:k(?:ubov(?:[\s\xa0]*List)?)?|s)|k))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*Petrov[\s\xa0]*list|[y\xFD][\s\xa0]*Petrov|[y\xFD][\s\xa0]*list[\s\xa0]*Petrov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Petrov)|2(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*Petrov)|(?:2[\s\xa0]*k|II)[\s\xa0]*Petrov|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Petrov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*Petrov[\s\xa0]*list|[y\xFD][\s\xa0]*Petrov|[y\xFD][\s\xa0]*list[\s\xa0]*Petrov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Petrov)|1(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*Petrov)|(?:1[\s\xa0]*k|I)[\s\xa0]*Petrov|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Petrov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:\xFAd(?:ov(?:[\s\xa0]*List)?)?|ud(?:ov(?:[\s\xa0]*List)?|e)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob(?:i[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:niha|\.)?[\s\xa0]*Juditina|J(?:udita|dt|udit))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Proroctvo[\s\xa0]*Baruchovo|Bar(?:uch)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zuzan[ae]|Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Ma(?:ch|k)abejcov|[\s\xa0]*Ma(?:ch|k)|Macc)|(?:2[\s\xa0]*k|II)[\s\xa0]*Ma(?:ch|k)abejcov|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Ma(?:ch|k)abejcov|Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ma(?:ch|k)|[y\xFD][\s\xa0]*Ma(?:ch|k)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ma(?:ch|k)|Ma(?:ch|k)))abejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Machabejcov)|(?:(?:3[\s\xa0]*k|III)[\s\xa0]*Machabejcov|3(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*Machabejcov|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*)?|[\s\xa0]*)|\xED[\s\xa0]*)Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Machabejcov)|(?:(?:4[\s\xa0]*k|IV)[\s\xa0]*Machabejcov|4(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:4(?:[\s\xa0]*k)?|IV)\.[\s\xa0]*Machabejcov|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Machabejcov)|(?:Prv(?:[a\xE1][\s\xa0]*(?:Ma(?:ch|k)|kniha[\s\xa0]*Mach)|(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*Mach)abejcov|(?:1[\s\xa0]*k|I)[\s\xa0]*Machabejcov|1(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
| true | bcv_parser::regexps.space = "[\\s\\xa0]"
bcv_parser::regexps.escaped_passage = ///
(?:^ | [^\x1f\x1e\dA-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ] ) # Beginning of string or not in the middle of a word or immediately following another book. Only count a book if it's part of a sequence: `Matt5John3` is OK, but not `1Matt5John3`
(
# Start inverted book/chapter (cb)
(?:
(?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s* (?: [\u2013\u2014\-] | through | thru | to) \s* \d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: ch (?: apters? | a?pts?\.? | a?p?s?\.? )? \s*
\d+ \s*
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )?\s* )
| (?: \d+ (?: th | nd | st ) \s*
ch (?: apter | a?pt\.? | a?p?\.? )? \s* #no plurals here since it's a single chapter
(?: from | of | in ) (?: \s+ the \s+ book \s+ of )? \s* )
)? # End inverted book/chapter (cb)
\x1f(\d+)(?:/\d+)?\x1f #book
(?:
/\d+\x1f #special Psalm chapters
| [\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014]
| title (?! [a-z] ) #could be followed by a number
| ver[šs]ov | kapitoly | kapitole | kapitolu | kapitol | hlavy | a[žz] | porov | pozri | alebo | kap | ff | - | a
| [b-e] (?! \w ) #a-e allows 1:1a
| $ #or the end of the string
)+
)
///gi
# These are the only valid ways to end a potential passage match. The closing parenthesis allows for fully capturing parentheses surrounding translations (ESV**)**. The last one, `[\d\x1f]` needs not to be +; otherwise `Gen5ff` becomes `\x1f0\x1f5ff`, and `adjust_regexp_end` matches the `\x1f5` and incorrectly dangles the ff.
bcv_parser::regexps.match_end_split = ///
\d \W* title
| \d \W* ff (?: [\s\xa0*]* \.)?
| \d [\s\xa0*]* [b-e] (?! \w )
| \x1e (?: [\s\xa0*]* [)\]\uff09] )? #ff09 is a full-width closing parenthesis
| [\d\x1f]
///gi
bcv_parser::regexps.control = /[\x1e\x1f]/g
bcv_parser::regexps.pre_book = "[^A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ]"
bcv_parser::regexps.first = "(?:Prv[áa]#{bcv_parser::regexps.space}+kniha|Prv[ýy]#{bcv_parser::regexps.space}+list|Prv[áa]|Prv[ýy]|1#{bcv_parser::regexps.space}+k|I|1)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:Druh[áa]#{bcv_parser::regexps.space}+kniha|Druh[ýy]#{bcv_parser::regexps.space}+list|Druh[áa]|Druh[ýy]|2#{bcv_parser::regexps.space}+k|II|2)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:Tretia#{bcv_parser::regexps.space}+kniha|Tretia|Tret[íi]|3#{bcv_parser::regexps.space}+k|III|3)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|(?:porov|pozri|alebo|a)|(?:a[žz]|-))"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|(?:a[žz]|-))"
# Each book regexp should return two parenthesized objects: an optional preliminary character and the book itself.
bcv_parser::regexps.get_books = (include_apocrypha, case_sensitive) ->
books = [
osis: ["Ps"]
apocrypha: true
extra: "2"
regexp: ///(\b)( # Don't match a preceding \d like usual because we only want to match a valid OSIS, which will never have a preceding digit.
Ps151
# Always follwed by ".1"; the regular Psalms parser can handle `Ps151` on its own.
)(?=\.1)///g # Case-sensitive because we only want to match a valid OSIS.
,
osis: ["Gen"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Moj[zž]i[sš]ova)|(?:K(?:\.[\s\xa0]*p[o\xF4]|[\s\xa0]*p[o\xF4]|niha[\s\xa0]*p[o\xF4])vodu|G(?:enezis|n)|1[\s\xa0]*M|Gen|K(?:niha|\.)?[\s\xa0]*stvorenia|(?:1[\s\xa0]*k|I)[\s\xa0]*Moj[zž]i[sš]ova|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Moj[zž]i[sš]ova|Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Moj[zž]i[sš]|[y\xFD][\s\xa0]*Moj[zž]i[sš]|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš]))ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Moj[zž]i[sš]ova|Exodus)|(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Moj[zž]i[sš]|[y\xFD][\s\xa0]*Moj[zž]i[sš]|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš]))ova|(?:2[\s\xa0]*k|II)[\s\xa0]*Moj[zž]i[sš]ova|Exod|2[\s\xa0]*M|Ex|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Moj[zž]i[sš]ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[e\xE9]l(?:[\s\xa0]*a[\s\xa0]*drak)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Moj[zž]i[sš]ova)|(?:(?:3[\s\xa0]*k|III)[\s\xa0]*Moj[zž]i[sš]ova|L(?:evitikus|v)|3[\s\xa0]*M|Lev|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*Moj[zž]i[sš]ova|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])|[\s\xa0]*Moj[zž]i[sš])|\xED[\s\xa0]*Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Moj[zž]i[sš]ova)|(?:(?:4[\s\xa0]*k|IV)[\s\xa0]*Moj[zž]i[sš]ova|N(?:umeri|m)|4[\s\xa0]*M|Num|(?:4(?:[\s\xa0]*k)?|IV)\.[\s\xa0]*Moj[zž]i[sš]ova|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus)|[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus)|niha[\s\xa0]*(?:Sirachov(?:c(?:ov)?|ho[\s\xa0]*syn)a|Ekleziastikus))|Sir(?:achovcova|achovec)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M[u\xFA]d(?:ros(?:ti?|ť))?|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*n[a\xE1]|[\s\xa0]*n[a\xE1]|niha[\s\xa0]*n[a\xE1])rekov|N[a\xE1]reky|Lam|[ZŽ]alospevy|Pla[cč][\s\xa0]*Jeremi[a\xE1][sš]ov|[ZŽ]alosp|N[a\xE1]r|Jeremi[a\xE1][sš]ov[\s\xa0]*Pla[cč])|(?:Pla[cč])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jeremi[a\xE1][sš]ov[\s\xa0]*list|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zj(?:av(?:enie(?:[\s\xa0]*(?:sv[a\xE4]t[e\xE9]ho[\s\xa0]*J[a\xE1]|J[a\xE1]|Apo[sš]tola[\s\xa0]*J[a\xE1])na)?)?|v)?|Apokalypsa|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Manasesova[\s\xa0]*modlitba|PrMan)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:5[\s\xa0]*Moj[zž]i[sš]ova)|(?:D(?:euteron[o\xF3]mium|t)|5[\s\xa0]*M|Deut|(?:5[\s\xa0]*k|V)[\s\xa0]*Moj[zž]i[sš]ova|(?:5(?:[\s\xa0]*k)?|V)\.[\s\xa0]*Moj[zž]i[sš]ova|Piata[\s\xa0]*(?:kniha[\s\xa0]*Moj[zž]i[sš]|Moj[zž]i[sš])ova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:o(?:z(?:u[ae]|uova)?|šu(?:ov)?a|s(?:u(?:ov)?a|h))|\xF3zu(?:ov)?a)|Iosua)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:udcovia|dc)|Judg|Sud(?:cov)?|K\.?[\s\xa0]*sudcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:R(?:\xFAt|uth?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[y\xFD][\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Ezdr[a\xE1][sš](?:ova)?))|(?:1[\s\xa0]*k|I)[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|1(?:[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Esd)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[y\xFD][\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Ezdr[a\xE1][sš](?:ova)?))|(?:2[\s\xa0]*k|II)[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|2(?:[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?|Esd)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Ezdr[a\xE1][sš](?:ova)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:I(?:z(?:a[ij][a\xE1][sš])?|sa))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*Samuelova)|(?:(?:2[\s\xa0]*k|II)[\s\xa0]*Samuelova|2(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Samuelova|Druh(?:(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?)Samuelova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Samuelova)|(?:(?:1[\s\xa0]*k|I)[\s\xa0]*Samuelova|1(?:[\s\xa0]*?Sam|[\s\xa0]*S)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Samuelova|Prv(?:(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?)Samuelova)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Kr[a\xE1][lľ]ov|[\s\xa0]*Kr[lľ]|Kgs|[\s\xa0]*Kr)|(?:Druh[y\xFD]|4)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:I[IV]|4[\s\xa0]*k|2[\s\xa0]*k)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:(?:I[IV]|4[\s\xa0]*k|4|2(?:[\s\xa0]*k)?)\.|Druh[y\xFD][\s\xa0]*list)[\s\xa0]*Kr[a\xE1][lľ]ov|Druh[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Kr[a\xE1][lľ]ov|[\s\xa0]*Kr[lľ]|Kgs|[\s\xa0]*Kr)|(?:Prv[y\xFD]|3)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:3[\s\xa0]*k|III|I|1[\s\xa0]*k)[\s\xa0]*Kr[a\xE1][lľ]ov|(?:(?:3[\s\xa0]*k|III|[3I]|1(?:[\s\xa0]*k)?)\.|Prv[y\xFD][\s\xa0]*list)[\s\xa0]*Kr[a\xE1][lľ]ov|Prv[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])ov|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*Kr[a\xE1][lľ]|Kr[a\xE1][lľ])|[\s\xa0]*Kr[a\xE1][lľ])|\xED[\s\xa0]*Kr[a\xE1][lľ])ov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|[y\xFD][\s\xa0]*Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|[y\xFD][\s\xa0]*Paralipomenon|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))|2(?:[\s\xa0]*Kroni(?:ck[a\xE1]|k)|[\s\xa0]*Kron\xEDk|[\s\xa0]*Krn|Chr|[\s\xa0]*Kron|[\s\xa0]*Paralipomenon)|(?:2[\s\xa0]*k|II)[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|[y\xFD][\s\xa0]*Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|[y\xFD][\s\xa0]*Paralipomenon|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))|1(?:[\s\xa0]*Kroni(?:ck[a\xE1]|k)|[\s\xa0]*Kron\xEDk|[\s\xa0]*Krn|Chr|[\s\xa0]*Kron|[\s\xa0]*Paralipomenon)|(?:1[\s\xa0]*k|I)[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*(?:Kron(?:i(?:ck[a\xE1]|k)|\xEDk)|Paralipomenon))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:d(?:r[a\xE1][sš])?|ra))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:emi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:r[e\xE9]cke[\s\xa0]*[cč]asti[\s\xa0]*knihy[\s\xa0]*Ester|kEsth)|Ester[\s\xa0]*gr)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Esth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Est(?:er|h)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Job"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*J[o\xF3]|[\s\xa0]*J[o\xF3]|niha[\s\xa0]*J[o\xF3])bova|J[o\xF3]b)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[ZŽ]al(?:t[a\xE1]r|my)|Ps|[ZŽ](?:alm)?|K(?:\.[\s\xa0]*[zž]|[\s\xa0]*[zž]|niha[\s\xa0]*[zž])almov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarj[a\xE1][sš]ova[\s\xa0]*modlitba|PrAzar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:\.[\s\xa0]*pr[i\xED]slov[i\xED]|[\s\xa0]*pr[i\xED]slov[i\xED]|niha[\s\xa0]*pr[i\xED]slov[i\xED])|Pr(?:[i\xED]slovia|ov|[i\xED]s)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kazate[lľ])|(?:K(?:[\s\xa0]*kazate[lľ]ova|az|\.[\s\xa0]*kazate[lľ]ova|niha[\s\xa0]*kazate[lľ]ova|oh(?:elet(?:[\s\xa0]*—[\s\xa0]*Kazate[lľ])?)?)|E(?:kleziastes|ccl))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Piese[nň][\s\xa0]*ml[a\xE1]dencov[\s\xa0]*v[\s\xa0]*ohnivej[\s\xa0]*peci|SgThree|Traja[\s\xa0]*ml[a\xE1]denci[\s\xa0]*v[\s\xa0]*rozp[a\xE1]lenej[\s\xa0]*peci)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Piese[nň][\s\xa0]*[SŠ]alam[u\xFA]nova)|(?:V(?:e[lľ]p(?:iese[nň][\s\xa0]*[SŠ]alam[u\xFA]nova)?|[lľ]p)|P(?:iese[nň][\s\xa0]*piesn[i\xED]|Š)|Song|Pies)|(?:Ve[lľ]piese[nň]|Piese[nň])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jer(?:emi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ez(?:e(?:chiel|k))?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:iel)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ho(?:ze[a\xE1][sš]|s)|Oz(?:e[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:PI:NAME:<NAME>END_PIel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[A\xC1]m(?:os)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ob(?:ad(?:i[a\xE1][sš])?|edi[a\xE1][sš])|Abd(?:i[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Jon(?:\xE1[sš]|a[hsš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mic(?:h(?:e[a\xE1][sš])?)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:N(?:ah(?:um)?|\xE1hum))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:akuk)?|Ab(?:akuk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sof(?:oni[a\xE1][sš])?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ag(?:geus|eus)?|Hag(?:geus)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Z(?:ach(?:ari[a\xE1][sš])?|ech))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:achi[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:at(?:[u\xFA][sš]a|t)|t|at[u\xFA][sš])|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Mat[u\xFA][sš]a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Marka|M(?:ar(?:ek|ka)|k|ark))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:L(?:uk(?:[a\xE1][sš]a|e)|k|uk[a\xE1][sš])|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*Luk[a\xE1][sš]a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*J[a\xE1]nov)|(?:Prv(?:[y\xFD][\s\xa0]*J[a\xE1]nov[\s\xa0]*list|[y\xFD][\s\xa0]*list[\s\xa0]*J[a\xE1]nov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov)|(?:1[\s\xa0]*k|I)[\s\xa0]*J[a\xE1]nov|1(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*J[a\xE1]nov)|(?:Prv[y\xFD][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*J[a\xE1]nov)|(?:Druh(?:[y\xFD][\s\xa0]*J[a\xE1]nov[\s\xa0]*list|[y\xFD][\s\xa0]*list[\s\xa0]*J[a\xE1]nov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov)|(?:2[\s\xa0]*k|II)[\s\xa0]*J[a\xE1]nov|2(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*J[a\xE1]nov)|(?:Druh[y\xFD][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*J[a\xE1]nov)|(?:Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*J[a\xE1]|J[a\xE1])nov|[\s\xa0]*J[a\xE1]nov[\s\xa0]*list)|\xED[\s\xa0]*J[a\xE1]nov[\s\xa0]*list)|(?:3[\s\xa0]*k|III)[\s\xa0]*J[a\xE1]nov|3(?:(?:Joh|[\s\xa0]*J)n|[\s\xa0]*J)|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*J[a\xE1]nov)|(?:Tret[i\xED][\s\xa0]*J[a\xE1]nov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:(?:oh)?n|[a\xE1]na|[a\xE1]n)|Evanjelium[\s\xa0]*Pod[lľ]a[\s\xa0]*J[a\xE1]na)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sk(?:utky(?:[\s\xa0]*apo[sš]tolov)?)?|Acts)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Rimanom)|(?:(?:R(?:\xEDmsky|o|imsky|i)|List[\s\xa0]*Rimano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[y\xFD][\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|Korin(?:t(?:sk[y\xFD]|ano)|ťano)))m|2(?:[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:[\s\xa0]*K|C)or)|(?:2[\s\xa0]*k|II)[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[y\xFD][\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)|Korin(?:t(?:sk[y\xFD]|ano)|ťano)))m|1(?:[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:[\s\xa0]*K|C)or)|(?:1[\s\xa0]*k|I)[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Korin(?:t(?:sk[y\xFD]|ano)|ťano)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Gala[tť]anom)|(?:Ga(?:latsk[y\xFD]m|l)?|List[\s\xa0]*Gala[tť]anom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Efezanom)|(?:E(?:fezsk[y\xFD]m|ph|f)|List[\s\xa0]*Efezanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filipsk[y\xFD]m|Phil|Flp|Filipanom|List[\s\xa0]*Filipanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kolosanom)|(?:Kolosensk[y\xFD]m|[CK]ol|List[\s\xa0]*Kolosanom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)|(?:Druh(?:[y\xFD][\s\xa0]*Sol[u\xFA]n[cč]ano|[y\xFD][\s\xa0]*Sol[u\xFA]nsky|[y\xFD][\s\xa0]*Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|[y\xFD][\s\xa0]*list[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky)))m|(?:2[\s\xa0]*k|II)[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m|2(?:[\s\xa0]*(?:Sol|Tes)|Thess)|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)|(?:Prv(?:[y\xFD][\s\xa0]*Sol[u\xFA]n[cč]ano|[y\xFD][\s\xa0]*Sol[u\xFA]nsky|[y\xFD][\s\xa0]*Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|[y\xFD][\s\xa0]*list[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))|Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky)))m|(?:1[\s\xa0]*k|I)[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m|1(?:[\s\xa0]*(?:Sol|Tes)|Thess)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*(?:Tesaloni(?:c(?:k[y\xFD]|ano)|čano)|Sol(?:[u\xFA]n[cč]ano|[u\xFA]nsky))m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Timotej?|[y\xFD][\s\xa0]*Timotej?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Timotej?|Timotej?))ovi|2(?:[\s\xa0]*Timotej?ovi|[\s\xa0]*?Tim)|(?:2[\s\xa0]*k|II)[\s\xa0]*Timotej?ovi|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Timotej?ovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*list[\s\xa0]*Timotej?|[y\xFD][\s\xa0]*Timotej?|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Timotej?|Timotej?))ovi|1(?:[\s\xa0]*Timotej?ovi|[\s\xa0]*?Tim)|(?:1[\s\xa0]*k|I)[\s\xa0]*Timotej?ovi|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Timotej?ovi)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T(?:it(?:ovi|us)|\xEDtovi))|(?:List[\s\xa0]*T[i\xED]tovi|T[i\xED]t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Filemonovi)|(?:List[\s\xa0]*Filem[o\xF3]novi|(?:F(?:ile|l)|Phl)m)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Hebrej|[ZŽ]id)om)|(?:[ZŽ]id|Hebr|Heb|List[\s\xa0]*Hebrejom)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:a(?:k(?:ubov(?:[\s\xa0]*List)?)?|s)|k))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Druh(?:[y\xFD][\s\xa0]*Petrov[\s\xa0]*list|[y\xFD][\s\xa0]*Petrov|[y\xFD][\s\xa0]*list[\s\xa0]*Petrov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Petrov)|2(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*Petrov)|(?:2[\s\xa0]*k|II)[\s\xa0]*Petrov|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Petrov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:Prv(?:[y\xFD][\s\xa0]*Petrov[\s\xa0]*list|[y\xFD][\s\xa0]*Petrov|[y\xFD][\s\xa0]*list[\s\xa0]*Petrov|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Petrov)|1(?:(?:[\s\xa0]*P|Pe)t|[\s\xa0]*Petrov)|(?:1[\s\xa0]*k|I)[\s\xa0]*Petrov|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Petrov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:J(?:\xFAd(?:ov(?:[\s\xa0]*List)?)?|ud(?:ov(?:[\s\xa0]*List)?|e)?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob(?:i[a\xE1][sš])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:K(?:niha|\.)?[\s\xa0]*Juditina|J(?:udita|dt|udit))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Proroctvo[\s\xa0]*Baruchovo|Bar(?:uch)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Zuzan[ae]|Sus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Ma(?:ch|k)abejcov|[\s\xa0]*Ma(?:ch|k)|Macc)|(?:2[\s\xa0]*k|II)[\s\xa0]*Ma(?:ch|k)abejcov|(?:2(?:[\s\xa0]*k)?|II)\.[\s\xa0]*Ma(?:ch|k)abejcov|Druh(?:[y\xFD][\s\xa0]*list[\s\xa0]*Ma(?:ch|k)|[y\xFD][\s\xa0]*Ma(?:ch|k)|[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*Ma(?:ch|k)|Ma(?:ch|k)))abejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3[\s\xa0]*Machabejcov)|(?:(?:3[\s\xa0]*k|III)[\s\xa0]*Machabejcov|3(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:3(?:[\s\xa0]*k)?|III)\.[\s\xa0]*Machabejcov|Tret(?:i(?:a[\s\xa0]*(?:kniha[\s\xa0]*)?|[\s\xa0]*)|\xED[\s\xa0]*)Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:4[\s\xa0]*Machabejcov)|(?:(?:4[\s\xa0]*k|IV)[\s\xa0]*Machabejcov|4(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:4(?:[\s\xa0]*k)?|IV)\.[\s\xa0]*Machabejcov|[SŠ]tvrt[a\xE1][\s\xa0]*(?:kniha[\s\xa0]*)?Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1[\s\xa0]*Machabejcov)|(?:Prv(?:[a\xE1][\s\xa0]*(?:Ma(?:ch|k)|kniha[\s\xa0]*Mach)|(?:[y\xFD][\s\xa0]*list|[y\xFD])[\s\xa0]*Mach)abejcov|(?:1[\s\xa0]*k|I)[\s\xa0]*Machabejcov|1(?:[\s\xa0]*Ma(?:ch|k)|Macc)|(?:1(?:[\s\xa0]*k)?|I)\.[\s\xa0]*Machabejcov)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
]
# Short-circuit the look if we know we want all the books.
return books if include_apocrypha is true and case_sensitive is "none"
# Filter out books in the Apocrypha if we don't want them. `Array.map` isn't supported below IE9.
out = []
for book in books
continue if include_apocrypha is false and book.apocrypha? and book.apocrypha is true
if case_sensitive is "books"
book.regexp = new RegExp book.regexp.source, "g"
out.push book
out
# Default to not using the Apocrypha
bcv_parser::regexps.books = bcv_parser::regexps.get_books false, "none"
|
[
{
"context": "{}\n\n for stack in app.routeStack\n apiKey = \"#{stack.ctrl}.#{stack.action}\".toLowerCase()\n a",
"end": 428,
"score": 0.9103264212608337,
"start": 425,
"tag": "KEY",
"value": "\"#{"
},
{
"context": "ack in app.routeStack\n apiKey = \"#{stack.ctrl}.#{stack.action}\".toLowerCase()\n apis[apiKey] or",
"end": 442,
"score": 0.9748404026031494,
"start": 440,
"tag": "KEY",
"value": "#{"
},
{
"context": "Stack\n apiKey = \"#{stack.ctrl}.#{stack.action}\".toLowerCase()\n apis[apiKey] or=\n path: stack.path\n ",
"end": 470,
"score": 0.9914608597755432,
"start": 457,
"tag": "KEY",
"value": "toLowerCase()"
}
] | talk-api2x/server/controllers/discover.coffee | ikingye/talk-os | 3,084 | app = require '../server'
config = require 'config'
striker = require '../components/striker'
util = require '../util'
limbo = require 'limbo'
{
TeamModel
} = limbo.use 'talk'
module.exports = discoverController = app.controller 'discover', ->
@ratelimit '20', only: 'urlMeta'
@ensure 'url', only: 'urlMeta'
@action 'index', (req, res, callback) ->
apis = {}
for stack in app.routeStack
apiKey = "#{stack.ctrl}.#{stack.action}".toLowerCase()
apis[apiKey] or=
path: stack.path
method: stack.method
callback null, apis
@action 'strikerToken', (req, res, callback) ->
callback null, token: striker.signAuth()
@action 'urlMeta', (req, res, callback) ->
{url} = req.get()
url = 'http://' + url unless url.indexOf('http') is 0
util.fetchUrlMetas url
.timeout 5000
.nodeify callback
@action 'toTeam', (req, res, callback) ->
{shortName} = req.get()
TeamModel.findOne shortName: shortName, (err, team) ->
if team?._id
return res.redirect 302, util.buildTeamUrl(team._id)
else
return res.redirect 302, util.buildIndexUrl()
| 12818 | app = require '../server'
config = require 'config'
striker = require '../components/striker'
util = require '../util'
limbo = require 'limbo'
{
TeamModel
} = limbo.use 'talk'
module.exports = discoverController = app.controller 'discover', ->
@ratelimit '20', only: 'urlMeta'
@ensure 'url', only: 'urlMeta'
@action 'index', (req, res, callback) ->
apis = {}
for stack in app.routeStack
apiKey = <KEY>stack.ctrl}.<KEY>stack.action}".<KEY>
apis[apiKey] or=
path: stack.path
method: stack.method
callback null, apis
@action 'strikerToken', (req, res, callback) ->
callback null, token: striker.signAuth()
@action 'urlMeta', (req, res, callback) ->
{url} = req.get()
url = 'http://' + url unless url.indexOf('http') is 0
util.fetchUrlMetas url
.timeout 5000
.nodeify callback
@action 'toTeam', (req, res, callback) ->
{shortName} = req.get()
TeamModel.findOne shortName: shortName, (err, team) ->
if team?._id
return res.redirect 302, util.buildTeamUrl(team._id)
else
return res.redirect 302, util.buildIndexUrl()
| true | app = require '../server'
config = require 'config'
striker = require '../components/striker'
util = require '../util'
limbo = require 'limbo'
{
TeamModel
} = limbo.use 'talk'
module.exports = discoverController = app.controller 'discover', ->
@ratelimit '20', only: 'urlMeta'
@ensure 'url', only: 'urlMeta'
@action 'index', (req, res, callback) ->
apis = {}
for stack in app.routeStack
apiKey = PI:KEY:<KEY>END_PIstack.ctrl}.PI:KEY:<KEY>END_PIstack.action}".PI:KEY:<KEY>END_PI
apis[apiKey] or=
path: stack.path
method: stack.method
callback null, apis
@action 'strikerToken', (req, res, callback) ->
callback null, token: striker.signAuth()
@action 'urlMeta', (req, res, callback) ->
{url} = req.get()
url = 'http://' + url unless url.indexOf('http') is 0
util.fetchUrlMetas url
.timeout 5000
.nodeify callback
@action 'toTeam', (req, res, callback) ->
{shortName} = req.get()
TeamModel.findOne shortName: shortName, (err, team) ->
if team?._id
return res.redirect 302, util.buildTeamUrl(team._id)
else
return res.redirect 302, util.buildIndexUrl()
|
[
{
"context": "ep.equals(a, b)\n\n a = \"Hello\"\n b = \"Goodbye\"\n assert !deep.equals(a, b)\n\n a = false",
"end": 2733,
"score": 0.6564573645591736,
"start": 2730,
"tag": "NAME",
"value": "bye"
}
] | coffee/test/deep.test.coffee | jeffomatic/deep | 3 | _ = require('underscore')
assert = require('assert')
testHelper = require('./test_helper')
deep = require('../lib/deep')
describe 'deep module', () ->
describe 'isPlainObject()', () ->
it 'object literals are plain objects', (done) ->
assert deep.isPlainObject({})
done()
it 'objects created with `new Object` are plain objects', (done) ->
assert deep.isPlainObject(new Object)
done()
it 'global is a plain object', (done) ->
assert deep.isPlainObject(global)
done()
it 'arrays are not plain objects', (done) ->
assert !deep.isPlainObject([])
done()
it 'functions are not plain objects', (done) ->
assert !deep.isPlainObject(() ->)
done()
it 'Buffers are not plain objects', (done) ->
assert !deep.isPlainObject(new Buffer(1))
done()
it 'Custom objects are not plain objects', (done) ->
Foobar = () ->
assert !deep.isPlainObject(new Foobar)
done()
describe 'clone()', () ->
beforeEach (done) ->
class Foobar
@original =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
new Buffer(1)
{
foo: 'bar'
foobar: new Foobar
}
]
obj:
a: [
{
b: {
c: []
}
}
]
z: 'just a string!'
@clone = deep.clone(@original)
done()
it 'should generate new plain objects and arrays', (done) ->
@clone.obj.a[0].b.c.push 0
assert.notEqual @clone.obj.a[0].b.c.length, @original.obj.a[0].b.c.length
@clone.arr[4].bar = 'foo'
assert !@original.arr[4].bar?
done()
it 'should preserve references to functions', (done) ->
assert.equal @clone.arr[0], @original.arr[0]
done()
it 'should preserve references to Buffers', (done) ->
assert.equal @clone.arr[3].constructor.name, 'Buffer'
assert.equal @clone.arr[3], @original.arr[3]
done()
it 'should preserve references to custom objects', (done) ->
assert.equal @clone.arr[4].foobar.constructor.name, 'Foobar'
assert.equal @clone.arr[4].foobar, @original.arr[4].foobar
done()
describe 'equals()', () ->
it 'should return true for scalar data that are identical', ->
a = 1
b = 1
assert deep.equals(a, b)
a = "Hello"
b = "Hello"
assert deep.equals(a, b)
a = false
b = false
assert deep.equals(a, b)
it 'should return false for scalar data that are different', ->
a = 1
b = 2
assert !deep.equals(a, b)
a = "Hello"
b = "Goodbye"
assert !deep.equals(a, b)
a = false
b = true
assert !deep.equals(a, b)
it 'should return true for matching references to non-plain objects', ->
klass = (@v) ->
a = b = new klass("Hello")
assert deep.equals(a, b)
it 'should return false for non-matching references to similar non-plain objects', ->
klass = (@v) ->
a = new klass("Hello")
b = new klass("Hello")
assert !deep.equals(a, b)
it 'should return true for simple plain objects that are identical', ->
a = x: 1, y: 2
b = x: 1, y: 2
assert deep.equals(a, b)
it 'should return true for simple plain objects that are identical except for order', ->
a = x: 1; a.y = 2
b = y: 2; b.x = 1
assert deep.equals(a, b)
it 'should return false for simple plain objects that differ', ->
a = x: 1, y: 2
b = x: 1, y: 3
assert !deep.equals(a, b)
it 'should return true for arrays that are identical', ->
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
assert deep.equals(a, b)
it 'should return false for arrays that are identical except for order', ->
a = [1, 2, 3, 4]
b = [1, 2, 4, 3]
assert !deep.equals(a, b)
it 'should return false for arrays that differ in length', ->
a = [1, 2, 3, 4]
b = [1, 2, 3]
assert !deep.equals(a, b)
it 'should return false for arrays that differ in content', ->
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
assert !deep.equals(a, b)
it 'should return true for deeply nested content that is identical', ->
klass = (@v) ->
obj1 = new klass('Hello')
obj2 = new klass('Goodbye')
a = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
b = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
assert deep.equals(a, b)
it 'should return false for deeply nested content that differs slightly', ->
klass = (@v) ->
obj1 = new klass('Hello')
obj2 = new klass('Goodbye')
a = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
b = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string that is different']}
]
assert !deep.equals(a, b)
describe 'extend()', () ->
it 'should accept multiple sources', (done) ->
a = a: 1
b = b: 2
c = c: 3
deep.extend a, b, c
assert.deepEqual a, a: 1, b: 2, c: 3
done()
it 'should prioritize latter arguments', (done) ->
a = a: 1
b = a: 2
c = a: 3
deep.extend a, b, c
assert.deepEqual a, a: 3
done()
it 'should extend recursively', (done) ->
a =
alpha:
beta:
charlie: 1
b =
alpha:
beta:
delta: 3
epsilon: 2
deep.extend a, b
assert.deepEqual a,
alpha:
beta:
charlie: 1
delta: 3
epsilon: 2
done()
it 'should create copies of nested objects', (done) ->
a =
alpha:
beta:
charlie: 1
b =
alpha:
beta:
delta: [1, 2, 3, 4]
deep.extend a, b
b.alpha.beta.delta.push(5)
assert.equal a.alpha.beta.delta.length, b.alpha.beta.delta.length - 1
done()
describe 'select()', () ->
before (done) ->
@container =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
(arg) -> "Goodbye #{arg}!"
{
foo: 'bar'
foobar: (arg) -> "Hello again #{arg}!"
}
]
obj:
a: [
{
b: {
c: (arg) -> "Goodbye again #{arg}!"
}
}
]
z: 'just a string!'
@selected = deep.select(@container, _.isFunction)
done()
it "should find all objects that satisfy the filter", (done) ->
assert.equal @selected.length, 4
assert.deepEqual @selected[0].value, @container.arr[0]
assert.deepEqual @selected[1].value, @container.arr[3]
assert.deepEqual @selected[2].value, @container.arr[4].foobar
assert.deepEqual @selected[3].value, @container.obj.a[0].b.c
done()
it "should report paths to objects that satisfy the filter", (done) ->
assert.deepEqual @selected[0].path, [ 'arr', '0' ]
assert.deepEqual @selected[1].path, [ 'arr', '3' ]
assert.deepEqual @selected[2].path, [ 'arr', '4', 'foobar' ]
assert.deepEqual @selected[3].path, [ 'obj', 'a', '0', 'b', 'c' ]
done()
describe "set()", () ->
beforeEach (done) ->
@obj =
arr: []
done()
it 'should set values using paths', (done) ->
deep.set @obj, [ 'arr', '0' ], 'new value'
assert.equal @obj.arr[0], 'new value'
done()
it 'should set values with path lenghts of 1', (done) ->
deep.set @obj, [ 'new' ], 'new value'
assert.equal @obj.new, 'new value'
done()
describe "transform()", () ->
beforeEach (done) ->
@original =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
(arg) -> "Goodbye #{arg}!"
{
foo: 'bar'
foobar: (arg) -> "Hello again #{arg}!"
bar: 3
}
]
obj:
a: [
{
b: {
c: (arg) -> "Goodbye again #{arg}!"
}
}
5
]
z: 'just a string!'
@transformed = deep.transform(@original, _.isNumber, (v) -> v + 1)
done()
it 'should apply transform to values that satisfy the filter', (done) ->
assert.equal @transformed.arr[2], 2
assert.equal @transformed.arr[4].bar, 4
assert.equal @transformed.obj.a[1], 6
done()
it 'should not affect values that do not satisfy the filter', (done) ->
assert.equal @transformed.arr[0], @original.arr[0]
assert.equal @transformed.arr[1], @original.arr[1]
assert.equal @transformed.obj.z, @original.obj.z
done() | 136174 | _ = require('underscore')
assert = require('assert')
testHelper = require('./test_helper')
deep = require('../lib/deep')
describe 'deep module', () ->
describe 'isPlainObject()', () ->
it 'object literals are plain objects', (done) ->
assert deep.isPlainObject({})
done()
it 'objects created with `new Object` are plain objects', (done) ->
assert deep.isPlainObject(new Object)
done()
it 'global is a plain object', (done) ->
assert deep.isPlainObject(global)
done()
it 'arrays are not plain objects', (done) ->
assert !deep.isPlainObject([])
done()
it 'functions are not plain objects', (done) ->
assert !deep.isPlainObject(() ->)
done()
it 'Buffers are not plain objects', (done) ->
assert !deep.isPlainObject(new Buffer(1))
done()
it 'Custom objects are not plain objects', (done) ->
Foobar = () ->
assert !deep.isPlainObject(new Foobar)
done()
describe 'clone()', () ->
beforeEach (done) ->
class Foobar
@original =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
new Buffer(1)
{
foo: 'bar'
foobar: new Foobar
}
]
obj:
a: [
{
b: {
c: []
}
}
]
z: 'just a string!'
@clone = deep.clone(@original)
done()
it 'should generate new plain objects and arrays', (done) ->
@clone.obj.a[0].b.c.push 0
assert.notEqual @clone.obj.a[0].b.c.length, @original.obj.a[0].b.c.length
@clone.arr[4].bar = 'foo'
assert !@original.arr[4].bar?
done()
it 'should preserve references to functions', (done) ->
assert.equal @clone.arr[0], @original.arr[0]
done()
it 'should preserve references to Buffers', (done) ->
assert.equal @clone.arr[3].constructor.name, 'Buffer'
assert.equal @clone.arr[3], @original.arr[3]
done()
it 'should preserve references to custom objects', (done) ->
assert.equal @clone.arr[4].foobar.constructor.name, 'Foobar'
assert.equal @clone.arr[4].foobar, @original.arr[4].foobar
done()
describe 'equals()', () ->
it 'should return true for scalar data that are identical', ->
a = 1
b = 1
assert deep.equals(a, b)
a = "Hello"
b = "Hello"
assert deep.equals(a, b)
a = false
b = false
assert deep.equals(a, b)
it 'should return false for scalar data that are different', ->
a = 1
b = 2
assert !deep.equals(a, b)
a = "Hello"
b = "Good<NAME>"
assert !deep.equals(a, b)
a = false
b = true
assert !deep.equals(a, b)
it 'should return true for matching references to non-plain objects', ->
klass = (@v) ->
a = b = new klass("Hello")
assert deep.equals(a, b)
it 'should return false for non-matching references to similar non-plain objects', ->
klass = (@v) ->
a = new klass("Hello")
b = new klass("Hello")
assert !deep.equals(a, b)
it 'should return true for simple plain objects that are identical', ->
a = x: 1, y: 2
b = x: 1, y: 2
assert deep.equals(a, b)
it 'should return true for simple plain objects that are identical except for order', ->
a = x: 1; a.y = 2
b = y: 2; b.x = 1
assert deep.equals(a, b)
it 'should return false for simple plain objects that differ', ->
a = x: 1, y: 2
b = x: 1, y: 3
assert !deep.equals(a, b)
it 'should return true for arrays that are identical', ->
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
assert deep.equals(a, b)
it 'should return false for arrays that are identical except for order', ->
a = [1, 2, 3, 4]
b = [1, 2, 4, 3]
assert !deep.equals(a, b)
it 'should return false for arrays that differ in length', ->
a = [1, 2, 3, 4]
b = [1, 2, 3]
assert !deep.equals(a, b)
it 'should return false for arrays that differ in content', ->
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
assert !deep.equals(a, b)
it 'should return true for deeply nested content that is identical', ->
klass = (@v) ->
obj1 = new klass('Hello')
obj2 = new klass('Goodbye')
a = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
b = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
assert deep.equals(a, b)
it 'should return false for deeply nested content that differs slightly', ->
klass = (@v) ->
obj1 = new klass('Hello')
obj2 = new klass('Goodbye')
a = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
b = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string that is different']}
]
assert !deep.equals(a, b)
describe 'extend()', () ->
it 'should accept multiple sources', (done) ->
a = a: 1
b = b: 2
c = c: 3
deep.extend a, b, c
assert.deepEqual a, a: 1, b: 2, c: 3
done()
it 'should prioritize latter arguments', (done) ->
a = a: 1
b = a: 2
c = a: 3
deep.extend a, b, c
assert.deepEqual a, a: 3
done()
it 'should extend recursively', (done) ->
a =
alpha:
beta:
charlie: 1
b =
alpha:
beta:
delta: 3
epsilon: 2
deep.extend a, b
assert.deepEqual a,
alpha:
beta:
charlie: 1
delta: 3
epsilon: 2
done()
it 'should create copies of nested objects', (done) ->
a =
alpha:
beta:
charlie: 1
b =
alpha:
beta:
delta: [1, 2, 3, 4]
deep.extend a, b
b.alpha.beta.delta.push(5)
assert.equal a.alpha.beta.delta.length, b.alpha.beta.delta.length - 1
done()
describe 'select()', () ->
before (done) ->
@container =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
(arg) -> "Goodbye #{arg}!"
{
foo: 'bar'
foobar: (arg) -> "Hello again #{arg}!"
}
]
obj:
a: [
{
b: {
c: (arg) -> "Goodbye again #{arg}!"
}
}
]
z: 'just a string!'
@selected = deep.select(@container, _.isFunction)
done()
it "should find all objects that satisfy the filter", (done) ->
assert.equal @selected.length, 4
assert.deepEqual @selected[0].value, @container.arr[0]
assert.deepEqual @selected[1].value, @container.arr[3]
assert.deepEqual @selected[2].value, @container.arr[4].foobar
assert.deepEqual @selected[3].value, @container.obj.a[0].b.c
done()
it "should report paths to objects that satisfy the filter", (done) ->
assert.deepEqual @selected[0].path, [ 'arr', '0' ]
assert.deepEqual @selected[1].path, [ 'arr', '3' ]
assert.deepEqual @selected[2].path, [ 'arr', '4', 'foobar' ]
assert.deepEqual @selected[3].path, [ 'obj', 'a', '0', 'b', 'c' ]
done()
describe "set()", () ->
beforeEach (done) ->
@obj =
arr: []
done()
it 'should set values using paths', (done) ->
deep.set @obj, [ 'arr', '0' ], 'new value'
assert.equal @obj.arr[0], 'new value'
done()
it 'should set values with path lenghts of 1', (done) ->
deep.set @obj, [ 'new' ], 'new value'
assert.equal @obj.new, 'new value'
done()
describe "transform()", () ->
beforeEach (done) ->
@original =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
(arg) -> "Goodbye #{arg}!"
{
foo: 'bar'
foobar: (arg) -> "Hello again #{arg}!"
bar: 3
}
]
obj:
a: [
{
b: {
c: (arg) -> "Goodbye again #{arg}!"
}
}
5
]
z: 'just a string!'
@transformed = deep.transform(@original, _.isNumber, (v) -> v + 1)
done()
it 'should apply transform to values that satisfy the filter', (done) ->
assert.equal @transformed.arr[2], 2
assert.equal @transformed.arr[4].bar, 4
assert.equal @transformed.obj.a[1], 6
done()
it 'should not affect values that do not satisfy the filter', (done) ->
assert.equal @transformed.arr[0], @original.arr[0]
assert.equal @transformed.arr[1], @original.arr[1]
assert.equal @transformed.obj.z, @original.obj.z
done() | true | _ = require('underscore')
assert = require('assert')
testHelper = require('./test_helper')
deep = require('../lib/deep')
describe 'deep module', () ->
describe 'isPlainObject()', () ->
it 'object literals are plain objects', (done) ->
assert deep.isPlainObject({})
done()
it 'objects created with `new Object` are plain objects', (done) ->
assert deep.isPlainObject(new Object)
done()
it 'global is a plain object', (done) ->
assert deep.isPlainObject(global)
done()
it 'arrays are not plain objects', (done) ->
assert !deep.isPlainObject([])
done()
it 'functions are not plain objects', (done) ->
assert !deep.isPlainObject(() ->)
done()
it 'Buffers are not plain objects', (done) ->
assert !deep.isPlainObject(new Buffer(1))
done()
it 'Custom objects are not plain objects', (done) ->
Foobar = () ->
assert !deep.isPlainObject(new Foobar)
done()
describe 'clone()', () ->
beforeEach (done) ->
class Foobar
@original =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
new Buffer(1)
{
foo: 'bar'
foobar: new Foobar
}
]
obj:
a: [
{
b: {
c: []
}
}
]
z: 'just a string!'
@clone = deep.clone(@original)
done()
it 'should generate new plain objects and arrays', (done) ->
@clone.obj.a[0].b.c.push 0
assert.notEqual @clone.obj.a[0].b.c.length, @original.obj.a[0].b.c.length
@clone.arr[4].bar = 'foo'
assert !@original.arr[4].bar?
done()
it 'should preserve references to functions', (done) ->
assert.equal @clone.arr[0], @original.arr[0]
done()
it 'should preserve references to Buffers', (done) ->
assert.equal @clone.arr[3].constructor.name, 'Buffer'
assert.equal @clone.arr[3], @original.arr[3]
done()
it 'should preserve references to custom objects', (done) ->
assert.equal @clone.arr[4].foobar.constructor.name, 'Foobar'
assert.equal @clone.arr[4].foobar, @original.arr[4].foobar
done()
describe 'equals()', () ->
it 'should return true for scalar data that are identical', ->
a = 1
b = 1
assert deep.equals(a, b)
a = "Hello"
b = "Hello"
assert deep.equals(a, b)
a = false
b = false
assert deep.equals(a, b)
it 'should return false for scalar data that are different', ->
a = 1
b = 2
assert !deep.equals(a, b)
a = "Hello"
b = "GoodPI:NAME:<NAME>END_PI"
assert !deep.equals(a, b)
a = false
b = true
assert !deep.equals(a, b)
it 'should return true for matching references to non-plain objects', ->
klass = (@v) ->
a = b = new klass("Hello")
assert deep.equals(a, b)
it 'should return false for non-matching references to similar non-plain objects', ->
klass = (@v) ->
a = new klass("Hello")
b = new klass("Hello")
assert !deep.equals(a, b)
it 'should return true for simple plain objects that are identical', ->
a = x: 1, y: 2
b = x: 1, y: 2
assert deep.equals(a, b)
it 'should return true for simple plain objects that are identical except for order', ->
a = x: 1; a.y = 2
b = y: 2; b.x = 1
assert deep.equals(a, b)
it 'should return false for simple plain objects that differ', ->
a = x: 1, y: 2
b = x: 1, y: 3
assert !deep.equals(a, b)
it 'should return true for arrays that are identical', ->
a = [1, 2, 3, 4]
b = [1, 2, 3, 4]
assert deep.equals(a, b)
it 'should return false for arrays that are identical except for order', ->
a = [1, 2, 3, 4]
b = [1, 2, 4, 3]
assert !deep.equals(a, b)
it 'should return false for arrays that differ in length', ->
a = [1, 2, 3, 4]
b = [1, 2, 3]
assert !deep.equals(a, b)
it 'should return false for arrays that differ in content', ->
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
assert !deep.equals(a, b)
it 'should return true for deeply nested content that is identical', ->
klass = (@v) ->
obj1 = new klass('Hello')
obj2 = new klass('Goodbye')
a = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
b = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
assert deep.equals(a, b)
it 'should return false for deeply nested content that differs slightly', ->
klass = (@v) ->
obj1 = new klass('Hello')
obj2 = new klass('Goodbye')
a = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string']}
]
b = [
1
[false, null, undefined, obj1]
{x: 3, y: 4, z: [5, 6, obj2, 'some string that is different']}
]
assert !deep.equals(a, b)
describe 'extend()', () ->
it 'should accept multiple sources', (done) ->
a = a: 1
b = b: 2
c = c: 3
deep.extend a, b, c
assert.deepEqual a, a: 1, b: 2, c: 3
done()
it 'should prioritize latter arguments', (done) ->
a = a: 1
b = a: 2
c = a: 3
deep.extend a, b, c
assert.deepEqual a, a: 3
done()
it 'should extend recursively', (done) ->
a =
alpha:
beta:
charlie: 1
b =
alpha:
beta:
delta: 3
epsilon: 2
deep.extend a, b
assert.deepEqual a,
alpha:
beta:
charlie: 1
delta: 3
epsilon: 2
done()
it 'should create copies of nested objects', (done) ->
a =
alpha:
beta:
charlie: 1
b =
alpha:
beta:
delta: [1, 2, 3, 4]
deep.extend a, b
b.alpha.beta.delta.push(5)
assert.equal a.alpha.beta.delta.length, b.alpha.beta.delta.length - 1
done()
describe 'select()', () ->
before (done) ->
@container =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
(arg) -> "Goodbye #{arg}!"
{
foo: 'bar'
foobar: (arg) -> "Hello again #{arg}!"
}
]
obj:
a: [
{
b: {
c: (arg) -> "Goodbye again #{arg}!"
}
}
]
z: 'just a string!'
@selected = deep.select(@container, _.isFunction)
done()
it "should find all objects that satisfy the filter", (done) ->
assert.equal @selected.length, 4
assert.deepEqual @selected[0].value, @container.arr[0]
assert.deepEqual @selected[1].value, @container.arr[3]
assert.deepEqual @selected[2].value, @container.arr[4].foobar
assert.deepEqual @selected[3].value, @container.obj.a[0].b.c
done()
it "should report paths to objects that satisfy the filter", (done) ->
assert.deepEqual @selected[0].path, [ 'arr', '0' ]
assert.deepEqual @selected[1].path, [ 'arr', '3' ]
assert.deepEqual @selected[2].path, [ 'arr', '4', 'foobar' ]
assert.deepEqual @selected[3].path, [ 'obj', 'a', '0', 'b', 'c' ]
done()
describe "set()", () ->
beforeEach (done) ->
@obj =
arr: []
done()
it 'should set values using paths', (done) ->
deep.set @obj, [ 'arr', '0' ], 'new value'
assert.equal @obj.arr[0], 'new value'
done()
it 'should set values with path lenghts of 1', (done) ->
deep.set @obj, [ 'new' ], 'new value'
assert.equal @obj.new, 'new value'
done()
describe "transform()", () ->
beforeEach (done) ->
@original =
arr: [
(arg) -> "Hello #{arg}!"
'hello!'
1
(arg) -> "Goodbye #{arg}!"
{
foo: 'bar'
foobar: (arg) -> "Hello again #{arg}!"
bar: 3
}
]
obj:
a: [
{
b: {
c: (arg) -> "Goodbye again #{arg}!"
}
}
5
]
z: 'just a string!'
@transformed = deep.transform(@original, _.isNumber, (v) -> v + 1)
done()
it 'should apply transform to values that satisfy the filter', (done) ->
assert.equal @transformed.arr[2], 2
assert.equal @transformed.arr[4].bar, 4
assert.equal @transformed.obj.a[1], 6
done()
it 'should not affect values that do not satisfy the filter', (done) ->
assert.equal @transformed.arr[0], @original.arr[0]
assert.equal @transformed.arr[1], @original.arr[1]
assert.equal @transformed.obj.z, @original.obj.z
done() |
[
{
"context": " one:\n constructor:\n name: 'Blaine'\n two:\n constructor:\n ",
"end": 432,
"score": 0.9963313937187195,
"start": 426,
"tag": "NAME",
"value": "Blaine"
},
{
"context": " two:\n constructor:\n name: 'Sch'\n complete()\n\n it 'matches case insensiti",
"end": 492,
"score": 0.9844268560409546,
"start": 489,
"tag": "NAME",
"value": "Sch"
}
] | tests/command_spec.coffee | thisredone/pry.coffee | 1 | expect = require('chai').expect
Command = require('../src/pry/command')
Range = require('../src/pry/range')
describe 'Command', ->
subject = null
beforeEach (complete) ->
subject = new Command
scope: (p) -> p
output:
send: -> true
complete()
describe '#command', ->
beforeEach (complete) ->
subject.constructor.commands =
one:
constructor:
name: 'Blaine'
two:
constructor:
name: 'Sch'
complete()
it 'matches case insensitive strings', ->
expect(subject.command('blaine').constructor.name).to.equal 'Blaine'
describe '#command_regex', ->
describe 'given a name of foo and 1-3 arguments', ->
beforeEach (complete) ->
subject.name = 'foo'
subject.args = new Range(0, 3)
complete()
it 'matches foo', ->
expect('foo').to.match subject.command_regex()
it 'matches foo bar', ->
expect('foo bar').to.match subject.command_regex()
it 'matches foo bar baz guz', ->
expect('foo bar baz guz').to.match subject.command_regex()
it 'doesnt matches foo bar baz guz gul', ->
expect('foo bar baz guz gul').to.not.match subject.command_regex()
| 84966 | expect = require('chai').expect
Command = require('../src/pry/command')
Range = require('../src/pry/range')
describe 'Command', ->
subject = null
beforeEach (complete) ->
subject = new Command
scope: (p) -> p
output:
send: -> true
complete()
describe '#command', ->
beforeEach (complete) ->
subject.constructor.commands =
one:
constructor:
name: '<NAME>'
two:
constructor:
name: '<NAME>'
complete()
it 'matches case insensitive strings', ->
expect(subject.command('blaine').constructor.name).to.equal 'Blaine'
describe '#command_regex', ->
describe 'given a name of foo and 1-3 arguments', ->
beforeEach (complete) ->
subject.name = 'foo'
subject.args = new Range(0, 3)
complete()
it 'matches foo', ->
expect('foo').to.match subject.command_regex()
it 'matches foo bar', ->
expect('foo bar').to.match subject.command_regex()
it 'matches foo bar baz guz', ->
expect('foo bar baz guz').to.match subject.command_regex()
it 'doesnt matches foo bar baz guz gul', ->
expect('foo bar baz guz gul').to.not.match subject.command_regex()
| true | expect = require('chai').expect
Command = require('../src/pry/command')
Range = require('../src/pry/range')
describe 'Command', ->
subject = null
beforeEach (complete) ->
subject = new Command
scope: (p) -> p
output:
send: -> true
complete()
describe '#command', ->
beforeEach (complete) ->
subject.constructor.commands =
one:
constructor:
name: 'PI:NAME:<NAME>END_PI'
two:
constructor:
name: 'PI:NAME:<NAME>END_PI'
complete()
it 'matches case insensitive strings', ->
expect(subject.command('blaine').constructor.name).to.equal 'Blaine'
describe '#command_regex', ->
describe 'given a name of foo and 1-3 arguments', ->
beforeEach (complete) ->
subject.name = 'foo'
subject.args = new Range(0, 3)
complete()
it 'matches foo', ->
expect('foo').to.match subject.command_regex()
it 'matches foo bar', ->
expect('foo bar').to.match subject.command_regex()
it 'matches foo bar baz guz', ->
expect('foo bar baz guz').to.match subject.command_regex()
it 'doesnt matches foo bar baz guz gul', ->
expect('foo bar baz guz gul').to.not.match subject.command_regex()
|
[
{
"context": "k = proj.task 'abc'\n task.name.should.equal 'abc'\n task.type.should.equal 'default'\n\n it '",
"end": 550,
"score": 0.5456283092498779,
"start": 547,
"tag": "NAME",
"value": "abc"
},
{
"context": "abc', ( task ) ->\n task.name.should.equal 'abc'\n task.type.should.equal 'default'\n ",
"end": 786,
"score": 0.82076096534729,
"start": 783,
"tag": "NAME",
"value": "abc"
}
] | test/project.test.coffee | venkatperi/jsgradle | 0 | assert = require 'assert'
should = require 'should'
Project = require '../lib/project/Project'
proj = undefined
describe 'Project', ->
it 'needs a name', ->
assert.throws -> new Project()
it 'has path', ->
proj = new Project name : 'test'
proj.name.should.equal 'test'
proj.depth.should.equal 0
describe 'items', ->
beforeEach ->
proj = new Project name : 'test'
it 'needs a name', ->
assert.throws -> proj.task()
it 'create task', ->
task = proj.task 'abc'
task.name.should.equal 'abc'
task.type.should.equal 'default'
it 'task exists', ->
proj.task 'abc'
assert.throws -> proj.task 'abc'
it 'configure task', ( done ) ->
proj.task 'abc', ( task ) ->
task.name.should.equal 'abc'
task.type.should.equal 'default'
done()
| 94383 | assert = require 'assert'
should = require 'should'
Project = require '../lib/project/Project'
proj = undefined
describe 'Project', ->
it 'needs a name', ->
assert.throws -> new Project()
it 'has path', ->
proj = new Project name : 'test'
proj.name.should.equal 'test'
proj.depth.should.equal 0
describe 'items', ->
beforeEach ->
proj = new Project name : 'test'
it 'needs a name', ->
assert.throws -> proj.task()
it 'create task', ->
task = proj.task 'abc'
task.name.should.equal '<NAME>'
task.type.should.equal 'default'
it 'task exists', ->
proj.task 'abc'
assert.throws -> proj.task 'abc'
it 'configure task', ( done ) ->
proj.task 'abc', ( task ) ->
task.name.should.equal '<NAME>'
task.type.should.equal 'default'
done()
| true | assert = require 'assert'
should = require 'should'
Project = require '../lib/project/Project'
proj = undefined
describe 'Project', ->
it 'needs a name', ->
assert.throws -> new Project()
it 'has path', ->
proj = new Project name : 'test'
proj.name.should.equal 'test'
proj.depth.should.equal 0
describe 'items', ->
beforeEach ->
proj = new Project name : 'test'
it 'needs a name', ->
assert.throws -> proj.task()
it 'create task', ->
task = proj.task 'abc'
task.name.should.equal 'PI:NAME:<NAME>END_PI'
task.type.should.equal 'default'
it 'task exists', ->
proj.task 'abc'
assert.throws -> proj.task 'abc'
it 'configure task', ( done ) ->
proj.task 'abc', ( task ) ->
task.name.should.equal 'PI:NAME:<NAME>END_PI'
task.type.should.equal 'default'
done()
|
[
{
"context": "th.role = 'unknown'\n req.session.auth.alias = 'noname'\n res.json {code:0,reason:'',status:'logout su",
"end": 6479,
"score": 0.7261060476303101,
"start": 6473,
"tag": "USERNAME",
"value": "noname"
},
{
"context": "Date\n # always remember:hashise!!\n password: hashise password \n try\n await ins.save()\n res.json 'Registe",
"end": 11998,
"score": 0.9982492923736572,
"start": 11982,
"tag": "PASSWORD",
"value": "hashise password"
},
{
"context": " .send {'alias':'agent'}\n .send {'password':'1234567'} # solid password for this task.\n .end (err,r",
"end": 18700,
"score": 0.9993026852607727,
"start": 18693,
"tag": "PASSWORD",
"value": "1234567"
},
{
"context": ".redirect 303,'/admin/login'\n else\n keyname = TICKET_PREFIX + ':hash:' + category + '*'\n recor",
"end": 22952,
"score": 0.8385102152824402,
"start": 22951,
"tag": "KEY",
"value": "T"
},
{
"context": "ct 303,'/admin/login'\n else\n keyname = TICKET_PREFIX + ':hash:' + category + '*'\n records = await _",
"end": 22964,
"score": 0.6397838592529297,
"start": 22958,
"tag": "KEY",
"value": "PREFIX"
},
{
"context": ".redirect 303,'/admin/login'\n else\n keyname = TICKET_PREFIX + ':hash:*'\n records = await _retr",
"end": 23431,
"score": 0.5872706174850464,
"start": 23430,
"tag": "KEY",
"value": "T"
},
{
"context": "ne.property 'initial_timestamp'\n obj.password = one.property 'password'\n obj.id = one.id\n results.push o",
"end": 30581,
"score": 0.9545661807060242,
"start": 30569,
"tag": "PASSWORD",
"value": "one.property"
},
{
"context": "itial_timestamp'\n obj.password = one.property 'password'\n obj.id = one.id\n results.push obj \n res.",
"end": 30591,
"score": 0.9544379115104675,
"start": 30583,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "nitial_timestamp:Date.parse new Date\n password: hashise '1234567' # default password. \n try\n await in",
"end": 34031,
"score": 0.9975957870483398,
"start": 34024,
"tag": "PASSWORD",
"value": "hashise"
},
{
"context": "estamp:Date.parse new Date\n password: hashise '1234567' # default password. \n try\n await ins.save()\n",
"end": 34040,
"score": 0.9657008051872253,
"start": 34033,
"tag": "PASSWORD",
"value": "1234567"
},
{
"context": "'isActive'\n warning = ''\n if dbpassword is '8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414'\n warning = 'should change this simple/initi",
"end": 37127,
"score": 0.9941554069519043,
"start": 37063,
"tag": "PASSWORD",
"value": "8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414"
},
{
"context": "hatistime:fieldobj['first-half-']\n dakaer:'superuser'\n category:'entry' \n browser:req.he",
"end": 38569,
"score": 0.5458195209503174,
"start": 38560,
"tag": "USERNAME",
"value": "superuser"
},
{
"context": "atistime:fieldobj['second-half-']\n dakaer:'superuser'\n category:'exit' \n browser:req.hea",
"end": 38869,
"score": 0.5992055535316467,
"start": 38860,
"tag": "USERNAME",
"value": "superuser"
},
{
"context": "atistime:fieldobj['second-half-']\n dakaer:'superuser'\n browser:req.headers['user-agent']\n ",
"end": 39405,
"score": 0.5763137936592102,
"start": 39396,
"tag": "USERNAME",
"value": "superuser"
}
] | coffees/app.coffee | android1and1/tickets | 0 | # firssts of first check if 'redis-server' is running.
{spawn} = require 'child_process'
# this for redis promisify(client.get),the way inpirit from npm-redis.
{promisify} = require 'util'
pgrep = spawn '/usr/bin/pgrep',['redis-server']
pgrep.on 'close',(code)->
if code isnt 0
console.log 'should run redis-server first.'
process.exit 1
path = require 'path'
fs = require 'fs'
http = require 'http'
qr_image = require 'qr-image'
formidable = require 'formidable'
crypto = require 'crypto'
# super-user's credential
fs.stat './configs/credentials/super-user.js',(err,stats)->
if err
console.log 'Credential File Not Exists,Fix It.'
process.exit 1
credential = require './configs/credentials/super-user.js'
hostname = require './configs/hostname.js'
superpass = credential.password
# ruler for daka app am:7:30 pm:18:00
ruler = require './configs/ruler-of-daka.js'
{Nohm} = require 'nohm'
Account = require './modules/md-account'
Daka = require './modules/md-daka'
dakaModel = undefined
accountModel = undefined
TICKET_PREFIX = 'ticket'
TICKET_MEDIA_ROOT = path.join __dirname,'public','tickets'
DAKA_WILDCARD = 'DaKa*daily*'
ACCOUNT_WILDCARD='DaKa*account*'
redis = (require 'redis').createClient()
setAsync = promisify redis.set
.bind redis
getAsync = promisify redis.get
.bind redis
expireAsync = promisify redis.expire
.bind redis
existsAsync = promisify redis.exists
.bind redis
delAsync = (key)->
new Promise (resolve,reject)->
redis.del key,(err,intReply)->
if err
reject err
else
resolve intReply
hgetAsync = (key,index)->
new Promise (resolve,reject)->
redis.hget key,index,(err,value)->
if err
reject err
else
resolve value
hgetallAsync = (key)->
new Promise (resolve,reject)->
redis.hgetall key,(err,record)->
if err
reject err
else
resolve record
lrangeAsync = (key,start,end)->
new Promise (resolve,reject)->
redis.lrange key,start,end,(err,items)->
if err
reject err
else
resolve items
redis.on 'error',(err)->
console.log 'Heard that:',err
redis.on 'connect',->
Nohm.setClient @
Nohm.setPrefix 'DaKa' # the main api name.
# register the 2 models.
dakaModel = Nohm.register Daka
accountModel = Nohm.register Account
express = require 'express'
app = express()
app.set 'view engine','pug'
STATIC_ROOT = path.join __dirname,'public'
app.use express.static STATIC_ROOT
# enable "req.body",like the old middware - "bodyParser"
app.use express.urlencoded({extended:false})
# session
Session = require 'express-session'
Store = (require 'connect-redis') Session
# authenticate now
redis_auth_pass = require './configs/redis/auth_pass.js'
redis.auth redis_auth_pass,(err,reply)->
if err
console.error 'redis db authenticate failure.'
return process.exit -1
# start add all middle-ware
app.use Session {
cookie:
maxAge: 86400 * 1000 # one day.
httpOnly:true
path:'/' # 似乎太过宽泛,之后有机会会琢磨这个
secret: 'youkNoW.'
store: new Store {client:redis}
resave:false
saveUninitialized:true
}
app.use (req,res,next)->
res.locals.referrer = req.session.referrer
delete req.session.referrer # then,delete() really harmless
next()
app.get '/',(req,res)->
role = req.session?.auth?.role
alias = req.session?.auth?.alias
if role is 'unknown' and alias is 'noname'
[role,alias] = ['visitor','hi']
res.render 'index'
,
title:'welcome-daka'
role:role
alias:alias
app.get '/alpha/:tpl',(req,res)->
tpl = req.params.tpl # client send /alpha?tpl=something
# Notice:all template in views/alpha,use layout via "../layouts"
res.render 'alpha/' + tpl,{'title':'Alpha!'}
app.get '/create-check-words',(req,res)->
# 如果用户选择了填表单方式来打卡。
digits = [48..57] # 0..9
alpha = [97...97+26] # A..Z
chars = digits.concat alpha
.concat digits
.concat alpha
# total 72 chars,so index max is 72-1=71
{round,random} = Math
words = for _ in [1..5] # make length=5 words
index = round random()*71
String.fromCharCode chars[index]
words = words.join ''
# 存储check words到redis数据库,并设置超时条件。
await setAsync 'important',words
await expireAsync 'important',60
res.json words
app.get '/create-qrcode',(req,res)->
# the query string from user-daka js code(img.src=url+'....')
# query string include socketid,timestamp,and alias
text = [req.query.socketid,req.query.timestamp].join('-')
await setAsync 'important',text
await expireAsync 'important',60
# templary solid ,original mode is j602
fulltext = hostname + '/user/daka-response?mode=' + req.query.mode + '&&alias=' + req.query.alias + '&&check=' + text
res.type 'png'
qr_image.image(fulltext).pipe res
# maniuate new func or new mind.
app.get '/user/daka',(req,res)->
if req.session?.auth?.role isnt 'user'
req.session.referrer = '/user/daka'
res.redirect 303,'/user/login'
else
# check which scene the user now in?
user = req.session.auth.alias
# ruler object
today = new Date
today.setHours ruler.am.hours
today.setMinutes ruler.am.minutes
today.setSeconds 0
ids = await dakaModel.find {alias:user,utc_ms:{min:Date.parse today}}
# mode变量值为0提示“入场”待打卡状态,1则为“出场”待打卡状态。
res.render 'user-daka',{mode:ids.length,alias:user,title:'User DaKa Console'}
app.get '/user/login',(req,res)->
res.render 'user-login',{title:'Fill User Login Form'}
app.post '/user/login',(req,res)->
# reference line#163
{itisreferrer,alias,password} = req.body
itisreferrer = itisreferrer or '/user/login-success'
# filter these 2 strings for anti-injecting
isInvalidation = (! filter alias or ! filter password)
if isInvalidation
return res.render 'user-login-failure',{reason: '含有非法字符(只允许ASCII字符和数字)!',title:'User-Login-Failure'}
# auth initialize
initSession req
# first check if exists this alias name?
# mobj is 'match stats object'
mobj = await matchDB accountModel,alias,'user',password
if mobj.match_result
# till here,login data is matches.
updateAuthSession req,'user',alias
res.redirect 303,itisreferrer
else
updateAuthSession req,'unknown','noname'
return res.render 'user-login-failure',{reason: '用户登录失败,原因:帐户不存在/帐户被临时禁用/账户口令不匹配。',title:'User-Login-Failure'}
app.put '/user/logout',(req,res)->
role = req.session?.auth?.role
if role is 'user'
req.session.auth.role = 'unknown'
req.session.auth.alias = 'noname'
res.json {code:0,reason:'',status:'logout success'}
else
res.json {code:-1,reason:'No This Account Or Role Isnt User.',status:'logout failure'}
app.get '/user/login-success',(req,res)->
res.render 'user-login-success',{title:'User Role Validation:successfully'}
# user choiced alternatively way to daka
app.post '/user/daka-response',(req,res)->
check = req.body.check
# get from redis db
words = await getAsync 'important'
session_alias = req.session?.auth?.alias
if words is check
# save this daka-item
try
obj = new Date
desc = obj.toString()
ms = Date.parse obj
ins = await Nohm.factory 'daily'
ins.property
alias: session_alias
utc_ms: ms
whatistime: desc
browser: req.headers["user-agent"]
category:req.body.mode # 'entry' or 'exit' mode
await ins.save()
# notice admin with user's success.
# the .js file include socket,if code=0,socket.emit 'code','0'
return res.render 'user-daka-response-success',{code:'0',title:'login Result',status:'打卡成功',user:session_alias}
catch error
# notice admin with user's failure.
# js file include socket,if code=-1,socket.emit 'code','-1'
# show db errors
console.dir ins.errors
return res.render 'user-daka-response-failure',{title:'daka failure','reason':ins.errors,code:'-1',user:session_alias,status:'数据库错误,打卡失败。'}
else
return res.render 'user-daka-response-failure',{title:'daka failure',status:'打卡失败',code:'-1',reason:'超时或验证无效',user:session_alias}
# user daka via QR code (scan software)
app.get '/user/daka-response',(req,res)->
session_alias = req.session?.auth?.alias
if session_alias is undefined
req.session.referrer = '/user/daka-response'
return res.redirect 303,'/user/login'
if req.query.alias isnt session_alias
return res.json {status:'alias inconsistent',warning:'you should requery daka and visit this page via only one browser',session:session_alias,querystring:req.query.alias}
# user-daka upload 'text' via scan-qrcode-then-goto-url.
text = req.query.check
dbkeep= await getAsync 'important'
if dbkeep isnt '' and text isnt '' and dbkeep is text
# save this daka-item
try
obj = new Date
desc = obj.toString()
ms = Date.parse obj
ins = await Nohm.factory 'daily'
ins.property
# if client has 2 difference browser,one for socketio,and one for qrcode-parser.how the 'alias' value is fit?
alias: req.query.alias # or req.session.auth.alias
utc_ms: ms
whatistime: desc
browser: req.headers["user-agent"]
category:req.query.mode # 'entry' or 'exit' mode
await ins.save()
# notice admin with user's success.
# the .js file include socket,if code=0,socket.emit 'code','0'
return res.render 'user-daka-response-success',{code:'0',title:'login Result',status:'打卡成功',user:req.query.alias}
catch error
console.log 'error',error
# notice admin with user's failure.
# the .js file include socket,if code=-1,socket.emit 'code','-1'
# show db errors
return res.render 'user-daka-response-failure',{title:'daka failure','reason':ins.errors,code:'-1',user:req.query.alias,status:'数据库错误,打卡失败。'}
else
return res.render 'user-daka-response-failure',{title:'daka failure',status:'打卡失败',code:'-1',reason:'超时或身份验证无效',user:req.query.alias}
# start-point-admin
app.get '/admin/daka',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/daka'
res.redirect 303,'/admin/login'
else
res.render 'admin-daka',{title:'Admin Console'}
app.get '/admin/login',(req,res)->
# pagejs= /mine/mine-admin-login.js
res.render 'admin-login',{title:'Fill Authentication Form'}
app.get '/admin/admin-update-password',(req,res)->
res.render 'admin-update-password',{title:'Admin-Update-Password'}
app.put '/admin/logout',(req,res)->
role = req.session?.auth?.role
if role is 'admin'
req.session.auth.role = 'unknown'
req.session.auth.alias = 'noname'
res.json {reason:'',status:'logout success'}
else
# notice that,if client logout failure,not change its role and alias
res.json {reason:'no this account or role isnt admin.',status:'logout failure'}
app.post '/admin/admin-update-password',(req,res)->
{oldpassword,newpassword,alias} = req.body
items = await accountModel.findAndLoad {alias:alias}
if items.length is 0
res.json 'no found!'
else
item = items[0]
dbkeep = item.property 'password'
if dbkeep is hashise oldpassword
# update this item's password part
item.property 'password',hashise newpassword
try
item.save()
catch error
return res.json item.error
return res.json 'Update Password For Admin.'
else #password is mismatches.
return res.json 'Mismatch your oldpassword,check it.'
app.get '/admin/register-user',(req,res)->
if req.session?.auth?.role isnt 'admin'
res.redirect 302,'/admin/login'
else
res.render 'admin-register-user',{title:'Admin-Register-User'}
app.post '/admin/register-user',(req,res)->
{alias,password} = req.body
if ! filter alias or ! filter password
return res.json 'Wrong:User Name(alias) contains invalid character(s).'
ins = await Nohm.factory 'account'
ins.property
alias:alias
role:'user'
initial_timestamp:Date.parse new Date
# always remember:hashise!!
password: hashise password
try
await ins.save()
res.json 'Register User - ' + alias
catch error
res.json ins.errors
# db operator:FIND(superuser,admin are need list all tickets)
# db operator:ADD
app.all '/admin/create-new-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/create-new-ticket'
return res.redirect 303,'/admin/login'
# redis instance already exists - 'redis'
if req.method is 'GET'
res.render 'admin-create-new-ticket',{alias:req.session.auth.alias,title:'Admin-Create-New-Ticket'}
else # POST
# let npm-formidable handles
formid = new formidable.IncomingForm
formid.uploadDir = TICKET_MEDIA_ROOT
formid.keepExtensions = true
formid.maxFileSize = 20 * 1024 * 1024 # update to 200M,for video
_save_one_ticket req,res,formid,redis
app.all '/admin/edit-ticket/:keyname',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/edit-ticket/' + req.params.keyname
return res.redirect 303,'/admin/login'
keyname = req.params.keyname
if req.method is 'GET'
# because it first from a inner-click,so not worry about if key exists.
item = await hgetallAsync keyname
res.render 'admin-edit-ticket-form',{keyname:keyname,title:'admin edit ticket',item:item}
else if req.method is 'POST'
item = await hgetallAsync keyname
options = item # todo.
ticket_id = item.ticket_id
formid = new formidable.IncomingForm
formid.uploadDir = TICKET_MEDIA_ROOT
formid.keepExtensions = true
formid.maxFileSize = 20 * 1024 * 1024 # update maxFileSize to 200M if supports video
formid.parse req,(formid_err,fields,files)->
if formid_err
return res.render 'admin-save-ticket-no-good.pug',{title:'No Save',reason:formid_err.message}
for k,v of fields
if k isnt 'original_uri'
options[k] = v
if files.media.size is 0
bool = fs.existsSync files.media.path
if bool
fs.unlinkSync files.media.path
else
console.log 'files.media.path illegel.'
if files.media.size isnt 0
media_url = files.media.path
realpath = path.join(STATIC_ROOT,'tickets',fields.original_uri.replace(/.*\/(.+)$/,"$1"))
if fields.original_uri
fs.unlinkSync(path.join(STATIC_ROOT,'tickets',fields.original_uri.replace(/.*\/(.+)$/,"$1")))
media_url = '/tickets/' + media_url.replace /.*\/(.+)$/,"$1"
options['media'] = media_url
options['media_type'] = files.media.type
# 检查category是否变了
if not (new RegExp(fields.category)).test keyname
await delAsync keyname
keyname = keyname.replace /hash:(.+)(:.+)$/,'hash:' + fields.category + '$2'
# update this ticket
redis.hmset keyname,options,(err,reply)->
if err
return res.render 'admin-save-ticket-no-good.pug',{title:'No Save',reason:err.message}
else
return res.render 'admin-save-ticket-success.pug',{ticket_id:ticket_id,reply:reply,title:'Updated!'}
else
res.send 'No Clear.'
# in fact,it is 'update-ticket',the query from route /admin/ticket-detail/:id
app.post '/admin/create-new-comment',(req,res)->
{keyname,comment} = req.body
lines = comment.replace(/\r\n/g,'\n').split('\n')
paras = ''
for line in lines
paras += '<p>' + line + '</p>'
comment_str = [
'<blockquote class="blockquote text-center"><p>'
paras
'</p><footer class="blockquote-footer"> <cite>发表于:</cite>'
new Date()
'<button type="button" class="ml-2 btn btn-light" data-toggle="popover" data-placement="bottom" data-content="'
req.header("user-agent")
'" title="browser infomation"> browser Info </button></footer></blockquote>'
].join ''
redis.hget keyname,'reference_comments',(err1,listkey)->
if err1
return res.json {replyText:'no good,reason:' + err1.message}
redis.lpush listkey,comment_str,(err2)->
if err2
return res.json {replyText:'no good,reason:' + err2.message}
else
redis.hincrby keyname,'visits',1,(err3)->
if err3
return res.json {replyText:'no good,reason:' + err3.message}
else
return res.json {replyText:'Good Job'}
# db operator:DELETE
app.delete '/admin/del-one-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/del-one-ticket'
return res.redirect 303,'/admin/login'
else
# check if has 'with-media' flag.
{keyname,with_media} = req.query
if with_media is 'true'
# 'media' is media's path
redis.hget keyname,'media',(err,reply)->
# remember that : media url !== fs path
media = path.join __dirname,'public',reply
# check if media path exists yet.
fs.stat media,(err,stats)->
intReply = await delAsync keyname
if err
# just del item from redis db,file system del failure.
res.send '删除条目' + intReply + '条,media file not clear,because:' + err.message
else
fs.unlink media,(err2)->
if err2 is null
res.send '删除条目' + intReply + '条,media file clear.'
else
res.send '删除条目' + intReply + '条,media file not clear,because:' + err2.message
else
try
# del its referencing comments
referencing_comments = await hgetAsync keyname,'reference_comments'
referenceDeleted = await delAsync referencing_comments
keyDeleted = await delAsync keyname
res.send '删除条目' + keyDeleted + '条,删除评论' + referenceDeleted + '条.'
catch error
res.send error.message
app.get '/admin/del-all-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/del-all-tickets'
return res.redirect 303,'/admin/login'
else
redis.keys TICKET_PREFIX + ':hash:*',(err,list)->
for item in list
await delAsync item
# at last ,report to client.
res.render 'admin-del-all-tickets'
# 投稿
app.post '/admin/contribute',(req,res)->
if req.session?.auth?.role isnt 'admin'
return res.json 'auth error.'
{keyname,to_address,to_port} = req.body
to_port = '80' if to_port is ''
if not keyname or not to_address
return res.json 'invalidate data.'
prefix_url = 'http://' + to_address + ':' + to_port
# retrieve item
request = require 'superagent'
agent = request.agent()
try
o = await hgetallAsync keyname
catch error
return res.json 'DB Operator Error.'
agent.post prefix_url+ '/admin/login'
.type 'form'
.send {'alias':'agent'}
.send {'password':'1234567'} # solid password for this task.
.end (err,reply)->
if err
return res.json err
# TODO if not match admin:password,err is null,but something is out of your expecting.
if not o.media
agent.post prefix_url + '/admin/create-new-ticket'
.send {
'admin_alias':'agent'
'title':o.title
'ticket':o.ticket
'client_time':o.client_time
'category':o.category
'visits':o.visits
'agent_post_time':(new Date()).toISOString()
}
.end (err,resp)->
if err
return res.json err
res.json resp.status
else # has media attribute
attachment = path.join __dirname,'public',o.media
agent.post prefix_url + '/admin/create-new-ticket'
.field 'alias','agent'
.field 'title',o.title
.field 'ticket',o.ticket
.field 'client_time',o.client_time
.field 'category',o.category
.field 'visits',o.visits
.field 'agent_post_time',(new Date()).toISOString()
.attach 'media',attachment
.end (err,resp)->
if err
return res.json err
res.json resp.status
app.get '/admin/get-ticket-by-id/:id',(req,res)->
ticket_id = req.params.id
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/get-ticket-by-id/' + ticket_id
return res.redirect 303,'/admin/login'
redis.keys TICKET_PREFIX + ':hash:*:' + ticket_id,(err,list)->
if err
res.json {status:'Error Occurs While Retrieving This Id.'}
else
if list.length is 0
res.render 'admin-ticket-no-found.pug',{status:'This Ticket Id No Found'}
else
item = await hgetallAsync list[0]
item.comments = await lrangeAsync item.reference_comments,0,-1
# add for template - 'views/admin-ticket-detail.pug'(20190910 at hanjie he dao)
item.keyname = list[0]
# add 1 to 'visits'
redis.hincrby list[0],'visits',1,(err,num)->
if err is null
res.render 'admin-ticket-detail',{title:'#' + item.ticket_id + ' Detail Page',item:item}
else
res.json 'Error Occurs During DB Manipulating.'
app.post '/admin/ticket-details',(req,res)->
ticket_id = req.body.ticket_id
redis.keys TICKET_PREFIX + ':hash:*:' + ticket_id,(err,list)->
if err
res.json {status:'Error Occurs While Retrieving This Id.'}
else
if list.length is 0
res.render 'admin-ticket-no-found.pug',{status:'This Ticket Id No Found'}
else
# add 1 to 'visits'
redis.hincrby list[0],'visits',1,(err,num)->
if err is null
item = await hgetallAsync list[0]
item.keyname = list[0]
item.comments = await lrangeAsync item.reference_comments,0,-1
#res.render 'admin-newest-ticket.pug',{title:'Detail Page #' + ticket_id,records:[item]}
res.redirect 302,'/admin/get-ticket-by-id/' + ticket_id
else
res.json 'Error Occurs During DB Manipulating.'
app.all '/admin/full-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/full-tickets'
return res.redirect 303,'/admin/login'
if req.method is 'GET'
redis.scan [0,'match','ticket:hash*','count','29'],(err,list)->
items = []
for key in list[1]
item = await hgetallAsync key
items.push item
res.render 'admin-full-tickets.pug',{next:list[0],items:items,title:'Full Indexes'}
else if req.method is 'POST'
redis.scan [req.body.nextCursor,'match','ticket:hash*','count','29'],(err,list)->
if err
res.json 'in case IS POST AND SCAN OCCURS ERROR.'
else
items = []
for key in list[1]
item = await hgetallAsync key
items.push item
res.json {items:items,next:list[0]}
else
res.json 'unknown.'
app.get '/admin/category-of-tickets/:category',(req,res)->
category = req.params.category
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/category-of-tickets/' + category
return res.redirect 303,'/admin/login'
else
keyname = TICKET_PREFIX + ':hash:' + category + '*'
records = await _retrieves keyname,(a,b)->b.ticket_id - a.ticket_id
if records.length > 20
records = records[0...20]
res.render 'admin-newest-ticket.pug',{records:records,title:'分类列表:'+category + 'top 20'}
app.get '/admin/visits-base-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/visits-base-tickets/'
return res.redirect 303,'/admin/login'
else
keyname = TICKET_PREFIX + ':hash:*'
records = await _retrieves keyname,(a,b)->b.visits - a.visits
if records.length > 20
records = records[0...20]
res.render 'admin-newest-ticket.pug',{records:records,title:'top 20 visits tickets'}
app.get '/admin/newest-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/newest-ticket'
return res.redirect 303,'/admin/login'
else
keypattern = TICKET_PREFIX + ':hash:*'
# at zhongnan hospital,fixed below await-func(inner help function - '_retrieves'
records = await _retrieves(keypattern,((a,b)->b.ticket_id - a.ticket_id))
# retrieve top 20 items.
if records.length > 20
records = records[0...20]
return res.render 'admin-newest-ticket.pug',{'title':'list top 20 items.',records:records}
app.post '/admin/enable-user',(req,res)->
id = req.body.id
try
ins = await Nohm.factory 'account',id
ins.property 'isActive',true
await ins.save()
res.json {code:0,message:'update user,now user in active-status.' }
catch error
reason = {
thrown: error
nohm_said:ins.errors
}
res.json {code:-1,reason:reason}
app.post '/admin/disable-user',(req,res)->
id = req.body.id
try
ins = await Nohm.factory 'account',id
ins.property 'isActive',false
await ins.save()
res.json {code:0,message:'update user,now user in disable-status.' }
catch error
reason = {
thrown: error
nohm_said:ins.errors
}
res.json {code:-1,reason:reason}
app.all '/admin/dynamic-indexes',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/dynamic-indexes'
return res.redirect 303,'/admin/login'
if req.method is 'GET'
range = parseInt req.query.range
if (range isnt 100) and (range isnt 200)
return res.render 'admin-range-list',{error:'Warning:Invalid Query.',title:'Range List'}
redis.keys 'ticket:hash*',(err,list)->
results = []
list = list.sort (a,b)->
aid = parseInt a.split(":")[3]
bid = parseInt b.split(":")[3]
bid - aid
list = list[0..range] # slice
for item in list
o = await hgetallAsync item
results.push o
return res.render 'admin-range-list.pug',{title:'Range List',thelist:results}
else # IN "POST" CASE
start = parseInt req.body.start
end = parseInt req.body.end
if start isnt -(-start) or end isnt -(-end)
return res.render 'admin-range-list',{error:'Warning:Querying Range Exceed.',title:'Range List'}
console.dir {start,end}
current = await getAsync(TICKET_PREFIX + ':counter')
current = parseInt current
results = []
if (start < 0) or (end <= 0) or (end <= start) or (end > current) or ((end-start) > 100)
return res.render 'admin-range-list',{error:'Warning:Querying Range Exceed.',title:'Range List'}
else
redis.keys 'ticket:hash*',(err,list)->
list = list.filter (item)->
num = parseInt item.split(":")[3]
if num > end
return false
else if num < start
return false
true
list = list.sort (a,b)->
aid = parseInt a.split(":")[3]
bid = parseInt b.split(":")[3]
bid - aid
for tid in list
o = await hgetallAsync tid
results.push o
return res.render 'admin-range-list',{thelist:results,title:'Range List'}
app.put '/admin/del-user',(req,res)->
ins = await Nohm.factory 'account'
# req.query.id be transimit from '/admin/list-users' page.
id = req.body.id
ins.id = id
try
await ins.remove()
catch error
return res.json {code:-1,'reason':JSON.stringify(ins.errors)}
return res.json {code:0,'gala':'remove #' + id + ' success.'}
app.post '/admin/login',(req,res)->
{itisreferrer,alias,password} = req.body
itisreferrer = itisreferrer or '/admin/login-success'
# filter alias,and password
isInvalid = ( !(filter alias) or !(filter password) )
if isInvalid
return res.render 'admin-login-failure',{title:'Login-Failure',reason:'表单中含有非法字符.'}
# initial session.auth
initSession req
# first check if exists this alias name?
# mobj is 'match stats object'
mobj = await matchDB accountModel,alias,'admin',password
if mobj.match_result
# till here,login data is matches.
updateAuthSession req,'admin',alias
res.redirect 303,itisreferrer
else
updateAuthSession req,'unknown','noname'
res.render 'admin-login-failure' ,{title:'Login-Failure',reason:'管理员登录失败,原因:帐户不存在或者帐户被临时禁用或者帐户名与口令不匹配。'}
app.get '/admin/login-success',(req,res)->
res.render 'admin-login-success.pug',{title:'Administrator Role Entablished'}
app.get '/admin/checkout-daka',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/checkout-daka'
return res.redirect 303,'/admin/login'
# query all user's name
inss = await accountModel.findAndLoad {role:'user'}
aliases = ( ins.property('alias') for ins in inss )
res.render 'admin-checkout-daka',{aliases:aliases,title:'Checkout-One-User-DaKa'}
# route /daka database interaction
app.get '/daka/one',(req,res)->
{user,range} = req.query
ids = await dakaModel.find {alias:user,utc_ms:{min:0}}
sorted = await dakaModel.sort {'field':'utc_ms'},ids
hashes = []
for id in sorted
ins = await dakaModel.load id
hashes.push ins.allProperties()
res.json hashes
app.get '/admin/list-user-daka',(req,res)->
alias = req.query.alias
if ! alias
return res.json 'no special user,check and redo.'
if not filter alias
return res.json 'has invalid char(s).'
# first,check role if is admin
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/list-user-daka?alias=' + alias
return res.redirect 303,'/admin/login'
inss = await dakaModel.findAndLoad alias:alias
result = []
for ins in inss
obj = ins.allProperties()
result.push obj
res.render 'admin-list-user-daka',{alias:alias,title:'List User DaKa Items',data:result}
app.get '/admin/list-users',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/list-users'
return res.redirect 303,'/admin/login'
inss = await accountModel.findAndLoad({'role':'user'})
results = []
inss.forEach (one)->
obj = {}
obj.alias = one.property 'alias'
obj.role = one.property 'role'
obj.initial_timestamp = one.property 'initial_timestamp'
obj.password = one.property 'password'
obj.isActive = one.property 'isActive'
obj.id = one.id
results.push obj
res.render 'admin-list-users',{title:'Admin:List-Users',accounts:results}
app.get '/superuser/list-admins',(req,res)->
if req.session?.auth?.role isnt 'superuser'
req.session.referrer = '/superuser/list-admins'
return res.redirect 303,'/superuser/login'
inss = await accountModel.findAndLoad {'role':'admin'}
results = []
inss.forEach (one)->
obj = {}
obj.alias = one.property 'alias'
obj.role = one.property 'role'
obj.initial_timestamp = one.property 'initial_timestamp'
obj.password = one.property 'password'
obj.id = one.id
results.push obj
res.render 'superuser-list-admins',{title:'List-Administrators',accounts:results}
app.get '/superuser/list-tickets/:category',(req,res)->
pattern = [TICKET_PREFIX,'hash',req.params.category,'*'].join ':'
redis.keys pattern,(err,keys)->
# this is a good sample about redis-multi way.maybe multi is perfom better than hgetallAsync.
list = redis.multi()
for key in keys
list.hgetall key
list.exec (err,replies)->
if err
return res.json err
else
return res.render 'superuser-list-tickets',{title:'list tickets',tickets:replies}
app.put '/superuser/del-admin',(req,res)->
ins = await Nohm.factory 'account'
# req.query.id be transimit from '/superuser/list-admins' page.
id = req.query.id
ins.id = id
try
await ins.remove()
catch error
return res.json {code:-1,'reason':JSON.stringify(ins.errors)}
return res.json {code:0,'gala':'remove #' + id + ' success.'}
app.all '/superuser/daka-complement',(req,res)->
if req.session?.auth?.role isnt 'superuser'
req.session.referrer = '/superuser/daka-complement'
return res.redirect 303,'/superuser/login'
if req.method is 'POST'
# client post via xhr,so server side use 'formidable' module
formid = new formidable.IncomingForm
formid.parse req,(err,fields,files)->
if err
res.json {code:-1}
else
# store
objs = convert fields
responses = []
for obj in objs #objs is an array,elements be made by one object
response = await complement_save obj['combo'],obj
responses.push response
# responses example:[{},[{},{}],{}...]
res.json responses
else
res.render 'superuser-daka-complement',{title:'Super User Daka-Complement'}
app.get '/superuser/login',(req,res)->
# referrer will received from middle ware
res.render 'superuser-login.pug',{title:'Are You A Super?'}
app.get '/superuser/login-success',(req,res)->
res.render 'superuser-login-success.pug',{title:'Super User Login!'}
app.post '/superuser/login',(req,res)->
# initial sesson.auth
initSession req
{password,itisreferrer} = req.body
hash = sha256 password
if hash is superpass
updateAuthSession req,'superuser','superuser'
if itisreferrer
res.redirect 303,itisreferrer
else
res.redirect 301,'/superuser/login-success'
else
updateAuthSession req,'unknown','noname'
res.json {staus:'super user login failurre.'}
app.get '/superuser/register-admin',(req,res)->
if req.session?.auth?.role isnt 'superuser'
res.redirect 302,'/superuser/login'
else
res.render 'superuser-register-admin',{defaultValue:'1234567',title:'Superuser-register-admin'}
app.get '/superuser/delete-all-daka-items',(req,res)->
if req.session?.auth?.role isnt 'superuser'
return res.json 'wrong:must role is superuser.'
# delete all daka items,be cafeful.
multi = redis.multi()
redis.keys DAKA_WILDCARD,(err,keys)->
for key in keys
multi.del key
multi.exec (err,replies)->
res.json replies
app.post '/superuser/register-admin',(req,res)->
{adminname} = req.body
if ! filter adminname
return res.json 'Wrong:Admin Name(alias) contains invalid character(s).'
ins = await Nohm.factory 'account'
ins.property
alias:adminname
role:'admin'
initial_timestamp:Date.parse new Date
password: hashise '1234567' # default password.
try
await ins.save()
res.json 'Saved.'
catch error
res.json ins.errors
app.get '/no-staticify',(req,res)->
# listen radio(voa&rfa mandarin)
fs.readdir path.join(STATIC_ROOT,'audioes'),(err,list)->
if err is null
audio_list = []
for item in list
realpath = path.join STATIC_ROOT,'audioes',item
if (fs.statSync realpath).isFile()
audio_list.push path.join '/audioes',item
res.render 'no-staticify',{title:'list audioes',list:audio_list}
else
res.render 'no-staticify-failure',{title:'you-see-failure',error_reason:err.message}
app.delete '/remove-readed-audio',(req,res)->
if req.body.data
uri = path.join 'public',req.body.data
bool = fs.existsSync uri
if bool
fs.unlinkSync uri
res.json {status:'has deleted.'}
else
res.json {status:'no found'}
else
res.json {status:'not good'}
# during learn css3,svg..,use this route for convient.
app.use '/staticify/:viewname',(req,res)->
res.render 'staticify/' + req.params.viewname,{title:'it is staticify page'}
app.use (req,res)->
res.status 404
res.render '404'
app.use (err,req,res,next)->
console.error 'occurs 500 error. [[ ' + err.stack + ' ]]'
res.type 'text/plain'
res.status 500
res.send '500 - Server Error!'
if require.main is module
server = http.Server app
server.listen 3003,->
console.log 'server running at port 3003;press Ctrl-C to terminate.'
else
module.exports = app
# initSession is a help function
initSession = (req)->
if not req.session?.auth
req.session.auth =
alias:'noname'
counter:0
tries:[]
matches:[]
role:'unknown'
null
# updateAuthSession is a help function
# this method be invoked by {user|admin|superuser}/login (post request)
updateAuthSession = (req,role,alias)->
timestamp = new Date
counter = req.session.auth.counter++
req.session.auth.tries.push 'counter#' + counter + ':user try to login at ' + timestamp
req.session.auth.role = role
req.session.auth.alias = alias
if role is 'unknown'
req.session.auth.matches.push '*Not* Matches counter#' + counter + ' .'
else
req.session.auth.matches.push 'Matches counter#' + counter + ' .'
# hashise is a help function.
hashise = (plain)->
hash = crypto.createHash 'sha256'
hash.update plain
hash.digest 'hex'
# filter is a help function
filter = (be_dealt_with)->
# return true is safe,return false means injectable.
if not be_dealt_with
return false
return not /\W/.test be_dealt_with
# matchDB is a help function
# *Notice that* invoke this method via "await <this>"
matchDB = (db,alias,role,password)->
# db example 'accountModel'
items = await db.findAndLoad {'alias':alias}
if items.length is 0 # means no found.
return false
else
item = items[0]
dbpassword = item.property 'password'
dbrole = item.property 'role'
isActive = item.property 'isActive'
warning = ''
if dbpassword is '8bb0cf6eb9b17d0f7d22b456f121257dc1254e1f01665370476383ea776df414'
warning = 'should change this simple/initial/templory password immediately.'
match_result = (isActive) and ((hashise password) is dbpassword) and (dbrole is role)
return {match_result:match_result,warning:warning}
# for authenticate super user password.
sha256 = (plain)->
crypto.createHash 'sha256'
.update plain
.digest 'hex'
# help func convert,can convert formidable's fields object to an object arrary(for iterator store in redis).
convert = (fields)->
results = []
for i,v of fields
matched = i.match /(\D*)(\d*)$/
pre = matched[1]
post = matched[2]
if (post in Object.keys(results)) is false
results[post] = {}
results[post][pre] = v
results
# help function - complement_save()
# complement_save handle single object(one form in client side).
complement_save = (option,fieldobj)->
# option always is uploaded object's field - option
response = undefined
# inner help function - single_save()
single_save = (standard)->
ins = await Nohm.factory 'daily'
ins.property standard
try
await ins.save()
catch error
console.dir error
return {'item-id':ins.id,'saved':false,reason:ins.errors}
return {'item-id':ins.id,'saved':true}
switch option
when 'option1'
standard =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['first-half-']
whatistime:fieldobj['first-half-']
dakaer:'superuser'
category:'entry'
browser:req.headers['user-agent']
response = await single_save standard
when 'option2'
standard =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['second-half-']
whatistime:fieldobj['second-half-']
dakaer:'superuser'
category:'exit'
browser:req.headers['user-agent']
response = await single_save standard
when 'option3'
standard1 =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['first-half-']
whatistime:fieldobj['first-half-']
dakaer:'superuser'
browser:req.headers['user-agent']
category:'entry'
standard2 =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['second-half-']
whatistime:fieldobj['second-half-']
dakaer:'superuser'
browser:req.headers['user-agent']
category:'exit'
# save 2 instances.
response1 = await single_save standard1
response2 = await single_save standard2
response = [response1,response2]
else
response = {code:-1,reason:'unknow status.'}
response
# help function - '_save_one_ticket'
_save_one_ticket = (req,res,form,redis)->
form.parse req,(err,fields,files)->
if err
return res.render 'admin-save-ticket-no-good.pug',{title :'No Save',reason:err.message}
options = ['visits','0','urge','0','resolved','false']
for k,v of fields
options = options.concat [k,v]
if files.media and files.media.size is 0
fs.unlinkSync files.media.path
if files.media and files.media.size isnt 0
media_url = files.media.path
# for img or other media "src" attribute,the path is relative STATIC-ROOT.
media_url = '/tickets/' + media_url.replace /.*\/(.+)$/,"$1"
options = options.concat ['media',media_url,'media_type',files.media.type]
# store this ticket
redis.incr (TICKET_PREFIX + ':counter'),(err,number)->
if err isnt null # occurs error.
return res.json 'Occurs Error While DB Operation.' + err.message
keyname = [TICKET_PREFIX,'hash',fields.category,number].join ':'
options = options.concat ['ticket_id',number,'reference_comments','comments-for-' + number]
redis.hmset keyname,options,(err,reply)->
if err
return res.json 'Occurs Error During Creating,Reason:' + err.message
else
# successfully
return res.render 'admin-save-ticket-success.pug',{ticket_id:number,reply:reply,title:'Stored Success'}
# help function 'retrieves',for retrieves ticket by its first argument.
_retrieves = (keyname,sortby)->
promise = new Promise (resolve,reject)->
redis.keys keyname,(err,list)->
records = []
for item in list
record = await hgetallAsync item
bool = await existsAsync record.reference_comments
if bool
comments = await lrangeAsync record.reference_comments,0,-1
# give new attribute 'comments'
record.comments = comments
else
record.comments = []
# keyname 将用于$.ajax {url:'/admin/del-one-ticket?keyname=' + keyname....
record.keyname = item
records.push record
#sorting before output to client.
records.sort sortby
resolve records
return promise
| 42187 | # firssts of first check if 'redis-server' is running.
{spawn} = require 'child_process'
# this for redis promisify(client.get),the way inpirit from npm-redis.
{promisify} = require 'util'
pgrep = spawn '/usr/bin/pgrep',['redis-server']
pgrep.on 'close',(code)->
if code isnt 0
console.log 'should run redis-server first.'
process.exit 1
path = require 'path'
fs = require 'fs'
http = require 'http'
qr_image = require 'qr-image'
formidable = require 'formidable'
crypto = require 'crypto'
# super-user's credential
fs.stat './configs/credentials/super-user.js',(err,stats)->
if err
console.log 'Credential File Not Exists,Fix It.'
process.exit 1
credential = require './configs/credentials/super-user.js'
hostname = require './configs/hostname.js'
superpass = credential.password
# ruler for daka app am:7:30 pm:18:00
ruler = require './configs/ruler-of-daka.js'
{Nohm} = require 'nohm'
Account = require './modules/md-account'
Daka = require './modules/md-daka'
dakaModel = undefined
accountModel = undefined
TICKET_PREFIX = 'ticket'
TICKET_MEDIA_ROOT = path.join __dirname,'public','tickets'
DAKA_WILDCARD = 'DaKa*daily*'
ACCOUNT_WILDCARD='DaKa*account*'
redis = (require 'redis').createClient()
setAsync = promisify redis.set
.bind redis
getAsync = promisify redis.get
.bind redis
expireAsync = promisify redis.expire
.bind redis
existsAsync = promisify redis.exists
.bind redis
delAsync = (key)->
new Promise (resolve,reject)->
redis.del key,(err,intReply)->
if err
reject err
else
resolve intReply
hgetAsync = (key,index)->
new Promise (resolve,reject)->
redis.hget key,index,(err,value)->
if err
reject err
else
resolve value
hgetallAsync = (key)->
new Promise (resolve,reject)->
redis.hgetall key,(err,record)->
if err
reject err
else
resolve record
lrangeAsync = (key,start,end)->
new Promise (resolve,reject)->
redis.lrange key,start,end,(err,items)->
if err
reject err
else
resolve items
redis.on 'error',(err)->
console.log 'Heard that:',err
redis.on 'connect',->
Nohm.setClient @
Nohm.setPrefix 'DaKa' # the main api name.
# register the 2 models.
dakaModel = Nohm.register Daka
accountModel = Nohm.register Account
express = require 'express'
app = express()
app.set 'view engine','pug'
STATIC_ROOT = path.join __dirname,'public'
app.use express.static STATIC_ROOT
# enable "req.body",like the old middware - "bodyParser"
app.use express.urlencoded({extended:false})
# session
Session = require 'express-session'
Store = (require 'connect-redis') Session
# authenticate now
redis_auth_pass = require './configs/redis/auth_pass.js'
redis.auth redis_auth_pass,(err,reply)->
if err
console.error 'redis db authenticate failure.'
return process.exit -1
# start add all middle-ware
app.use Session {
cookie:
maxAge: 86400 * 1000 # one day.
httpOnly:true
path:'/' # 似乎太过宽泛,之后有机会会琢磨这个
secret: 'youkNoW.'
store: new Store {client:redis}
resave:false
saveUninitialized:true
}
app.use (req,res,next)->
res.locals.referrer = req.session.referrer
delete req.session.referrer # then,delete() really harmless
next()
app.get '/',(req,res)->
role = req.session?.auth?.role
alias = req.session?.auth?.alias
if role is 'unknown' and alias is 'noname'
[role,alias] = ['visitor','hi']
res.render 'index'
,
title:'welcome-daka'
role:role
alias:alias
app.get '/alpha/:tpl',(req,res)->
tpl = req.params.tpl # client send /alpha?tpl=something
# Notice:all template in views/alpha,use layout via "../layouts"
res.render 'alpha/' + tpl,{'title':'Alpha!'}
app.get '/create-check-words',(req,res)->
# 如果用户选择了填表单方式来打卡。
digits = [48..57] # 0..9
alpha = [97...97+26] # A..Z
chars = digits.concat alpha
.concat digits
.concat alpha
# total 72 chars,so index max is 72-1=71
{round,random} = Math
words = for _ in [1..5] # make length=5 words
index = round random()*71
String.fromCharCode chars[index]
words = words.join ''
# 存储check words到redis数据库,并设置超时条件。
await setAsync 'important',words
await expireAsync 'important',60
res.json words
app.get '/create-qrcode',(req,res)->
# the query string from user-daka js code(img.src=url+'....')
# query string include socketid,timestamp,and alias
text = [req.query.socketid,req.query.timestamp].join('-')
await setAsync 'important',text
await expireAsync 'important',60
# templary solid ,original mode is j602
fulltext = hostname + '/user/daka-response?mode=' + req.query.mode + '&&alias=' + req.query.alias + '&&check=' + text
res.type 'png'
qr_image.image(fulltext).pipe res
# maniuate new func or new mind.
app.get '/user/daka',(req,res)->
if req.session?.auth?.role isnt 'user'
req.session.referrer = '/user/daka'
res.redirect 303,'/user/login'
else
# check which scene the user now in?
user = req.session.auth.alias
# ruler object
today = new Date
today.setHours ruler.am.hours
today.setMinutes ruler.am.minutes
today.setSeconds 0
ids = await dakaModel.find {alias:user,utc_ms:{min:Date.parse today}}
# mode变量值为0提示“入场”待打卡状态,1则为“出场”待打卡状态。
res.render 'user-daka',{mode:ids.length,alias:user,title:'User DaKa Console'}
app.get '/user/login',(req,res)->
res.render 'user-login',{title:'Fill User Login Form'}
app.post '/user/login',(req,res)->
# reference line#163
{itisreferrer,alias,password} = req.body
itisreferrer = itisreferrer or '/user/login-success'
# filter these 2 strings for anti-injecting
isInvalidation = (! filter alias or ! filter password)
if isInvalidation
return res.render 'user-login-failure',{reason: '含有非法字符(只允许ASCII字符和数字)!',title:'User-Login-Failure'}
# auth initialize
initSession req
# first check if exists this alias name?
# mobj is 'match stats object'
mobj = await matchDB accountModel,alias,'user',password
if mobj.match_result
# till here,login data is matches.
updateAuthSession req,'user',alias
res.redirect 303,itisreferrer
else
updateAuthSession req,'unknown','noname'
return res.render 'user-login-failure',{reason: '用户登录失败,原因:帐户不存在/帐户被临时禁用/账户口令不匹配。',title:'User-Login-Failure'}
app.put '/user/logout',(req,res)->
role = req.session?.auth?.role
if role is 'user'
req.session.auth.role = 'unknown'
req.session.auth.alias = 'noname'
res.json {code:0,reason:'',status:'logout success'}
else
res.json {code:-1,reason:'No This Account Or Role Isnt User.',status:'logout failure'}
app.get '/user/login-success',(req,res)->
res.render 'user-login-success',{title:'User Role Validation:successfully'}
# user choiced alternatively way to daka
app.post '/user/daka-response',(req,res)->
check = req.body.check
# get from redis db
words = await getAsync 'important'
session_alias = req.session?.auth?.alias
if words is check
# save this daka-item
try
obj = new Date
desc = obj.toString()
ms = Date.parse obj
ins = await Nohm.factory 'daily'
ins.property
alias: session_alias
utc_ms: ms
whatistime: desc
browser: req.headers["user-agent"]
category:req.body.mode # 'entry' or 'exit' mode
await ins.save()
# notice admin with user's success.
# the .js file include socket,if code=0,socket.emit 'code','0'
return res.render 'user-daka-response-success',{code:'0',title:'login Result',status:'打卡成功',user:session_alias}
catch error
# notice admin with user's failure.
# js file include socket,if code=-1,socket.emit 'code','-1'
# show db errors
console.dir ins.errors
return res.render 'user-daka-response-failure',{title:'daka failure','reason':ins.errors,code:'-1',user:session_alias,status:'数据库错误,打卡失败。'}
else
return res.render 'user-daka-response-failure',{title:'daka failure',status:'打卡失败',code:'-1',reason:'超时或验证无效',user:session_alias}
# user daka via QR code (scan software)
app.get '/user/daka-response',(req,res)->
session_alias = req.session?.auth?.alias
if session_alias is undefined
req.session.referrer = '/user/daka-response'
return res.redirect 303,'/user/login'
if req.query.alias isnt session_alias
return res.json {status:'alias inconsistent',warning:'you should requery daka and visit this page via only one browser',session:session_alias,querystring:req.query.alias}
# user-daka upload 'text' via scan-qrcode-then-goto-url.
text = req.query.check
dbkeep= await getAsync 'important'
if dbkeep isnt '' and text isnt '' and dbkeep is text
# save this daka-item
try
obj = new Date
desc = obj.toString()
ms = Date.parse obj
ins = await Nohm.factory 'daily'
ins.property
# if client has 2 difference browser,one for socketio,and one for qrcode-parser.how the 'alias' value is fit?
alias: req.query.alias # or req.session.auth.alias
utc_ms: ms
whatistime: desc
browser: req.headers["user-agent"]
category:req.query.mode # 'entry' or 'exit' mode
await ins.save()
# notice admin with user's success.
# the .js file include socket,if code=0,socket.emit 'code','0'
return res.render 'user-daka-response-success',{code:'0',title:'login Result',status:'打卡成功',user:req.query.alias}
catch error
console.log 'error',error
# notice admin with user's failure.
# the .js file include socket,if code=-1,socket.emit 'code','-1'
# show db errors
return res.render 'user-daka-response-failure',{title:'daka failure','reason':ins.errors,code:'-1',user:req.query.alias,status:'数据库错误,打卡失败。'}
else
return res.render 'user-daka-response-failure',{title:'daka failure',status:'打卡失败',code:'-1',reason:'超时或身份验证无效',user:req.query.alias}
# start-point-admin
app.get '/admin/daka',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/daka'
res.redirect 303,'/admin/login'
else
res.render 'admin-daka',{title:'Admin Console'}
app.get '/admin/login',(req,res)->
# pagejs= /mine/mine-admin-login.js
res.render 'admin-login',{title:'Fill Authentication Form'}
app.get '/admin/admin-update-password',(req,res)->
res.render 'admin-update-password',{title:'Admin-Update-Password'}
app.put '/admin/logout',(req,res)->
role = req.session?.auth?.role
if role is 'admin'
req.session.auth.role = 'unknown'
req.session.auth.alias = 'noname'
res.json {reason:'',status:'logout success'}
else
# notice that,if client logout failure,not change its role and alias
res.json {reason:'no this account or role isnt admin.',status:'logout failure'}
app.post '/admin/admin-update-password',(req,res)->
{oldpassword,newpassword,alias} = req.body
items = await accountModel.findAndLoad {alias:alias}
if items.length is 0
res.json 'no found!'
else
item = items[0]
dbkeep = item.property 'password'
if dbkeep is hashise oldpassword
# update this item's password part
item.property 'password',hashise newpassword
try
item.save()
catch error
return res.json item.error
return res.json 'Update Password For Admin.'
else #password is mismatches.
return res.json 'Mismatch your oldpassword,check it.'
app.get '/admin/register-user',(req,res)->
if req.session?.auth?.role isnt 'admin'
res.redirect 302,'/admin/login'
else
res.render 'admin-register-user',{title:'Admin-Register-User'}
app.post '/admin/register-user',(req,res)->
{alias,password} = req.body
if ! filter alias or ! filter password
return res.json 'Wrong:User Name(alias) contains invalid character(s).'
ins = await Nohm.factory 'account'
ins.property
alias:alias
role:'user'
initial_timestamp:Date.parse new Date
# always remember:hashise!!
password: <PASSWORD>
try
await ins.save()
res.json 'Register User - ' + alias
catch error
res.json ins.errors
# db operator:FIND(superuser,admin are need list all tickets)
# db operator:ADD
app.all '/admin/create-new-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/create-new-ticket'
return res.redirect 303,'/admin/login'
# redis instance already exists - 'redis'
if req.method is 'GET'
res.render 'admin-create-new-ticket',{alias:req.session.auth.alias,title:'Admin-Create-New-Ticket'}
else # POST
# let npm-formidable handles
formid = new formidable.IncomingForm
formid.uploadDir = TICKET_MEDIA_ROOT
formid.keepExtensions = true
formid.maxFileSize = 20 * 1024 * 1024 # update to 200M,for video
_save_one_ticket req,res,formid,redis
app.all '/admin/edit-ticket/:keyname',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/edit-ticket/' + req.params.keyname
return res.redirect 303,'/admin/login'
keyname = req.params.keyname
if req.method is 'GET'
# because it first from a inner-click,so not worry about if key exists.
item = await hgetallAsync keyname
res.render 'admin-edit-ticket-form',{keyname:keyname,title:'admin edit ticket',item:item}
else if req.method is 'POST'
item = await hgetallAsync keyname
options = item # todo.
ticket_id = item.ticket_id
formid = new formidable.IncomingForm
formid.uploadDir = TICKET_MEDIA_ROOT
formid.keepExtensions = true
formid.maxFileSize = 20 * 1024 * 1024 # update maxFileSize to 200M if supports video
formid.parse req,(formid_err,fields,files)->
if formid_err
return res.render 'admin-save-ticket-no-good.pug',{title:'No Save',reason:formid_err.message}
for k,v of fields
if k isnt 'original_uri'
options[k] = v
if files.media.size is 0
bool = fs.existsSync files.media.path
if bool
fs.unlinkSync files.media.path
else
console.log 'files.media.path illegel.'
if files.media.size isnt 0
media_url = files.media.path
realpath = path.join(STATIC_ROOT,'tickets',fields.original_uri.replace(/.*\/(.+)$/,"$1"))
if fields.original_uri
fs.unlinkSync(path.join(STATIC_ROOT,'tickets',fields.original_uri.replace(/.*\/(.+)$/,"$1")))
media_url = '/tickets/' + media_url.replace /.*\/(.+)$/,"$1"
options['media'] = media_url
options['media_type'] = files.media.type
# 检查category是否变了
if not (new RegExp(fields.category)).test keyname
await delAsync keyname
keyname = keyname.replace /hash:(.+)(:.+)$/,'hash:' + fields.category + '$2'
# update this ticket
redis.hmset keyname,options,(err,reply)->
if err
return res.render 'admin-save-ticket-no-good.pug',{title:'No Save',reason:err.message}
else
return res.render 'admin-save-ticket-success.pug',{ticket_id:ticket_id,reply:reply,title:'Updated!'}
else
res.send 'No Clear.'
# in fact,it is 'update-ticket',the query from route /admin/ticket-detail/:id
app.post '/admin/create-new-comment',(req,res)->
{keyname,comment} = req.body
lines = comment.replace(/\r\n/g,'\n').split('\n')
paras = ''
for line in lines
paras += '<p>' + line + '</p>'
comment_str = [
'<blockquote class="blockquote text-center"><p>'
paras
'</p><footer class="blockquote-footer"> <cite>发表于:</cite>'
new Date()
'<button type="button" class="ml-2 btn btn-light" data-toggle="popover" data-placement="bottom" data-content="'
req.header("user-agent")
'" title="browser infomation"> browser Info </button></footer></blockquote>'
].join ''
redis.hget keyname,'reference_comments',(err1,listkey)->
if err1
return res.json {replyText:'no good,reason:' + err1.message}
redis.lpush listkey,comment_str,(err2)->
if err2
return res.json {replyText:'no good,reason:' + err2.message}
else
redis.hincrby keyname,'visits',1,(err3)->
if err3
return res.json {replyText:'no good,reason:' + err3.message}
else
return res.json {replyText:'Good Job'}
# db operator:DELETE
app.delete '/admin/del-one-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/del-one-ticket'
return res.redirect 303,'/admin/login'
else
# check if has 'with-media' flag.
{keyname,with_media} = req.query
if with_media is 'true'
# 'media' is media's path
redis.hget keyname,'media',(err,reply)->
# remember that : media url !== fs path
media = path.join __dirname,'public',reply
# check if media path exists yet.
fs.stat media,(err,stats)->
intReply = await delAsync keyname
if err
# just del item from redis db,file system del failure.
res.send '删除条目' + intReply + '条,media file not clear,because:' + err.message
else
fs.unlink media,(err2)->
if err2 is null
res.send '删除条目' + intReply + '条,media file clear.'
else
res.send '删除条目' + intReply + '条,media file not clear,because:' + err2.message
else
try
# del its referencing comments
referencing_comments = await hgetAsync keyname,'reference_comments'
referenceDeleted = await delAsync referencing_comments
keyDeleted = await delAsync keyname
res.send '删除条目' + keyDeleted + '条,删除评论' + referenceDeleted + '条.'
catch error
res.send error.message
app.get '/admin/del-all-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/del-all-tickets'
return res.redirect 303,'/admin/login'
else
redis.keys TICKET_PREFIX + ':hash:*',(err,list)->
for item in list
await delAsync item
# at last ,report to client.
res.render 'admin-del-all-tickets'
# 投稿
app.post '/admin/contribute',(req,res)->
if req.session?.auth?.role isnt 'admin'
return res.json 'auth error.'
{keyname,to_address,to_port} = req.body
to_port = '80' if to_port is ''
if not keyname or not to_address
return res.json 'invalidate data.'
prefix_url = 'http://' + to_address + ':' + to_port
# retrieve item
request = require 'superagent'
agent = request.agent()
try
o = await hgetallAsync keyname
catch error
return res.json 'DB Operator Error.'
agent.post prefix_url+ '/admin/login'
.type 'form'
.send {'alias':'agent'}
.send {'password':'<PASSWORD>'} # solid password for this task.
.end (err,reply)->
if err
return res.json err
# TODO if not match admin:password,err is null,but something is out of your expecting.
if not o.media
agent.post prefix_url + '/admin/create-new-ticket'
.send {
'admin_alias':'agent'
'title':o.title
'ticket':o.ticket
'client_time':o.client_time
'category':o.category
'visits':o.visits
'agent_post_time':(new Date()).toISOString()
}
.end (err,resp)->
if err
return res.json err
res.json resp.status
else # has media attribute
attachment = path.join __dirname,'public',o.media
agent.post prefix_url + '/admin/create-new-ticket'
.field 'alias','agent'
.field 'title',o.title
.field 'ticket',o.ticket
.field 'client_time',o.client_time
.field 'category',o.category
.field 'visits',o.visits
.field 'agent_post_time',(new Date()).toISOString()
.attach 'media',attachment
.end (err,resp)->
if err
return res.json err
res.json resp.status
app.get '/admin/get-ticket-by-id/:id',(req,res)->
ticket_id = req.params.id
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/get-ticket-by-id/' + ticket_id
return res.redirect 303,'/admin/login'
redis.keys TICKET_PREFIX + ':hash:*:' + ticket_id,(err,list)->
if err
res.json {status:'Error Occurs While Retrieving This Id.'}
else
if list.length is 0
res.render 'admin-ticket-no-found.pug',{status:'This Ticket Id No Found'}
else
item = await hgetallAsync list[0]
item.comments = await lrangeAsync item.reference_comments,0,-1
# add for template - 'views/admin-ticket-detail.pug'(20190910 at hanjie he dao)
item.keyname = list[0]
# add 1 to 'visits'
redis.hincrby list[0],'visits',1,(err,num)->
if err is null
res.render 'admin-ticket-detail',{title:'#' + item.ticket_id + ' Detail Page',item:item}
else
res.json 'Error Occurs During DB Manipulating.'
app.post '/admin/ticket-details',(req,res)->
ticket_id = req.body.ticket_id
redis.keys TICKET_PREFIX + ':hash:*:' + ticket_id,(err,list)->
if err
res.json {status:'Error Occurs While Retrieving This Id.'}
else
if list.length is 0
res.render 'admin-ticket-no-found.pug',{status:'This Ticket Id No Found'}
else
# add 1 to 'visits'
redis.hincrby list[0],'visits',1,(err,num)->
if err is null
item = await hgetallAsync list[0]
item.keyname = list[0]
item.comments = await lrangeAsync item.reference_comments,0,-1
#res.render 'admin-newest-ticket.pug',{title:'Detail Page #' + ticket_id,records:[item]}
res.redirect 302,'/admin/get-ticket-by-id/' + ticket_id
else
res.json 'Error Occurs During DB Manipulating.'
app.all '/admin/full-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/full-tickets'
return res.redirect 303,'/admin/login'
if req.method is 'GET'
redis.scan [0,'match','ticket:hash*','count','29'],(err,list)->
items = []
for key in list[1]
item = await hgetallAsync key
items.push item
res.render 'admin-full-tickets.pug',{next:list[0],items:items,title:'Full Indexes'}
else if req.method is 'POST'
redis.scan [req.body.nextCursor,'match','ticket:hash*','count','29'],(err,list)->
if err
res.json 'in case IS POST AND SCAN OCCURS ERROR.'
else
items = []
for key in list[1]
item = await hgetallAsync key
items.push item
res.json {items:items,next:list[0]}
else
res.json 'unknown.'
app.get '/admin/category-of-tickets/:category',(req,res)->
category = req.params.category
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/category-of-tickets/' + category
return res.redirect 303,'/admin/login'
else
keyname = <KEY>ICKET_<KEY> + ':hash:' + category + '*'
records = await _retrieves keyname,(a,b)->b.ticket_id - a.ticket_id
if records.length > 20
records = records[0...20]
res.render 'admin-newest-ticket.pug',{records:records,title:'分类列表:'+category + 'top 20'}
app.get '/admin/visits-base-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/visits-base-tickets/'
return res.redirect 303,'/admin/login'
else
keyname = <KEY>ICKET_PREFIX + ':hash:*'
records = await _retrieves keyname,(a,b)->b.visits - a.visits
if records.length > 20
records = records[0...20]
res.render 'admin-newest-ticket.pug',{records:records,title:'top 20 visits tickets'}
app.get '/admin/newest-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/newest-ticket'
return res.redirect 303,'/admin/login'
else
keypattern = TICKET_PREFIX + ':hash:*'
# at zhongnan hospital,fixed below await-func(inner help function - '_retrieves'
records = await _retrieves(keypattern,((a,b)->b.ticket_id - a.ticket_id))
# retrieve top 20 items.
if records.length > 20
records = records[0...20]
return res.render 'admin-newest-ticket.pug',{'title':'list top 20 items.',records:records}
app.post '/admin/enable-user',(req,res)->
id = req.body.id
try
ins = await Nohm.factory 'account',id
ins.property 'isActive',true
await ins.save()
res.json {code:0,message:'update user,now user in active-status.' }
catch error
reason = {
thrown: error
nohm_said:ins.errors
}
res.json {code:-1,reason:reason}
app.post '/admin/disable-user',(req,res)->
id = req.body.id
try
ins = await Nohm.factory 'account',id
ins.property 'isActive',false
await ins.save()
res.json {code:0,message:'update user,now user in disable-status.' }
catch error
reason = {
thrown: error
nohm_said:ins.errors
}
res.json {code:-1,reason:reason}
app.all '/admin/dynamic-indexes',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/dynamic-indexes'
return res.redirect 303,'/admin/login'
if req.method is 'GET'
range = parseInt req.query.range
if (range isnt 100) and (range isnt 200)
return res.render 'admin-range-list',{error:'Warning:Invalid Query.',title:'Range List'}
redis.keys 'ticket:hash*',(err,list)->
results = []
list = list.sort (a,b)->
aid = parseInt a.split(":")[3]
bid = parseInt b.split(":")[3]
bid - aid
list = list[0..range] # slice
for item in list
o = await hgetallAsync item
results.push o
return res.render 'admin-range-list.pug',{title:'Range List',thelist:results}
else # IN "POST" CASE
start = parseInt req.body.start
end = parseInt req.body.end
if start isnt -(-start) or end isnt -(-end)
return res.render 'admin-range-list',{error:'Warning:Querying Range Exceed.',title:'Range List'}
console.dir {start,end}
current = await getAsync(TICKET_PREFIX + ':counter')
current = parseInt current
results = []
if (start < 0) or (end <= 0) or (end <= start) or (end > current) or ((end-start) > 100)
return res.render 'admin-range-list',{error:'Warning:Querying Range Exceed.',title:'Range List'}
else
redis.keys 'ticket:hash*',(err,list)->
list = list.filter (item)->
num = parseInt item.split(":")[3]
if num > end
return false
else if num < start
return false
true
list = list.sort (a,b)->
aid = parseInt a.split(":")[3]
bid = parseInt b.split(":")[3]
bid - aid
for tid in list
o = await hgetallAsync tid
results.push o
return res.render 'admin-range-list',{thelist:results,title:'Range List'}
app.put '/admin/del-user',(req,res)->
ins = await Nohm.factory 'account'
# req.query.id be transimit from '/admin/list-users' page.
id = req.body.id
ins.id = id
try
await ins.remove()
catch error
return res.json {code:-1,'reason':JSON.stringify(ins.errors)}
return res.json {code:0,'gala':'remove #' + id + ' success.'}
app.post '/admin/login',(req,res)->
{itisreferrer,alias,password} = req.body
itisreferrer = itisreferrer or '/admin/login-success'
# filter alias,and password
isInvalid = ( !(filter alias) or !(filter password) )
if isInvalid
return res.render 'admin-login-failure',{title:'Login-Failure',reason:'表单中含有非法字符.'}
# initial session.auth
initSession req
# first check if exists this alias name?
# mobj is 'match stats object'
mobj = await matchDB accountModel,alias,'admin',password
if mobj.match_result
# till here,login data is matches.
updateAuthSession req,'admin',alias
res.redirect 303,itisreferrer
else
updateAuthSession req,'unknown','noname'
res.render 'admin-login-failure' ,{title:'Login-Failure',reason:'管理员登录失败,原因:帐户不存在或者帐户被临时禁用或者帐户名与口令不匹配。'}
app.get '/admin/login-success',(req,res)->
res.render 'admin-login-success.pug',{title:'Administrator Role Entablished'}
app.get '/admin/checkout-daka',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/checkout-daka'
return res.redirect 303,'/admin/login'
# query all user's name
inss = await accountModel.findAndLoad {role:'user'}
aliases = ( ins.property('alias') for ins in inss )
res.render 'admin-checkout-daka',{aliases:aliases,title:'Checkout-One-User-DaKa'}
# route /daka database interaction
app.get '/daka/one',(req,res)->
{user,range} = req.query
ids = await dakaModel.find {alias:user,utc_ms:{min:0}}
sorted = await dakaModel.sort {'field':'utc_ms'},ids
hashes = []
for id in sorted
ins = await dakaModel.load id
hashes.push ins.allProperties()
res.json hashes
app.get '/admin/list-user-daka',(req,res)->
alias = req.query.alias
if ! alias
return res.json 'no special user,check and redo.'
if not filter alias
return res.json 'has invalid char(s).'
# first,check role if is admin
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/list-user-daka?alias=' + alias
return res.redirect 303,'/admin/login'
inss = await dakaModel.findAndLoad alias:alias
result = []
for ins in inss
obj = ins.allProperties()
result.push obj
res.render 'admin-list-user-daka',{alias:alias,title:'List User DaKa Items',data:result}
app.get '/admin/list-users',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/list-users'
return res.redirect 303,'/admin/login'
inss = await accountModel.findAndLoad({'role':'user'})
results = []
inss.forEach (one)->
obj = {}
obj.alias = one.property 'alias'
obj.role = one.property 'role'
obj.initial_timestamp = one.property 'initial_timestamp'
obj.password = one.property 'password'
obj.isActive = one.property 'isActive'
obj.id = one.id
results.push obj
res.render 'admin-list-users',{title:'Admin:List-Users',accounts:results}
app.get '/superuser/list-admins',(req,res)->
if req.session?.auth?.role isnt 'superuser'
req.session.referrer = '/superuser/list-admins'
return res.redirect 303,'/superuser/login'
inss = await accountModel.findAndLoad {'role':'admin'}
results = []
inss.forEach (one)->
obj = {}
obj.alias = one.property 'alias'
obj.role = one.property 'role'
obj.initial_timestamp = one.property 'initial_timestamp'
obj.password = <PASSWORD> '<PASSWORD>'
obj.id = one.id
results.push obj
res.render 'superuser-list-admins',{title:'List-Administrators',accounts:results}
app.get '/superuser/list-tickets/:category',(req,res)->
pattern = [TICKET_PREFIX,'hash',req.params.category,'*'].join ':'
redis.keys pattern,(err,keys)->
# this is a good sample about redis-multi way.maybe multi is perfom better than hgetallAsync.
list = redis.multi()
for key in keys
list.hgetall key
list.exec (err,replies)->
if err
return res.json err
else
return res.render 'superuser-list-tickets',{title:'list tickets',tickets:replies}
app.put '/superuser/del-admin',(req,res)->
ins = await Nohm.factory 'account'
# req.query.id be transimit from '/superuser/list-admins' page.
id = req.query.id
ins.id = id
try
await ins.remove()
catch error
return res.json {code:-1,'reason':JSON.stringify(ins.errors)}
return res.json {code:0,'gala':'remove #' + id + ' success.'}
app.all '/superuser/daka-complement',(req,res)->
if req.session?.auth?.role isnt 'superuser'
req.session.referrer = '/superuser/daka-complement'
return res.redirect 303,'/superuser/login'
if req.method is 'POST'
# client post via xhr,so server side use 'formidable' module
formid = new formidable.IncomingForm
formid.parse req,(err,fields,files)->
if err
res.json {code:-1}
else
# store
objs = convert fields
responses = []
for obj in objs #objs is an array,elements be made by one object
response = await complement_save obj['combo'],obj
responses.push response
# responses example:[{},[{},{}],{}...]
res.json responses
else
res.render 'superuser-daka-complement',{title:'Super User Daka-Complement'}
app.get '/superuser/login',(req,res)->
# referrer will received from middle ware
res.render 'superuser-login.pug',{title:'Are You A Super?'}
app.get '/superuser/login-success',(req,res)->
res.render 'superuser-login-success.pug',{title:'Super User Login!'}
app.post '/superuser/login',(req,res)->
# initial sesson.auth
initSession req
{password,itisreferrer} = req.body
hash = sha256 password
if hash is superpass
updateAuthSession req,'superuser','superuser'
if itisreferrer
res.redirect 303,itisreferrer
else
res.redirect 301,'/superuser/login-success'
else
updateAuthSession req,'unknown','noname'
res.json {staus:'super user login failurre.'}
app.get '/superuser/register-admin',(req,res)->
if req.session?.auth?.role isnt 'superuser'
res.redirect 302,'/superuser/login'
else
res.render 'superuser-register-admin',{defaultValue:'1234567',title:'Superuser-register-admin'}
app.get '/superuser/delete-all-daka-items',(req,res)->
if req.session?.auth?.role isnt 'superuser'
return res.json 'wrong:must role is superuser.'
# delete all daka items,be cafeful.
multi = redis.multi()
redis.keys DAKA_WILDCARD,(err,keys)->
for key in keys
multi.del key
multi.exec (err,replies)->
res.json replies
app.post '/superuser/register-admin',(req,res)->
{adminname} = req.body
if ! filter adminname
return res.json 'Wrong:Admin Name(alias) contains invalid character(s).'
ins = await Nohm.factory 'account'
ins.property
alias:adminname
role:'admin'
initial_timestamp:Date.parse new Date
password: <PASSWORD> '<PASSWORD>' # default password.
try
await ins.save()
res.json 'Saved.'
catch error
res.json ins.errors
app.get '/no-staticify',(req,res)->
# listen radio(voa&rfa mandarin)
fs.readdir path.join(STATIC_ROOT,'audioes'),(err,list)->
if err is null
audio_list = []
for item in list
realpath = path.join STATIC_ROOT,'audioes',item
if (fs.statSync realpath).isFile()
audio_list.push path.join '/audioes',item
res.render 'no-staticify',{title:'list audioes',list:audio_list}
else
res.render 'no-staticify-failure',{title:'you-see-failure',error_reason:err.message}
app.delete '/remove-readed-audio',(req,res)->
if req.body.data
uri = path.join 'public',req.body.data
bool = fs.existsSync uri
if bool
fs.unlinkSync uri
res.json {status:'has deleted.'}
else
res.json {status:'no found'}
else
res.json {status:'not good'}
# during learn css3,svg..,use this route for convient.
app.use '/staticify/:viewname',(req,res)->
res.render 'staticify/' + req.params.viewname,{title:'it is staticify page'}
app.use (req,res)->
res.status 404
res.render '404'
app.use (err,req,res,next)->
console.error 'occurs 500 error. [[ ' + err.stack + ' ]]'
res.type 'text/plain'
res.status 500
res.send '500 - Server Error!'
if require.main is module
server = http.Server app
server.listen 3003,->
console.log 'server running at port 3003;press Ctrl-C to terminate.'
else
module.exports = app
# initSession is a help function
initSession = (req)->
if not req.session?.auth
req.session.auth =
alias:'noname'
counter:0
tries:[]
matches:[]
role:'unknown'
null
# updateAuthSession is a help function
# this method be invoked by {user|admin|superuser}/login (post request)
updateAuthSession = (req,role,alias)->
timestamp = new Date
counter = req.session.auth.counter++
req.session.auth.tries.push 'counter#' + counter + ':user try to login at ' + timestamp
req.session.auth.role = role
req.session.auth.alias = alias
if role is 'unknown'
req.session.auth.matches.push '*Not* Matches counter#' + counter + ' .'
else
req.session.auth.matches.push 'Matches counter#' + counter + ' .'
# hashise is a help function.
hashise = (plain)->
hash = crypto.createHash 'sha256'
hash.update plain
hash.digest 'hex'
# filter is a help function
filter = (be_dealt_with)->
# return true is safe,return false means injectable.
if not be_dealt_with
return false
return not /\W/.test be_dealt_with
# matchDB is a help function
# *Notice that* invoke this method via "await <this>"
matchDB = (db,alias,role,password)->
# db example 'accountModel'
items = await db.findAndLoad {'alias':alias}
if items.length is 0 # means no found.
return false
else
item = items[0]
dbpassword = item.property 'password'
dbrole = item.property 'role'
isActive = item.property 'isActive'
warning = ''
if dbpassword is '<PASSWORD>'
warning = 'should change this simple/initial/templory password immediately.'
match_result = (isActive) and ((hashise password) is dbpassword) and (dbrole is role)
return {match_result:match_result,warning:warning}
# for authenticate super user password.
sha256 = (plain)->
crypto.createHash 'sha256'
.update plain
.digest 'hex'
# help func convert,can convert formidable's fields object to an object arrary(for iterator store in redis).
convert = (fields)->
results = []
for i,v of fields
matched = i.match /(\D*)(\d*)$/
pre = matched[1]
post = matched[2]
if (post in Object.keys(results)) is false
results[post] = {}
results[post][pre] = v
results
# help function - complement_save()
# complement_save handle single object(one form in client side).
complement_save = (option,fieldobj)->
# option always is uploaded object's field - option
response = undefined
# inner help function - single_save()
single_save = (standard)->
ins = await Nohm.factory 'daily'
ins.property standard
try
await ins.save()
catch error
console.dir error
return {'item-id':ins.id,'saved':false,reason:ins.errors}
return {'item-id':ins.id,'saved':true}
switch option
when 'option1'
standard =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['first-half-']
whatistime:fieldobj['first-half-']
dakaer:'superuser'
category:'entry'
browser:req.headers['user-agent']
response = await single_save standard
when 'option2'
standard =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['second-half-']
whatistime:fieldobj['second-half-']
dakaer:'superuser'
category:'exit'
browser:req.headers['user-agent']
response = await single_save standard
when 'option3'
standard1 =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['first-half-']
whatistime:fieldobj['first-half-']
dakaer:'superuser'
browser:req.headers['user-agent']
category:'entry'
standard2 =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['second-half-']
whatistime:fieldobj['second-half-']
dakaer:'superuser'
browser:req.headers['user-agent']
category:'exit'
# save 2 instances.
response1 = await single_save standard1
response2 = await single_save standard2
response = [response1,response2]
else
response = {code:-1,reason:'unknow status.'}
response
# help function - '_save_one_ticket'
_save_one_ticket = (req,res,form,redis)->
form.parse req,(err,fields,files)->
if err
return res.render 'admin-save-ticket-no-good.pug',{title :'No Save',reason:err.message}
options = ['visits','0','urge','0','resolved','false']
for k,v of fields
options = options.concat [k,v]
if files.media and files.media.size is 0
fs.unlinkSync files.media.path
if files.media and files.media.size isnt 0
media_url = files.media.path
# for img or other media "src" attribute,the path is relative STATIC-ROOT.
media_url = '/tickets/' + media_url.replace /.*\/(.+)$/,"$1"
options = options.concat ['media',media_url,'media_type',files.media.type]
# store this ticket
redis.incr (TICKET_PREFIX + ':counter'),(err,number)->
if err isnt null # occurs error.
return res.json 'Occurs Error While DB Operation.' + err.message
keyname = [TICKET_PREFIX,'hash',fields.category,number].join ':'
options = options.concat ['ticket_id',number,'reference_comments','comments-for-' + number]
redis.hmset keyname,options,(err,reply)->
if err
return res.json 'Occurs Error During Creating,Reason:' + err.message
else
# successfully
return res.render 'admin-save-ticket-success.pug',{ticket_id:number,reply:reply,title:'Stored Success'}
# help function 'retrieves',for retrieves ticket by its first argument.
_retrieves = (keyname,sortby)->
promise = new Promise (resolve,reject)->
redis.keys keyname,(err,list)->
records = []
for item in list
record = await hgetallAsync item
bool = await existsAsync record.reference_comments
if bool
comments = await lrangeAsync record.reference_comments,0,-1
# give new attribute 'comments'
record.comments = comments
else
record.comments = []
# keyname 将用于$.ajax {url:'/admin/del-one-ticket?keyname=' + keyname....
record.keyname = item
records.push record
#sorting before output to client.
records.sort sortby
resolve records
return promise
| true | # firssts of first check if 'redis-server' is running.
{spawn} = require 'child_process'
# this for redis promisify(client.get),the way inpirit from npm-redis.
{promisify} = require 'util'
pgrep = spawn '/usr/bin/pgrep',['redis-server']
pgrep.on 'close',(code)->
if code isnt 0
console.log 'should run redis-server first.'
process.exit 1
path = require 'path'
fs = require 'fs'
http = require 'http'
qr_image = require 'qr-image'
formidable = require 'formidable'
crypto = require 'crypto'
# super-user's credential
fs.stat './configs/credentials/super-user.js',(err,stats)->
if err
console.log 'Credential File Not Exists,Fix It.'
process.exit 1
credential = require './configs/credentials/super-user.js'
hostname = require './configs/hostname.js'
superpass = credential.password
# ruler for daka app am:7:30 pm:18:00
ruler = require './configs/ruler-of-daka.js'
{Nohm} = require 'nohm'
Account = require './modules/md-account'
Daka = require './modules/md-daka'
dakaModel = undefined
accountModel = undefined
TICKET_PREFIX = 'ticket'
TICKET_MEDIA_ROOT = path.join __dirname,'public','tickets'
DAKA_WILDCARD = 'DaKa*daily*'
ACCOUNT_WILDCARD='DaKa*account*'
redis = (require 'redis').createClient()
setAsync = promisify redis.set
.bind redis
getAsync = promisify redis.get
.bind redis
expireAsync = promisify redis.expire
.bind redis
existsAsync = promisify redis.exists
.bind redis
delAsync = (key)->
new Promise (resolve,reject)->
redis.del key,(err,intReply)->
if err
reject err
else
resolve intReply
hgetAsync = (key,index)->
new Promise (resolve,reject)->
redis.hget key,index,(err,value)->
if err
reject err
else
resolve value
hgetallAsync = (key)->
new Promise (resolve,reject)->
redis.hgetall key,(err,record)->
if err
reject err
else
resolve record
lrangeAsync = (key,start,end)->
new Promise (resolve,reject)->
redis.lrange key,start,end,(err,items)->
if err
reject err
else
resolve items
redis.on 'error',(err)->
console.log 'Heard that:',err
redis.on 'connect',->
Nohm.setClient @
Nohm.setPrefix 'DaKa' # the main api name.
# register the 2 models.
dakaModel = Nohm.register Daka
accountModel = Nohm.register Account
express = require 'express'
app = express()
app.set 'view engine','pug'
STATIC_ROOT = path.join __dirname,'public'
app.use express.static STATIC_ROOT
# enable "req.body",like the old middware - "bodyParser"
app.use express.urlencoded({extended:false})
# session
Session = require 'express-session'
Store = (require 'connect-redis') Session
# authenticate now
redis_auth_pass = require './configs/redis/auth_pass.js'
redis.auth redis_auth_pass,(err,reply)->
if err
console.error 'redis db authenticate failure.'
return process.exit -1
# start add all middle-ware
app.use Session {
cookie:
maxAge: 86400 * 1000 # one day.
httpOnly:true
path:'/' # 似乎太过宽泛,之后有机会会琢磨这个
secret: 'youkNoW.'
store: new Store {client:redis}
resave:false
saveUninitialized:true
}
app.use (req,res,next)->
res.locals.referrer = req.session.referrer
delete req.session.referrer # then,delete() really harmless
next()
app.get '/',(req,res)->
role = req.session?.auth?.role
alias = req.session?.auth?.alias
if role is 'unknown' and alias is 'noname'
[role,alias] = ['visitor','hi']
res.render 'index'
,
title:'welcome-daka'
role:role
alias:alias
app.get '/alpha/:tpl',(req,res)->
tpl = req.params.tpl # client send /alpha?tpl=something
# Notice:all template in views/alpha,use layout via "../layouts"
res.render 'alpha/' + tpl,{'title':'Alpha!'}
app.get '/create-check-words',(req,res)->
# 如果用户选择了填表单方式来打卡。
digits = [48..57] # 0..9
alpha = [97...97+26] # A..Z
chars = digits.concat alpha
.concat digits
.concat alpha
# total 72 chars,so index max is 72-1=71
{round,random} = Math
words = for _ in [1..5] # make length=5 words
index = round random()*71
String.fromCharCode chars[index]
words = words.join ''
# 存储check words到redis数据库,并设置超时条件。
await setAsync 'important',words
await expireAsync 'important',60
res.json words
app.get '/create-qrcode',(req,res)->
# the query string from user-daka js code(img.src=url+'....')
# query string include socketid,timestamp,and alias
text = [req.query.socketid,req.query.timestamp].join('-')
await setAsync 'important',text
await expireAsync 'important',60
# templary solid ,original mode is j602
fulltext = hostname + '/user/daka-response?mode=' + req.query.mode + '&&alias=' + req.query.alias + '&&check=' + text
res.type 'png'
qr_image.image(fulltext).pipe res
# maniuate new func or new mind.
app.get '/user/daka',(req,res)->
if req.session?.auth?.role isnt 'user'
req.session.referrer = '/user/daka'
res.redirect 303,'/user/login'
else
# check which scene the user now in?
user = req.session.auth.alias
# ruler object
today = new Date
today.setHours ruler.am.hours
today.setMinutes ruler.am.minutes
today.setSeconds 0
ids = await dakaModel.find {alias:user,utc_ms:{min:Date.parse today}}
# mode变量值为0提示“入场”待打卡状态,1则为“出场”待打卡状态。
res.render 'user-daka',{mode:ids.length,alias:user,title:'User DaKa Console'}
app.get '/user/login',(req,res)->
res.render 'user-login',{title:'Fill User Login Form'}
app.post '/user/login',(req,res)->
# reference line#163
{itisreferrer,alias,password} = req.body
itisreferrer = itisreferrer or '/user/login-success'
# filter these 2 strings for anti-injecting
isInvalidation = (! filter alias or ! filter password)
if isInvalidation
return res.render 'user-login-failure',{reason: '含有非法字符(只允许ASCII字符和数字)!',title:'User-Login-Failure'}
# auth initialize
initSession req
# first check if exists this alias name?
# mobj is 'match stats object'
mobj = await matchDB accountModel,alias,'user',password
if mobj.match_result
# till here,login data is matches.
updateAuthSession req,'user',alias
res.redirect 303,itisreferrer
else
updateAuthSession req,'unknown','noname'
return res.render 'user-login-failure',{reason: '用户登录失败,原因:帐户不存在/帐户被临时禁用/账户口令不匹配。',title:'User-Login-Failure'}
app.put '/user/logout',(req,res)->
role = req.session?.auth?.role
if role is 'user'
req.session.auth.role = 'unknown'
req.session.auth.alias = 'noname'
res.json {code:0,reason:'',status:'logout success'}
else
res.json {code:-1,reason:'No This Account Or Role Isnt User.',status:'logout failure'}
app.get '/user/login-success',(req,res)->
res.render 'user-login-success',{title:'User Role Validation:successfully'}
# user choiced alternatively way to daka
app.post '/user/daka-response',(req,res)->
check = req.body.check
# get from redis db
words = await getAsync 'important'
session_alias = req.session?.auth?.alias
if words is check
# save this daka-item
try
obj = new Date
desc = obj.toString()
ms = Date.parse obj
ins = await Nohm.factory 'daily'
ins.property
alias: session_alias
utc_ms: ms
whatistime: desc
browser: req.headers["user-agent"]
category:req.body.mode # 'entry' or 'exit' mode
await ins.save()
# notice admin with user's success.
# the .js file include socket,if code=0,socket.emit 'code','0'
return res.render 'user-daka-response-success',{code:'0',title:'login Result',status:'打卡成功',user:session_alias}
catch error
# notice admin with user's failure.
# js file include socket,if code=-1,socket.emit 'code','-1'
# show db errors
console.dir ins.errors
return res.render 'user-daka-response-failure',{title:'daka failure','reason':ins.errors,code:'-1',user:session_alias,status:'数据库错误,打卡失败。'}
else
return res.render 'user-daka-response-failure',{title:'daka failure',status:'打卡失败',code:'-1',reason:'超时或验证无效',user:session_alias}
# user daka via QR code (scan software)
app.get '/user/daka-response',(req,res)->
session_alias = req.session?.auth?.alias
if session_alias is undefined
req.session.referrer = '/user/daka-response'
return res.redirect 303,'/user/login'
if req.query.alias isnt session_alias
return res.json {status:'alias inconsistent',warning:'you should requery daka and visit this page via only one browser',session:session_alias,querystring:req.query.alias}
# user-daka upload 'text' via scan-qrcode-then-goto-url.
text = req.query.check
dbkeep= await getAsync 'important'
if dbkeep isnt '' and text isnt '' and dbkeep is text
# save this daka-item
try
obj = new Date
desc = obj.toString()
ms = Date.parse obj
ins = await Nohm.factory 'daily'
ins.property
# if client has 2 difference browser,one for socketio,and one for qrcode-parser.how the 'alias' value is fit?
alias: req.query.alias # or req.session.auth.alias
utc_ms: ms
whatistime: desc
browser: req.headers["user-agent"]
category:req.query.mode # 'entry' or 'exit' mode
await ins.save()
# notice admin with user's success.
# the .js file include socket,if code=0,socket.emit 'code','0'
return res.render 'user-daka-response-success',{code:'0',title:'login Result',status:'打卡成功',user:req.query.alias}
catch error
console.log 'error',error
# notice admin with user's failure.
# the .js file include socket,if code=-1,socket.emit 'code','-1'
# show db errors
return res.render 'user-daka-response-failure',{title:'daka failure','reason':ins.errors,code:'-1',user:req.query.alias,status:'数据库错误,打卡失败。'}
else
return res.render 'user-daka-response-failure',{title:'daka failure',status:'打卡失败',code:'-1',reason:'超时或身份验证无效',user:req.query.alias}
# start-point-admin
app.get '/admin/daka',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/daka'
res.redirect 303,'/admin/login'
else
res.render 'admin-daka',{title:'Admin Console'}
app.get '/admin/login',(req,res)->
# pagejs= /mine/mine-admin-login.js
res.render 'admin-login',{title:'Fill Authentication Form'}
app.get '/admin/admin-update-password',(req,res)->
res.render 'admin-update-password',{title:'Admin-Update-Password'}
app.put '/admin/logout',(req,res)->
role = req.session?.auth?.role
if role is 'admin'
req.session.auth.role = 'unknown'
req.session.auth.alias = 'noname'
res.json {reason:'',status:'logout success'}
else
# notice that,if client logout failure,not change its role and alias
res.json {reason:'no this account or role isnt admin.',status:'logout failure'}
app.post '/admin/admin-update-password',(req,res)->
{oldpassword,newpassword,alias} = req.body
items = await accountModel.findAndLoad {alias:alias}
if items.length is 0
res.json 'no found!'
else
item = items[0]
dbkeep = item.property 'password'
if dbkeep is hashise oldpassword
# update this item's password part
item.property 'password',hashise newpassword
try
item.save()
catch error
return res.json item.error
return res.json 'Update Password For Admin.'
else #password is mismatches.
return res.json 'Mismatch your oldpassword,check it.'
app.get '/admin/register-user',(req,res)->
if req.session?.auth?.role isnt 'admin'
res.redirect 302,'/admin/login'
else
res.render 'admin-register-user',{title:'Admin-Register-User'}
app.post '/admin/register-user',(req,res)->
{alias,password} = req.body
if ! filter alias or ! filter password
return res.json 'Wrong:User Name(alias) contains invalid character(s).'
ins = await Nohm.factory 'account'
ins.property
alias:alias
role:'user'
initial_timestamp:Date.parse new Date
# always remember:hashise!!
password: PI:PASSWORD:<PASSWORD>END_PI
try
await ins.save()
res.json 'Register User - ' + alias
catch error
res.json ins.errors
# db operator:FIND(superuser,admin are need list all tickets)
# db operator:ADD
app.all '/admin/create-new-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/create-new-ticket'
return res.redirect 303,'/admin/login'
# redis instance already exists - 'redis'
if req.method is 'GET'
res.render 'admin-create-new-ticket',{alias:req.session.auth.alias,title:'Admin-Create-New-Ticket'}
else # POST
# let npm-formidable handles
formid = new formidable.IncomingForm
formid.uploadDir = TICKET_MEDIA_ROOT
formid.keepExtensions = true
formid.maxFileSize = 20 * 1024 * 1024 # update to 200M,for video
_save_one_ticket req,res,formid,redis
app.all '/admin/edit-ticket/:keyname',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/edit-ticket/' + req.params.keyname
return res.redirect 303,'/admin/login'
keyname = req.params.keyname
if req.method is 'GET'
# because it first from a inner-click,so not worry about if key exists.
item = await hgetallAsync keyname
res.render 'admin-edit-ticket-form',{keyname:keyname,title:'admin edit ticket',item:item}
else if req.method is 'POST'
item = await hgetallAsync keyname
options = item # todo.
ticket_id = item.ticket_id
formid = new formidable.IncomingForm
formid.uploadDir = TICKET_MEDIA_ROOT
formid.keepExtensions = true
formid.maxFileSize = 20 * 1024 * 1024 # update maxFileSize to 200M if supports video
formid.parse req,(formid_err,fields,files)->
if formid_err
return res.render 'admin-save-ticket-no-good.pug',{title:'No Save',reason:formid_err.message}
for k,v of fields
if k isnt 'original_uri'
options[k] = v
if files.media.size is 0
bool = fs.existsSync files.media.path
if bool
fs.unlinkSync files.media.path
else
console.log 'files.media.path illegel.'
if files.media.size isnt 0
media_url = files.media.path
realpath = path.join(STATIC_ROOT,'tickets',fields.original_uri.replace(/.*\/(.+)$/,"$1"))
if fields.original_uri
fs.unlinkSync(path.join(STATIC_ROOT,'tickets',fields.original_uri.replace(/.*\/(.+)$/,"$1")))
media_url = '/tickets/' + media_url.replace /.*\/(.+)$/,"$1"
options['media'] = media_url
options['media_type'] = files.media.type
# 检查category是否变了
if not (new RegExp(fields.category)).test keyname
await delAsync keyname
keyname = keyname.replace /hash:(.+)(:.+)$/,'hash:' + fields.category + '$2'
# update this ticket
redis.hmset keyname,options,(err,reply)->
if err
return res.render 'admin-save-ticket-no-good.pug',{title:'No Save',reason:err.message}
else
return res.render 'admin-save-ticket-success.pug',{ticket_id:ticket_id,reply:reply,title:'Updated!'}
else
res.send 'No Clear.'
# in fact,it is 'update-ticket',the query from route /admin/ticket-detail/:id
app.post '/admin/create-new-comment',(req,res)->
{keyname,comment} = req.body
lines = comment.replace(/\r\n/g,'\n').split('\n')
paras = ''
for line in lines
paras += '<p>' + line + '</p>'
comment_str = [
'<blockquote class="blockquote text-center"><p>'
paras
'</p><footer class="blockquote-footer"> <cite>发表于:</cite>'
new Date()
'<button type="button" class="ml-2 btn btn-light" data-toggle="popover" data-placement="bottom" data-content="'
req.header("user-agent")
'" title="browser infomation"> browser Info </button></footer></blockquote>'
].join ''
redis.hget keyname,'reference_comments',(err1,listkey)->
if err1
return res.json {replyText:'no good,reason:' + err1.message}
redis.lpush listkey,comment_str,(err2)->
if err2
return res.json {replyText:'no good,reason:' + err2.message}
else
redis.hincrby keyname,'visits',1,(err3)->
if err3
return res.json {replyText:'no good,reason:' + err3.message}
else
return res.json {replyText:'Good Job'}
# db operator:DELETE
app.delete '/admin/del-one-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/del-one-ticket'
return res.redirect 303,'/admin/login'
else
# check if has 'with-media' flag.
{keyname,with_media} = req.query
if with_media is 'true'
# 'media' is media's path
redis.hget keyname,'media',(err,reply)->
# remember that : media url !== fs path
media = path.join __dirname,'public',reply
# check if media path exists yet.
fs.stat media,(err,stats)->
intReply = await delAsync keyname
if err
# just del item from redis db,file system del failure.
res.send '删除条目' + intReply + '条,media file not clear,because:' + err.message
else
fs.unlink media,(err2)->
if err2 is null
res.send '删除条目' + intReply + '条,media file clear.'
else
res.send '删除条目' + intReply + '条,media file not clear,because:' + err2.message
else
try
# del its referencing comments
referencing_comments = await hgetAsync keyname,'reference_comments'
referenceDeleted = await delAsync referencing_comments
keyDeleted = await delAsync keyname
res.send '删除条目' + keyDeleted + '条,删除评论' + referenceDeleted + '条.'
catch error
res.send error.message
app.get '/admin/del-all-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/del-all-tickets'
return res.redirect 303,'/admin/login'
else
redis.keys TICKET_PREFIX + ':hash:*',(err,list)->
for item in list
await delAsync item
# at last ,report to client.
res.render 'admin-del-all-tickets'
# 投稿
app.post '/admin/contribute',(req,res)->
if req.session?.auth?.role isnt 'admin'
return res.json 'auth error.'
{keyname,to_address,to_port} = req.body
to_port = '80' if to_port is ''
if not keyname or not to_address
return res.json 'invalidate data.'
prefix_url = 'http://' + to_address + ':' + to_port
# retrieve item
request = require 'superagent'
agent = request.agent()
try
o = await hgetallAsync keyname
catch error
return res.json 'DB Operator Error.'
agent.post prefix_url+ '/admin/login'
.type 'form'
.send {'alias':'agent'}
.send {'password':'PI:PASSWORD:<PASSWORD>END_PI'} # solid password for this task.
.end (err,reply)->
if err
return res.json err
# TODO if not match admin:password,err is null,but something is out of your expecting.
if not o.media
agent.post prefix_url + '/admin/create-new-ticket'
.send {
'admin_alias':'agent'
'title':o.title
'ticket':o.ticket
'client_time':o.client_time
'category':o.category
'visits':o.visits
'agent_post_time':(new Date()).toISOString()
}
.end (err,resp)->
if err
return res.json err
res.json resp.status
else # has media attribute
attachment = path.join __dirname,'public',o.media
agent.post prefix_url + '/admin/create-new-ticket'
.field 'alias','agent'
.field 'title',o.title
.field 'ticket',o.ticket
.field 'client_time',o.client_time
.field 'category',o.category
.field 'visits',o.visits
.field 'agent_post_time',(new Date()).toISOString()
.attach 'media',attachment
.end (err,resp)->
if err
return res.json err
res.json resp.status
app.get '/admin/get-ticket-by-id/:id',(req,res)->
ticket_id = req.params.id
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/get-ticket-by-id/' + ticket_id
return res.redirect 303,'/admin/login'
redis.keys TICKET_PREFIX + ':hash:*:' + ticket_id,(err,list)->
if err
res.json {status:'Error Occurs While Retrieving This Id.'}
else
if list.length is 0
res.render 'admin-ticket-no-found.pug',{status:'This Ticket Id No Found'}
else
item = await hgetallAsync list[0]
item.comments = await lrangeAsync item.reference_comments,0,-1
# add for template - 'views/admin-ticket-detail.pug'(20190910 at hanjie he dao)
item.keyname = list[0]
# add 1 to 'visits'
redis.hincrby list[0],'visits',1,(err,num)->
if err is null
res.render 'admin-ticket-detail',{title:'#' + item.ticket_id + ' Detail Page',item:item}
else
res.json 'Error Occurs During DB Manipulating.'
app.post '/admin/ticket-details',(req,res)->
ticket_id = req.body.ticket_id
redis.keys TICKET_PREFIX + ':hash:*:' + ticket_id,(err,list)->
if err
res.json {status:'Error Occurs While Retrieving This Id.'}
else
if list.length is 0
res.render 'admin-ticket-no-found.pug',{status:'This Ticket Id No Found'}
else
# add 1 to 'visits'
redis.hincrby list[0],'visits',1,(err,num)->
if err is null
item = await hgetallAsync list[0]
item.keyname = list[0]
item.comments = await lrangeAsync item.reference_comments,0,-1
#res.render 'admin-newest-ticket.pug',{title:'Detail Page #' + ticket_id,records:[item]}
res.redirect 302,'/admin/get-ticket-by-id/' + ticket_id
else
res.json 'Error Occurs During DB Manipulating.'
app.all '/admin/full-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/full-tickets'
return res.redirect 303,'/admin/login'
if req.method is 'GET'
redis.scan [0,'match','ticket:hash*','count','29'],(err,list)->
items = []
for key in list[1]
item = await hgetallAsync key
items.push item
res.render 'admin-full-tickets.pug',{next:list[0],items:items,title:'Full Indexes'}
else if req.method is 'POST'
redis.scan [req.body.nextCursor,'match','ticket:hash*','count','29'],(err,list)->
if err
res.json 'in case IS POST AND SCAN OCCURS ERROR.'
else
items = []
for key in list[1]
item = await hgetallAsync key
items.push item
res.json {items:items,next:list[0]}
else
res.json 'unknown.'
app.get '/admin/category-of-tickets/:category',(req,res)->
category = req.params.category
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/category-of-tickets/' + category
return res.redirect 303,'/admin/login'
else
keyname = PI:KEY:<KEY>END_PIICKET_PI:KEY:<KEY>END_PI + ':hash:' + category + '*'
records = await _retrieves keyname,(a,b)->b.ticket_id - a.ticket_id
if records.length > 20
records = records[0...20]
res.render 'admin-newest-ticket.pug',{records:records,title:'分类列表:'+category + 'top 20'}
app.get '/admin/visits-base-tickets',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/visits-base-tickets/'
return res.redirect 303,'/admin/login'
else
keyname = PI:KEY:<KEY>END_PIICKET_PREFIX + ':hash:*'
records = await _retrieves keyname,(a,b)->b.visits - a.visits
if records.length > 20
records = records[0...20]
res.render 'admin-newest-ticket.pug',{records:records,title:'top 20 visits tickets'}
app.get '/admin/newest-ticket',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/newest-ticket'
return res.redirect 303,'/admin/login'
else
keypattern = TICKET_PREFIX + ':hash:*'
# at zhongnan hospital,fixed below await-func(inner help function - '_retrieves'
records = await _retrieves(keypattern,((a,b)->b.ticket_id - a.ticket_id))
# retrieve top 20 items.
if records.length > 20
records = records[0...20]
return res.render 'admin-newest-ticket.pug',{'title':'list top 20 items.',records:records}
app.post '/admin/enable-user',(req,res)->
id = req.body.id
try
ins = await Nohm.factory 'account',id
ins.property 'isActive',true
await ins.save()
res.json {code:0,message:'update user,now user in active-status.' }
catch error
reason = {
thrown: error
nohm_said:ins.errors
}
res.json {code:-1,reason:reason}
app.post '/admin/disable-user',(req,res)->
id = req.body.id
try
ins = await Nohm.factory 'account',id
ins.property 'isActive',false
await ins.save()
res.json {code:0,message:'update user,now user in disable-status.' }
catch error
reason = {
thrown: error
nohm_said:ins.errors
}
res.json {code:-1,reason:reason}
app.all '/admin/dynamic-indexes',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/dynamic-indexes'
return res.redirect 303,'/admin/login'
if req.method is 'GET'
range = parseInt req.query.range
if (range isnt 100) and (range isnt 200)
return res.render 'admin-range-list',{error:'Warning:Invalid Query.',title:'Range List'}
redis.keys 'ticket:hash*',(err,list)->
results = []
list = list.sort (a,b)->
aid = parseInt a.split(":")[3]
bid = parseInt b.split(":")[3]
bid - aid
list = list[0..range] # slice
for item in list
o = await hgetallAsync item
results.push o
return res.render 'admin-range-list.pug',{title:'Range List',thelist:results}
else # IN "POST" CASE
start = parseInt req.body.start
end = parseInt req.body.end
if start isnt -(-start) or end isnt -(-end)
return res.render 'admin-range-list',{error:'Warning:Querying Range Exceed.',title:'Range List'}
console.dir {start,end}
current = await getAsync(TICKET_PREFIX + ':counter')
current = parseInt current
results = []
if (start < 0) or (end <= 0) or (end <= start) or (end > current) or ((end-start) > 100)
return res.render 'admin-range-list',{error:'Warning:Querying Range Exceed.',title:'Range List'}
else
redis.keys 'ticket:hash*',(err,list)->
list = list.filter (item)->
num = parseInt item.split(":")[3]
if num > end
return false
else if num < start
return false
true
list = list.sort (a,b)->
aid = parseInt a.split(":")[3]
bid = parseInt b.split(":")[3]
bid - aid
for tid in list
o = await hgetallAsync tid
results.push o
return res.render 'admin-range-list',{thelist:results,title:'Range List'}
app.put '/admin/del-user',(req,res)->
ins = await Nohm.factory 'account'
# req.query.id be transimit from '/admin/list-users' page.
id = req.body.id
ins.id = id
try
await ins.remove()
catch error
return res.json {code:-1,'reason':JSON.stringify(ins.errors)}
return res.json {code:0,'gala':'remove #' + id + ' success.'}
app.post '/admin/login',(req,res)->
{itisreferrer,alias,password} = req.body
itisreferrer = itisreferrer or '/admin/login-success'
# filter alias,and password
isInvalid = ( !(filter alias) or !(filter password) )
if isInvalid
return res.render 'admin-login-failure',{title:'Login-Failure',reason:'表单中含有非法字符.'}
# initial session.auth
initSession req
# first check if exists this alias name?
# mobj is 'match stats object'
mobj = await matchDB accountModel,alias,'admin',password
if mobj.match_result
# till here,login data is matches.
updateAuthSession req,'admin',alias
res.redirect 303,itisreferrer
else
updateAuthSession req,'unknown','noname'
res.render 'admin-login-failure' ,{title:'Login-Failure',reason:'管理员登录失败,原因:帐户不存在或者帐户被临时禁用或者帐户名与口令不匹配。'}
app.get '/admin/login-success',(req,res)->
res.render 'admin-login-success.pug',{title:'Administrator Role Entablished'}
app.get '/admin/checkout-daka',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/checkout-daka'
return res.redirect 303,'/admin/login'
# query all user's name
inss = await accountModel.findAndLoad {role:'user'}
aliases = ( ins.property('alias') for ins in inss )
res.render 'admin-checkout-daka',{aliases:aliases,title:'Checkout-One-User-DaKa'}
# route /daka database interaction
app.get '/daka/one',(req,res)->
{user,range} = req.query
ids = await dakaModel.find {alias:user,utc_ms:{min:0}}
sorted = await dakaModel.sort {'field':'utc_ms'},ids
hashes = []
for id in sorted
ins = await dakaModel.load id
hashes.push ins.allProperties()
res.json hashes
app.get '/admin/list-user-daka',(req,res)->
alias = req.query.alias
if ! alias
return res.json 'no special user,check and redo.'
if not filter alias
return res.json 'has invalid char(s).'
# first,check role if is admin
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/list-user-daka?alias=' + alias
return res.redirect 303,'/admin/login'
inss = await dakaModel.findAndLoad alias:alias
result = []
for ins in inss
obj = ins.allProperties()
result.push obj
res.render 'admin-list-user-daka',{alias:alias,title:'List User DaKa Items',data:result}
app.get '/admin/list-users',(req,res)->
if req.session?.auth?.role isnt 'admin'
req.session.referrer = '/admin/list-users'
return res.redirect 303,'/admin/login'
inss = await accountModel.findAndLoad({'role':'user'})
results = []
inss.forEach (one)->
obj = {}
obj.alias = one.property 'alias'
obj.role = one.property 'role'
obj.initial_timestamp = one.property 'initial_timestamp'
obj.password = one.property 'password'
obj.isActive = one.property 'isActive'
obj.id = one.id
results.push obj
res.render 'admin-list-users',{title:'Admin:List-Users',accounts:results}
app.get '/superuser/list-admins',(req,res)->
if req.session?.auth?.role isnt 'superuser'
req.session.referrer = '/superuser/list-admins'
return res.redirect 303,'/superuser/login'
inss = await accountModel.findAndLoad {'role':'admin'}
results = []
inss.forEach (one)->
obj = {}
obj.alias = one.property 'alias'
obj.role = one.property 'role'
obj.initial_timestamp = one.property 'initial_timestamp'
obj.password = PI:PASSWORD:<PASSWORD>END_PI 'PI:PASSWORD:<PASSWORD>END_PI'
obj.id = one.id
results.push obj
res.render 'superuser-list-admins',{title:'List-Administrators',accounts:results}
app.get '/superuser/list-tickets/:category',(req,res)->
pattern = [TICKET_PREFIX,'hash',req.params.category,'*'].join ':'
redis.keys pattern,(err,keys)->
# this is a good sample about redis-multi way.maybe multi is perfom better than hgetallAsync.
list = redis.multi()
for key in keys
list.hgetall key
list.exec (err,replies)->
if err
return res.json err
else
return res.render 'superuser-list-tickets',{title:'list tickets',tickets:replies}
app.put '/superuser/del-admin',(req,res)->
ins = await Nohm.factory 'account'
# req.query.id be transimit from '/superuser/list-admins' page.
id = req.query.id
ins.id = id
try
await ins.remove()
catch error
return res.json {code:-1,'reason':JSON.stringify(ins.errors)}
return res.json {code:0,'gala':'remove #' + id + ' success.'}
app.all '/superuser/daka-complement',(req,res)->
if req.session?.auth?.role isnt 'superuser'
req.session.referrer = '/superuser/daka-complement'
return res.redirect 303,'/superuser/login'
if req.method is 'POST'
# client post via xhr,so server side use 'formidable' module
formid = new formidable.IncomingForm
formid.parse req,(err,fields,files)->
if err
res.json {code:-1}
else
# store
objs = convert fields
responses = []
for obj in objs #objs is an array,elements be made by one object
response = await complement_save obj['combo'],obj
responses.push response
# responses example:[{},[{},{}],{}...]
res.json responses
else
res.render 'superuser-daka-complement',{title:'Super User Daka-Complement'}
app.get '/superuser/login',(req,res)->
# referrer will received from middle ware
res.render 'superuser-login.pug',{title:'Are You A Super?'}
app.get '/superuser/login-success',(req,res)->
res.render 'superuser-login-success.pug',{title:'Super User Login!'}
app.post '/superuser/login',(req,res)->
# initial sesson.auth
initSession req
{password,itisreferrer} = req.body
hash = sha256 password
if hash is superpass
updateAuthSession req,'superuser','superuser'
if itisreferrer
res.redirect 303,itisreferrer
else
res.redirect 301,'/superuser/login-success'
else
updateAuthSession req,'unknown','noname'
res.json {staus:'super user login failurre.'}
app.get '/superuser/register-admin',(req,res)->
if req.session?.auth?.role isnt 'superuser'
res.redirect 302,'/superuser/login'
else
res.render 'superuser-register-admin',{defaultValue:'1234567',title:'Superuser-register-admin'}
app.get '/superuser/delete-all-daka-items',(req,res)->
if req.session?.auth?.role isnt 'superuser'
return res.json 'wrong:must role is superuser.'
# delete all daka items,be cafeful.
multi = redis.multi()
redis.keys DAKA_WILDCARD,(err,keys)->
for key in keys
multi.del key
multi.exec (err,replies)->
res.json replies
app.post '/superuser/register-admin',(req,res)->
{adminname} = req.body
if ! filter adminname
return res.json 'Wrong:Admin Name(alias) contains invalid character(s).'
ins = await Nohm.factory 'account'
ins.property
alias:adminname
role:'admin'
initial_timestamp:Date.parse new Date
password: PI:PASSWORD:<PASSWORD>END_PI 'PI:PASSWORD:<PASSWORD>END_PI' # default password.
try
await ins.save()
res.json 'Saved.'
catch error
res.json ins.errors
app.get '/no-staticify',(req,res)->
# listen radio(voa&rfa mandarin)
fs.readdir path.join(STATIC_ROOT,'audioes'),(err,list)->
if err is null
audio_list = []
for item in list
realpath = path.join STATIC_ROOT,'audioes',item
if (fs.statSync realpath).isFile()
audio_list.push path.join '/audioes',item
res.render 'no-staticify',{title:'list audioes',list:audio_list}
else
res.render 'no-staticify-failure',{title:'you-see-failure',error_reason:err.message}
app.delete '/remove-readed-audio',(req,res)->
if req.body.data
uri = path.join 'public',req.body.data
bool = fs.existsSync uri
if bool
fs.unlinkSync uri
res.json {status:'has deleted.'}
else
res.json {status:'no found'}
else
res.json {status:'not good'}
# during learn css3,svg..,use this route for convient.
app.use '/staticify/:viewname',(req,res)->
res.render 'staticify/' + req.params.viewname,{title:'it is staticify page'}
app.use (req,res)->
res.status 404
res.render '404'
app.use (err,req,res,next)->
console.error 'occurs 500 error. [[ ' + err.stack + ' ]]'
res.type 'text/plain'
res.status 500
res.send '500 - Server Error!'
if require.main is module
server = http.Server app
server.listen 3003,->
console.log 'server running at port 3003;press Ctrl-C to terminate.'
else
module.exports = app
# initSession is a help function
initSession = (req)->
if not req.session?.auth
req.session.auth =
alias:'noname'
counter:0
tries:[]
matches:[]
role:'unknown'
null
# updateAuthSession is a help function
# this method be invoked by {user|admin|superuser}/login (post request)
updateAuthSession = (req,role,alias)->
timestamp = new Date
counter = req.session.auth.counter++
req.session.auth.tries.push 'counter#' + counter + ':user try to login at ' + timestamp
req.session.auth.role = role
req.session.auth.alias = alias
if role is 'unknown'
req.session.auth.matches.push '*Not* Matches counter#' + counter + ' .'
else
req.session.auth.matches.push 'Matches counter#' + counter + ' .'
# hashise is a help function.
hashise = (plain)->
hash = crypto.createHash 'sha256'
hash.update plain
hash.digest 'hex'
# filter is a help function
filter = (be_dealt_with)->
# return true is safe,return false means injectable.
if not be_dealt_with
return false
return not /\W/.test be_dealt_with
# matchDB is a help function
# *Notice that* invoke this method via "await <this>"
matchDB = (db,alias,role,password)->
# db example 'accountModel'
items = await db.findAndLoad {'alias':alias}
if items.length is 0 # means no found.
return false
else
item = items[0]
dbpassword = item.property 'password'
dbrole = item.property 'role'
isActive = item.property 'isActive'
warning = ''
if dbpassword is 'PI:PASSWORD:<PASSWORD>END_PI'
warning = 'should change this simple/initial/templory password immediately.'
match_result = (isActive) and ((hashise password) is dbpassword) and (dbrole is role)
return {match_result:match_result,warning:warning}
# for authenticate super user password.
sha256 = (plain)->
crypto.createHash 'sha256'
.update plain
.digest 'hex'
# help func convert,can convert formidable's fields object to an object arrary(for iterator store in redis).
convert = (fields)->
results = []
for i,v of fields
matched = i.match /(\D*)(\d*)$/
pre = matched[1]
post = matched[2]
if (post in Object.keys(results)) is false
results[post] = {}
results[post][pre] = v
results
# help function - complement_save()
# complement_save handle single object(one form in client side).
complement_save = (option,fieldobj)->
# option always is uploaded object's field - option
response = undefined
# inner help function - single_save()
single_save = (standard)->
ins = await Nohm.factory 'daily'
ins.property standard
try
await ins.save()
catch error
console.dir error
return {'item-id':ins.id,'saved':false,reason:ins.errors}
return {'item-id':ins.id,'saved':true}
switch option
when 'option1'
standard =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['first-half-']
whatistime:fieldobj['first-half-']
dakaer:'superuser'
category:'entry'
browser:req.headers['user-agent']
response = await single_save standard
when 'option2'
standard =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['second-half-']
whatistime:fieldobj['second-half-']
dakaer:'superuser'
category:'exit'
browser:req.headers['user-agent']
response = await single_save standard
when 'option3'
standard1 =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['first-half-']
whatistime:fieldobj['first-half-']
dakaer:'superuser'
browser:req.headers['user-agent']
category:'entry'
standard2 =
alias:fieldobj.alias
utc_ms:Date.parse fieldobj['second-half-']
whatistime:fieldobj['second-half-']
dakaer:'superuser'
browser:req.headers['user-agent']
category:'exit'
# save 2 instances.
response1 = await single_save standard1
response2 = await single_save standard2
response = [response1,response2]
else
response = {code:-1,reason:'unknow status.'}
response
# help function - '_save_one_ticket'
_save_one_ticket = (req,res,form,redis)->
form.parse req,(err,fields,files)->
if err
return res.render 'admin-save-ticket-no-good.pug',{title :'No Save',reason:err.message}
options = ['visits','0','urge','0','resolved','false']
for k,v of fields
options = options.concat [k,v]
if files.media and files.media.size is 0
fs.unlinkSync files.media.path
if files.media and files.media.size isnt 0
media_url = files.media.path
# for img or other media "src" attribute,the path is relative STATIC-ROOT.
media_url = '/tickets/' + media_url.replace /.*\/(.+)$/,"$1"
options = options.concat ['media',media_url,'media_type',files.media.type]
# store this ticket
redis.incr (TICKET_PREFIX + ':counter'),(err,number)->
if err isnt null # occurs error.
return res.json 'Occurs Error While DB Operation.' + err.message
keyname = [TICKET_PREFIX,'hash',fields.category,number].join ':'
options = options.concat ['ticket_id',number,'reference_comments','comments-for-' + number]
redis.hmset keyname,options,(err,reply)->
if err
return res.json 'Occurs Error During Creating,Reason:' + err.message
else
# successfully
return res.render 'admin-save-ticket-success.pug',{ticket_id:number,reply:reply,title:'Stored Success'}
# help function 'retrieves',for retrieves ticket by its first argument.
_retrieves = (keyname,sortby)->
promise = new Promise (resolve,reject)->
redis.keys keyname,(err,list)->
records = []
for item in list
record = await hgetallAsync item
bool = await existsAsync record.reference_comments
if bool
comments = await lrangeAsync record.reference_comments,0,-1
# give new attribute 'comments'
record.comments = comments
else
record.comments = []
# keyname 将用于$.ajax {url:'/admin/del-one-ticket?keyname=' + keyname....
record.keyname = item
records.push record
#sorting before output to client.
records.sort sortby
resolve records
return promise
|
[
{
"context": " return specHelper\n random: (num) ->\n char = \"AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa\"\n string = \"\"\n for i in [0..num]\n rand",
"end": 1575,
"score": 0.9980047345161438,
"start": 1513,
"tag": "KEY",
"value": "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa"
}
] | v1/test/utils/specHelper.coffee | lizechoo/Bromeliad-Database | 0 | request = require 'request'
BASE_URL = 'http://localhost:8888/v1/api/'
token = null
specHelper = null
class SpecHelper
constructor: ->
@request = params: {}
route: (route) ->
parts = route.split("/")
@request.params.route = parts[0]
@request.params.action = parts[1]
return this
send: (send) ->
@request.send = send
return this
method: (method) ->
@request.method = method
return this
expect: (expect) ->
@request.expect = expect
return this
params: (params) ->
for param, value of params
@request.params[param] = value
return this
auth: (auth) ->
@request.auth = auth
return this
end: (callback) ->
options =
method: @request.method
uri: BASE_URL
headers: {}
options.qs = @request.params if @request.params
options.headers['Authorization'] = "bearer " + @request.auth if @request.auth
options.headers["Content-Type"] = "application/json"
options.body = JSON.stringify(@request.send) if @request.send
request options, (error, response, body) =>
if (response.statusCode != @request.expect)
console.log body
throw new Error("Response code expected: #{@request.expect}, actual: #{response.statusCode}")
try
parsed = JSON.parse body
catch e
console.error (body)
callback error, parsed
module.exports =
api: (route) ->
specHelper = new SpecHelper()
specHelper.route(route)
return specHelper
random: (num) ->
char = "AzByC0xDwEv9FuGt8HsIrJ7qKpLo6MnNmO5lPkQj4RiShT3gUfVe2WdXcY1bZa"
string = ""
for i in [0..num]
rand = Math.floor(Math.random() * char.length)
string += char[rand]
return string
| 8315 | request = require 'request'
BASE_URL = 'http://localhost:8888/v1/api/'
token = null
specHelper = null
class SpecHelper
constructor: ->
@request = params: {}
route: (route) ->
parts = route.split("/")
@request.params.route = parts[0]
@request.params.action = parts[1]
return this
send: (send) ->
@request.send = send
return this
method: (method) ->
@request.method = method
return this
expect: (expect) ->
@request.expect = expect
return this
params: (params) ->
for param, value of params
@request.params[param] = value
return this
auth: (auth) ->
@request.auth = auth
return this
end: (callback) ->
options =
method: @request.method
uri: BASE_URL
headers: {}
options.qs = @request.params if @request.params
options.headers['Authorization'] = "bearer " + @request.auth if @request.auth
options.headers["Content-Type"] = "application/json"
options.body = JSON.stringify(@request.send) if @request.send
request options, (error, response, body) =>
if (response.statusCode != @request.expect)
console.log body
throw new Error("Response code expected: #{@request.expect}, actual: #{response.statusCode}")
try
parsed = JSON.parse body
catch e
console.error (body)
callback error, parsed
module.exports =
api: (route) ->
specHelper = new SpecHelper()
specHelper.route(route)
return specHelper
random: (num) ->
char = "<KEY>"
string = ""
for i in [0..num]
rand = Math.floor(Math.random() * char.length)
string += char[rand]
return string
| true | request = require 'request'
BASE_URL = 'http://localhost:8888/v1/api/'
token = null
specHelper = null
class SpecHelper
constructor: ->
@request = params: {}
route: (route) ->
parts = route.split("/")
@request.params.route = parts[0]
@request.params.action = parts[1]
return this
send: (send) ->
@request.send = send
return this
method: (method) ->
@request.method = method
return this
expect: (expect) ->
@request.expect = expect
return this
params: (params) ->
for param, value of params
@request.params[param] = value
return this
auth: (auth) ->
@request.auth = auth
return this
end: (callback) ->
options =
method: @request.method
uri: BASE_URL
headers: {}
options.qs = @request.params if @request.params
options.headers['Authorization'] = "bearer " + @request.auth if @request.auth
options.headers["Content-Type"] = "application/json"
options.body = JSON.stringify(@request.send) if @request.send
request options, (error, response, body) =>
if (response.statusCode != @request.expect)
console.log body
throw new Error("Response code expected: #{@request.expect}, actual: #{response.statusCode}")
try
parsed = JSON.parse body
catch e
console.error (body)
callback error, parsed
module.exports =
api: (route) ->
specHelper = new SpecHelper()
specHelper.route(route)
return specHelper
random: (num) ->
char = "PI:KEY:<KEY>END_PI"
string = ""
for i in [0..num]
rand = Math.floor(Math.random() * char.length)
string += char[rand]
return string
|
[
{
"context": ">\n @resource.orders().findBy(token: 'abc123')\n .then window.onSuccess\n ",
"end": 7963,
"score": 0.8118163347244263,
"start": 7957,
"tag": "KEY",
"value": "abc123"
},
{
"context": ".requests.mostRecent())).toContain('filter[token]=abc123', 'limit=1')\n\n it 'gets a resource of th",
"end": 8454,
"score": 0.8279797434806824,
"start": 8448,
"tag": "KEY",
"value": "abc123"
},
{
"context": " @resource = MyLibrary.HasManyClass.build(token: 'abc123')\n\n @target = MyLibrary.Order.build()\n",
"end": 13129,
"score": 0.993005096912384,
"start": 13123,
"tag": "KEY",
"value": "abc123"
},
{
"context": " expect(@target.hasManyClassToken).toEqual('abc123')\n\n describe 'when target is polymorphic',",
"end": 13343,
"score": 0.8445244431495667,
"start": 13337,
"tag": "KEY",
"value": "abc123"
}
] | spec/associations/has_many.coffee | daniffig/active-resource.js | 95 | describe 'ActiveResource', ->
beforeEach ->
moxios.install(MyLibrary.interface.axios)
window.onSuccess = jasmine.createSpy('onSuccess')
window.onFailure = jasmine.createSpy('onFailure')
window.onCompletion = jasmine.createSpy('onCompletion')
afterEach ->
moxios.uninstall()
describe '::Associations', ->
describe '::HasManyAssociation', ->
describe 'reading', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns a CollectionProxy', ->
@promise.then =>
expect(@resource.orders().klass()).toBe(ActiveResource::Associations::CollectionProxy)
describe '#all(cached: true)', ->
it 'returns a collection', ->
@promise.then =>
expect(@resource.orders().all(cached: true).klass()).toBe(ActiveResource::Collection)
it 'returns resources already loaded', ->
@promise.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(2)
describe 'loading', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'uses relationship data URL', ->
relationshipLinks = {
self: 'https://example.com/api/v1/products/1/relationships/orders/',
related: 'https://example.com/api/v1/products/1/orders/'
}
@promise2.then =>
expect(@resource.orders().links()).toEqual(relationshipLinks)
describe '#loadTarget()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.association('orders').loadTarget()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@target.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@target.first().klass()).toBe(MyLibrary.Order)
it 'caches the result on the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(@target.size())
describe '#all()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().all()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@result.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@result.first().klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#load()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().where(some: 'value').load()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@result.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@result.first().klass()).toBe(MyLibrary.Order)
it 'does assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).not.toEqual(0)
it 'queries the first relationship resource with filters', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[some]=value')
describe '#first()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().first()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first resource of the relationship data URL', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('limit=1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#last()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().last()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first resource of the relationship data URL', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('limit=1&offset=-1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#find()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().find(1)
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries a specific member of the relationship data URL', ->
memberLink = 'https://example.com/api/v1/products/1/orders/1'
@promise4.then =>
expect(moxios.requests.mostRecent().url).toContain(memberLink)
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#findBy()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().findBy(token: 'abc123')
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first relationship resource with filters', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[token]=abc123', 'limit=1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe 'when using a Relation extension method', ->
it 'extends the association relation', ->
@promise2.then =>
expect(@resource.orders().where().klass()).toBe(ActiveResource::Associations::CollectionProxy)
it 'adds query params to the relationship URL query', ->
@promise3 = @promise2.then =>
@resource.orders().where(price: 5).all()
@resource
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[price]=5')
describe '#select()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().select('price','verificationCode').all()
@resource
it 'uses the correct model name for shallow fields', ->
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('fields[orders]=price,verification_code')
describe '#includes()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().includes('orderItems').all()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.includes)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'associates included resources', ->
@promise4.then =>
expect(@result.first().orderItems().all(cached: true).size()).toEqual(1)
expect(@result.last().orderItems().all(cached: true).size()).toEqual(1)
describe 'reloading', ->
describe 'when nested associations were included', ->
beforeEach ->
MyLibrary.Product.includes(orders: 'comments').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it "adds the nested associations to queryParams['include']", ->
@promise3 = @promise2.then =>
@resource.orders().reload()
@resource
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('include=comments')
describe 'assigning when owner is unpersisted', ->
beforeEach ->
@resource = MyLibrary.Product.build(id: 2)
@target = [MyLibrary.Order.build(id: 1), MyLibrary.Order.build(id: 2)]
@resource.orders().assign(@target)
it 'replaces the target with the resource(s)', ->
_.each @target, (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
it 'replaces the inverse target(s) of the resource(s)', ->
_.each @target, (t) =>
expect(t.product()).toBe(@resource)
it 'replaces the resources(s) foreign key(s)', ->
_.each @target, (t) =>
expect(t.productId).toEqual(@resource.id)
describe 'when assigning wrong type', ->
it 'throws an error', ->
expect(=> @resource.orders().assign(MyLibrary.OrderItem.build())).toThrow()
describe 'when foreignKey defined', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'orders', foreignKey: 'hasManyClassToken'
@resource = MyLibrary.HasManyClass.build(id: 2)
@target = MyLibrary.Order.build()
@resource.orders().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyClassToken).toEqual(2)
describe 'when primaryKey defined', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'orders', primaryKey: 'token', foreignKey: 'hasManyClassToken'
@resource = MyLibrary.HasManyClass.build(token: 'abc123')
@target = MyLibrary.Order.build()
@resource.orders().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyClassToken).toEqual('abc123')
describe 'when target is polymorphic', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'belongsToPolymorphics', as: 'hasManyAlias'
class MyLibrary.BelongsToPolymorphic extends MyLibrary.Base
this.className = 'BelongsToPolymorphic'
this.queryName = 'belongs_to_polymorphics'
@belongsTo 'hasManyAlias', polymorphic: true
@resource = MyLibrary.HasManyClass.build(id: 1)
@target = MyLibrary.BelongsToPolymorphic.build()
@resource.belongsToPolymorphics().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyAliasId).toEqual(1)
it 'assigns the inverse\'s foreign type', ->
expect(@target.hasManyAliasType).toEqual('HasManyClass')
# TODO: Make `foreignType` option work with specs
describe 'assigning when owner is persisted', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'in general', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise4 = @promise3.then =>
@resource.orders().assign(@target)
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'persists the update to the relationship URL', ->
relationshipLink = 'https://example.com/api/v1/products/1/relationships/orders/'
@promise4.then =>
expect(moxios.requests.mostRecent().url).toEqual(relationshipLink)
it 'makes a PATCH request', ->
@promise4.then =>
expect(moxios.requests.mostRecent().method).toEqual('patch')
describe 'when assigning collection of resources', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise4 = @promise3.then =>
@resource.orders().assign(@target)
@resource
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{
type: 'orders',
id: '1'
},
{
type: 'orders',
id: '2'
}
]
})
@promise4.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when update succeeds', ->
beforeEach ->
@promise5 = @promise4.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'replaces the target with the resource(s)', ->
@promise5.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
it 'replaces the inverse target(s) of the resource(s)', ->
@promise5.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'replaces the resources(s) foreign key(s)', ->
@promise5.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
describe 'when update fails', ->
beforeEach ->
@promise5 = @promise4.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not replace the target with the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(t)
it 'does not replace the inverse target(s) of the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(t.product()).not.toBe(@resource)
it 'does not replace the foreign key(s) of the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(t.productId).not.toEqual(@resource.id)
describe 'when assigning empty collection', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().assign([])
@resource
it 'sends an empty document', ->
resourceDocument = JSON.stringify({
data: []
})
@promise3.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when update succeeds', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'replaces the target with an empty collection', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe 'when assigning with save: false', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@priorRequestsCount = moxios.requests.count()
@output = @resource.orders().assign(@target.toCollection(), false)
it 'does not make a request', ->
@promise3.then =>
expect(moxios.requests.count()).toEqual(@priorRequestsCount)
it 'does return assigned resources', ->
@promise3.then =>
expect(@output.klass()).toBe(ActiveResource::Collection)
it 'replaces the target', ->
@promise3.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(@target.size())
describe 'building', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@target = @resource.orders().build([{ price: 1 }, { price: 2 }])
it 'builds resource(s) of reflection klass type', ->
@promise.then =>
@target.each (t) =>
expect(t.klass()).toBe(MyLibrary.Order)
it 'assigns attributes to the resource(s)', ->
@promise.then =>
@target.each (t) =>
expect([1, 2]).toContain(t.price)
it 'assigns the inverse target(s)', ->
@promise.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'assigns the target(s) foreign key(s)', ->
@promise.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
it 'adds the resource to the target', ->
@promise.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
describe 'creating', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'in general', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3, verificationCode: 'abc123' }, window.onCompletion)
@resource
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
.then =>
@target = window.onCompletion.calls.mostRecent().args[0]
it 'makes a request to the target\'s root URL', ->
targetURL = 'https://example.com/api/v1/orders/'
@promise3.then =>
expect(moxios.requests.mostRecent().url).toEqual(targetURL)
it 'makes a POST request', ->
@promise3.then =>
expect(moxios.requests.mostRecent().method).toEqual('post')
it 'sends a resource document', ->
resourceDocument = JSON.stringify({
data: {
type: 'orders',
attributes: {
price: 3,
verification_code: 'abc123',
product_id: '1'
},
relationships: {
product: {
data: { type: 'products', id: '1' }
}
}
}
})
@promise3.then =>
expect(extractData(moxios.requests.mostRecent().data)).toEqual(resourceDocument)
it 'builds resource(s) of reflection klass type', ->
@promise3.then =>
expect(@target.klass()).toBe(MyLibrary.Order)
it 'assigns attributes to the resource(s)', ->
@promise3.then =>
expect(@target.price).toEqual(3)
it 'assigns the inverse target(s)', ->
@promise3.then =>
expect(@target.product()).toBe(@resource)
it 'assigns the resource(s) foreign key(s)', ->
@promise3.then =>
expect(@target.productId).toEqual(@resource.id)
it 'adds the resource(s) to the target', ->
@promise3.then =>
expect(@resource.orders().all(cached: true).toArray()).toContain(@target)
describe 'when creation succeeds', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3, verificationCode: 'abc123' }, window.onCompletion)
@resource
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
.then =>
@target = window.onCompletion.calls.mostRecent().args[0]
it 'persists the resource', ->
@promise3.then =>
expect(@target.persisted?()).toBeTruthy()
describe 'when creation fails', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3 }, window.onCompletion)
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
.catch =>
Promise.reject(@target = window.onCompletion.calls.mostRecent().args[0])
it 'does not persist the resource', ->
@promise2.catch =>
expect(@target.persisted?()).toBeFalsy()
it 'adds errors to the resource', ->
@promise2.catch =>
expect(@target.errors().empty?()).toBeFalsy()
describe 'when autosave association is present', ->
beforeEach ->
@promise2 = @promise.then =>
MyLibrary.Order.hasMany 'orderItems', autosave: true
orderItems = [
MyLibrary.OrderItem.build(amount: 1.0),
MyLibrary.OrderItem.build(amount: 2.0)
]
@resource.orders().create({ price: 3, orderItems: orderItems }, window.onCompletion)
@resource
afterEach ->
MyLibrary.Order.hasMany 'orderItems'
MyLibrary.Order.resetQueryParams()
it 'adds the association attributes to the resource document', ->
resourceDocument = {
type: 'orders',
attributes: {
price: 3,
product_id: '1'
},
relationships: {
product: {
data: { type: 'products', id: '1' }
},
order_items: {
data: [
{
type: 'order_items',
attributes: {
amount: 1.0
}
},
{
type: 'order_items',
attributes: {
amount: 2.0
}
}
]
}
}
}
@promise2.then =>
expect(JSON.parse(moxios.requests.mostRecent().data)['data']).toEqual(resourceDocument)
it "adds the autosave association to queryOptions['include']", ->
@promise2.then =>
expect(JSON.parse(moxios.requests.mostRecent().data)['include']).toContain('order_items')
describe 'when creation succeeds', ->
beforeEach ->
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@order = window.onCompletion.calls.mostRecent().args[0]
it 'persists the autosave association', ->
@promise3.then =>
@order.orderItems().all(cached: true).each (o) ->
expect(o.persisted()).toBeTruthy()
describe 'when owner is not persisted', ->
it 'throws exception', ->
resource = MyLibrary.Product.build()
expect(-> resource.orders().create({ price: 5 })).toThrow()
describe 'pushing', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@promise2 = @promise.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise3 = @promise2.then =>
@resource.orders().push(@target)
@resource
describe 'in general', ->
it 'makes a request to the target\'s relationship URL', ->
@promise3.then =>
expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products/1/relationships/orders/')
it 'makes a POST request', ->
@promise3.then =>
expect(moxios.requests.mostRecent().method).toEqual('post')
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' },
{ type: 'orders', id: '2' }
]
})
@promise3.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when pushing succeeds', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'assigns the inverse target(s) of the resource(s)', ->
@promise4.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'assigns the resource(s) foreign key(s)', ->
@promise4.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
it 'adds the resource(s) to the target', ->
@promise4.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
describe 'when pushing fails', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not assign the inverse target(s) of the resource(s)', ->
@promise4.catch =>
@target.each (t) =>
expect(t.product()).not.toBe(@resource)
it 'does not assign the resource(s) foreign key(s)', ->
@promise4.catch =>
@target.each (t) =>
expect(t.productId).not.toEqual(@resource.id)
it 'does not add the resource(s) to the target', ->
@promise4.catch =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(t)
describe 'deleting', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@target = @resource.orders().all(cached: true)
describe 'in general', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
@resource
it 'makes a request to the target\'s relationship URL', ->
@promise2.then =>
expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products/1/relationships/orders/')
it 'makes a DELETE request', ->
@promise2.then =>
expect(moxios.requests.mostRecent().method).toEqual('delete')
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' }
]
})
@promise2.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when deleting succeeds', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'removes the inverse target(s) of the resource(s)', ->
@promise2.then =>
expect(@target.first().product()).toBeNull()
it 'removes the resource(s) foreign key(s)', ->
@promise2.then =>
expect(@target.first().productId).toBeNull()
it 'removes the resource(s) from the target', ->
@promise2.then =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(@target.first())
describe 'when deleting fails', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not remove the inverse target(s) of the resource(s)', ->
@promise2.catch =>
expect(@target.first().product()).toBe(@resource)
it 'does not remove the resource(s) foreign key(s)', ->
@promise2.catch =>
expect(@target.first().productId).toEqual(@resource.id)
it 'does not remove the resource(s) from the target', ->
@promise2.catch =>
expect(@resource.orders().all(cached: true).toArray()).toContain(@target.first())
describe '#deleteAll()', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().deleteAll()
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'sends a resource identifier document with all resources', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' },
{ type: 'orders', id: '2' }
]
})
@promise2.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
it 'deletes all resources from the target', ->
@promise2.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#empty()', ->
describe 'when target is empty', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns true', ->
@promise.then =>
expect(@resource.orders().empty()).toBeTruthy()
describe 'when target is not empty', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns false', ->
@promise.then =>
expect(@resource.orders().empty()).toBeFalsy()
| 121143 | describe 'ActiveResource', ->
beforeEach ->
moxios.install(MyLibrary.interface.axios)
window.onSuccess = jasmine.createSpy('onSuccess')
window.onFailure = jasmine.createSpy('onFailure')
window.onCompletion = jasmine.createSpy('onCompletion')
afterEach ->
moxios.uninstall()
describe '::Associations', ->
describe '::HasManyAssociation', ->
describe 'reading', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns a CollectionProxy', ->
@promise.then =>
expect(@resource.orders().klass()).toBe(ActiveResource::Associations::CollectionProxy)
describe '#all(cached: true)', ->
it 'returns a collection', ->
@promise.then =>
expect(@resource.orders().all(cached: true).klass()).toBe(ActiveResource::Collection)
it 'returns resources already loaded', ->
@promise.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(2)
describe 'loading', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'uses relationship data URL', ->
relationshipLinks = {
self: 'https://example.com/api/v1/products/1/relationships/orders/',
related: 'https://example.com/api/v1/products/1/orders/'
}
@promise2.then =>
expect(@resource.orders().links()).toEqual(relationshipLinks)
describe '#loadTarget()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.association('orders').loadTarget()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@target.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@target.first().klass()).toBe(MyLibrary.Order)
it 'caches the result on the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(@target.size())
describe '#all()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().all()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@result.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@result.first().klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#load()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().where(some: 'value').load()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@result.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@result.first().klass()).toBe(MyLibrary.Order)
it 'does assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).not.toEqual(0)
it 'queries the first relationship resource with filters', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[some]=value')
describe '#first()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().first()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first resource of the relationship data URL', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('limit=1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#last()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().last()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first resource of the relationship data URL', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('limit=1&offset=-1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#find()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().find(1)
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries a specific member of the relationship data URL', ->
memberLink = 'https://example.com/api/v1/products/1/orders/1'
@promise4.then =>
expect(moxios.requests.mostRecent().url).toContain(memberLink)
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#findBy()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().findBy(token: '<KEY>')
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first relationship resource with filters', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[token]=<KEY>', 'limit=1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe 'when using a Relation extension method', ->
it 'extends the association relation', ->
@promise2.then =>
expect(@resource.orders().where().klass()).toBe(ActiveResource::Associations::CollectionProxy)
it 'adds query params to the relationship URL query', ->
@promise3 = @promise2.then =>
@resource.orders().where(price: 5).all()
@resource
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[price]=5')
describe '#select()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().select('price','verificationCode').all()
@resource
it 'uses the correct model name for shallow fields', ->
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('fields[orders]=price,verification_code')
describe '#includes()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().includes('orderItems').all()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.includes)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'associates included resources', ->
@promise4.then =>
expect(@result.first().orderItems().all(cached: true).size()).toEqual(1)
expect(@result.last().orderItems().all(cached: true).size()).toEqual(1)
describe 'reloading', ->
describe 'when nested associations were included', ->
beforeEach ->
MyLibrary.Product.includes(orders: 'comments').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it "adds the nested associations to queryParams['include']", ->
@promise3 = @promise2.then =>
@resource.orders().reload()
@resource
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('include=comments')
describe 'assigning when owner is unpersisted', ->
beforeEach ->
@resource = MyLibrary.Product.build(id: 2)
@target = [MyLibrary.Order.build(id: 1), MyLibrary.Order.build(id: 2)]
@resource.orders().assign(@target)
it 'replaces the target with the resource(s)', ->
_.each @target, (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
it 'replaces the inverse target(s) of the resource(s)', ->
_.each @target, (t) =>
expect(t.product()).toBe(@resource)
it 'replaces the resources(s) foreign key(s)', ->
_.each @target, (t) =>
expect(t.productId).toEqual(@resource.id)
describe 'when assigning wrong type', ->
it 'throws an error', ->
expect(=> @resource.orders().assign(MyLibrary.OrderItem.build())).toThrow()
describe 'when foreignKey defined', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'orders', foreignKey: 'hasManyClassToken'
@resource = MyLibrary.HasManyClass.build(id: 2)
@target = MyLibrary.Order.build()
@resource.orders().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyClassToken).toEqual(2)
describe 'when primaryKey defined', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'orders', primaryKey: 'token', foreignKey: 'hasManyClassToken'
@resource = MyLibrary.HasManyClass.build(token: '<KEY>')
@target = MyLibrary.Order.build()
@resource.orders().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyClassToken).toEqual('<KEY>')
describe 'when target is polymorphic', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'belongsToPolymorphics', as: 'hasManyAlias'
class MyLibrary.BelongsToPolymorphic extends MyLibrary.Base
this.className = 'BelongsToPolymorphic'
this.queryName = 'belongs_to_polymorphics'
@belongsTo 'hasManyAlias', polymorphic: true
@resource = MyLibrary.HasManyClass.build(id: 1)
@target = MyLibrary.BelongsToPolymorphic.build()
@resource.belongsToPolymorphics().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyAliasId).toEqual(1)
it 'assigns the inverse\'s foreign type', ->
expect(@target.hasManyAliasType).toEqual('HasManyClass')
# TODO: Make `foreignType` option work with specs
describe 'assigning when owner is persisted', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'in general', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise4 = @promise3.then =>
@resource.orders().assign(@target)
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'persists the update to the relationship URL', ->
relationshipLink = 'https://example.com/api/v1/products/1/relationships/orders/'
@promise4.then =>
expect(moxios.requests.mostRecent().url).toEqual(relationshipLink)
it 'makes a PATCH request', ->
@promise4.then =>
expect(moxios.requests.mostRecent().method).toEqual('patch')
describe 'when assigning collection of resources', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise4 = @promise3.then =>
@resource.orders().assign(@target)
@resource
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{
type: 'orders',
id: '1'
},
{
type: 'orders',
id: '2'
}
]
})
@promise4.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when update succeeds', ->
beforeEach ->
@promise5 = @promise4.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'replaces the target with the resource(s)', ->
@promise5.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
it 'replaces the inverse target(s) of the resource(s)', ->
@promise5.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'replaces the resources(s) foreign key(s)', ->
@promise5.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
describe 'when update fails', ->
beforeEach ->
@promise5 = @promise4.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not replace the target with the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(t)
it 'does not replace the inverse target(s) of the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(t.product()).not.toBe(@resource)
it 'does not replace the foreign key(s) of the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(t.productId).not.toEqual(@resource.id)
describe 'when assigning empty collection', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().assign([])
@resource
it 'sends an empty document', ->
resourceDocument = JSON.stringify({
data: []
})
@promise3.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when update succeeds', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'replaces the target with an empty collection', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe 'when assigning with save: false', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@priorRequestsCount = moxios.requests.count()
@output = @resource.orders().assign(@target.toCollection(), false)
it 'does not make a request', ->
@promise3.then =>
expect(moxios.requests.count()).toEqual(@priorRequestsCount)
it 'does return assigned resources', ->
@promise3.then =>
expect(@output.klass()).toBe(ActiveResource::Collection)
it 'replaces the target', ->
@promise3.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(@target.size())
describe 'building', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@target = @resource.orders().build([{ price: 1 }, { price: 2 }])
it 'builds resource(s) of reflection klass type', ->
@promise.then =>
@target.each (t) =>
expect(t.klass()).toBe(MyLibrary.Order)
it 'assigns attributes to the resource(s)', ->
@promise.then =>
@target.each (t) =>
expect([1, 2]).toContain(t.price)
it 'assigns the inverse target(s)', ->
@promise.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'assigns the target(s) foreign key(s)', ->
@promise.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
it 'adds the resource to the target', ->
@promise.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
describe 'creating', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'in general', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3, verificationCode: 'abc123' }, window.onCompletion)
@resource
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
.then =>
@target = window.onCompletion.calls.mostRecent().args[0]
it 'makes a request to the target\'s root URL', ->
targetURL = 'https://example.com/api/v1/orders/'
@promise3.then =>
expect(moxios.requests.mostRecent().url).toEqual(targetURL)
it 'makes a POST request', ->
@promise3.then =>
expect(moxios.requests.mostRecent().method).toEqual('post')
it 'sends a resource document', ->
resourceDocument = JSON.stringify({
data: {
type: 'orders',
attributes: {
price: 3,
verification_code: 'abc123',
product_id: '1'
},
relationships: {
product: {
data: { type: 'products', id: '1' }
}
}
}
})
@promise3.then =>
expect(extractData(moxios.requests.mostRecent().data)).toEqual(resourceDocument)
it 'builds resource(s) of reflection klass type', ->
@promise3.then =>
expect(@target.klass()).toBe(MyLibrary.Order)
it 'assigns attributes to the resource(s)', ->
@promise3.then =>
expect(@target.price).toEqual(3)
it 'assigns the inverse target(s)', ->
@promise3.then =>
expect(@target.product()).toBe(@resource)
it 'assigns the resource(s) foreign key(s)', ->
@promise3.then =>
expect(@target.productId).toEqual(@resource.id)
it 'adds the resource(s) to the target', ->
@promise3.then =>
expect(@resource.orders().all(cached: true).toArray()).toContain(@target)
describe 'when creation succeeds', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3, verificationCode: 'abc123' }, window.onCompletion)
@resource
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
.then =>
@target = window.onCompletion.calls.mostRecent().args[0]
it 'persists the resource', ->
@promise3.then =>
expect(@target.persisted?()).toBeTruthy()
describe 'when creation fails', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3 }, window.onCompletion)
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
.catch =>
Promise.reject(@target = window.onCompletion.calls.mostRecent().args[0])
it 'does not persist the resource', ->
@promise2.catch =>
expect(@target.persisted?()).toBeFalsy()
it 'adds errors to the resource', ->
@promise2.catch =>
expect(@target.errors().empty?()).toBeFalsy()
describe 'when autosave association is present', ->
beforeEach ->
@promise2 = @promise.then =>
MyLibrary.Order.hasMany 'orderItems', autosave: true
orderItems = [
MyLibrary.OrderItem.build(amount: 1.0),
MyLibrary.OrderItem.build(amount: 2.0)
]
@resource.orders().create({ price: 3, orderItems: orderItems }, window.onCompletion)
@resource
afterEach ->
MyLibrary.Order.hasMany 'orderItems'
MyLibrary.Order.resetQueryParams()
it 'adds the association attributes to the resource document', ->
resourceDocument = {
type: 'orders',
attributes: {
price: 3,
product_id: '1'
},
relationships: {
product: {
data: { type: 'products', id: '1' }
},
order_items: {
data: [
{
type: 'order_items',
attributes: {
amount: 1.0
}
},
{
type: 'order_items',
attributes: {
amount: 2.0
}
}
]
}
}
}
@promise2.then =>
expect(JSON.parse(moxios.requests.mostRecent().data)['data']).toEqual(resourceDocument)
it "adds the autosave association to queryOptions['include']", ->
@promise2.then =>
expect(JSON.parse(moxios.requests.mostRecent().data)['include']).toContain('order_items')
describe 'when creation succeeds', ->
beforeEach ->
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@order = window.onCompletion.calls.mostRecent().args[0]
it 'persists the autosave association', ->
@promise3.then =>
@order.orderItems().all(cached: true).each (o) ->
expect(o.persisted()).toBeTruthy()
describe 'when owner is not persisted', ->
it 'throws exception', ->
resource = MyLibrary.Product.build()
expect(-> resource.orders().create({ price: 5 })).toThrow()
describe 'pushing', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@promise2 = @promise.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise3 = @promise2.then =>
@resource.orders().push(@target)
@resource
describe 'in general', ->
it 'makes a request to the target\'s relationship URL', ->
@promise3.then =>
expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products/1/relationships/orders/')
it 'makes a POST request', ->
@promise3.then =>
expect(moxios.requests.mostRecent().method).toEqual('post')
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' },
{ type: 'orders', id: '2' }
]
})
@promise3.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when pushing succeeds', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'assigns the inverse target(s) of the resource(s)', ->
@promise4.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'assigns the resource(s) foreign key(s)', ->
@promise4.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
it 'adds the resource(s) to the target', ->
@promise4.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
describe 'when pushing fails', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not assign the inverse target(s) of the resource(s)', ->
@promise4.catch =>
@target.each (t) =>
expect(t.product()).not.toBe(@resource)
it 'does not assign the resource(s) foreign key(s)', ->
@promise4.catch =>
@target.each (t) =>
expect(t.productId).not.toEqual(@resource.id)
it 'does not add the resource(s) to the target', ->
@promise4.catch =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(t)
describe 'deleting', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@target = @resource.orders().all(cached: true)
describe 'in general', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
@resource
it 'makes a request to the target\'s relationship URL', ->
@promise2.then =>
expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products/1/relationships/orders/')
it 'makes a DELETE request', ->
@promise2.then =>
expect(moxios.requests.mostRecent().method).toEqual('delete')
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' }
]
})
@promise2.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when deleting succeeds', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'removes the inverse target(s) of the resource(s)', ->
@promise2.then =>
expect(@target.first().product()).toBeNull()
it 'removes the resource(s) foreign key(s)', ->
@promise2.then =>
expect(@target.first().productId).toBeNull()
it 'removes the resource(s) from the target', ->
@promise2.then =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(@target.first())
describe 'when deleting fails', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not remove the inverse target(s) of the resource(s)', ->
@promise2.catch =>
expect(@target.first().product()).toBe(@resource)
it 'does not remove the resource(s) foreign key(s)', ->
@promise2.catch =>
expect(@target.first().productId).toEqual(@resource.id)
it 'does not remove the resource(s) from the target', ->
@promise2.catch =>
expect(@resource.orders().all(cached: true).toArray()).toContain(@target.first())
describe '#deleteAll()', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().deleteAll()
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'sends a resource identifier document with all resources', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' },
{ type: 'orders', id: '2' }
]
})
@promise2.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
it 'deletes all resources from the target', ->
@promise2.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#empty()', ->
describe 'when target is empty', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns true', ->
@promise.then =>
expect(@resource.orders().empty()).toBeTruthy()
describe 'when target is not empty', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns false', ->
@promise.then =>
expect(@resource.orders().empty()).toBeFalsy()
| true | describe 'ActiveResource', ->
beforeEach ->
moxios.install(MyLibrary.interface.axios)
window.onSuccess = jasmine.createSpy('onSuccess')
window.onFailure = jasmine.createSpy('onFailure')
window.onCompletion = jasmine.createSpy('onCompletion')
afterEach ->
moxios.uninstall()
describe '::Associations', ->
describe '::HasManyAssociation', ->
describe 'reading', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns a CollectionProxy', ->
@promise.then =>
expect(@resource.orders().klass()).toBe(ActiveResource::Associations::CollectionProxy)
describe '#all(cached: true)', ->
it 'returns a collection', ->
@promise.then =>
expect(@resource.orders().all(cached: true).klass()).toBe(ActiveResource::Collection)
it 'returns resources already loaded', ->
@promise.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(2)
describe 'loading', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'uses relationship data URL', ->
relationshipLinks = {
self: 'https://example.com/api/v1/products/1/relationships/orders/',
related: 'https://example.com/api/v1/products/1/orders/'
}
@promise2.then =>
expect(@resource.orders().links()).toEqual(relationshipLinks)
describe '#loadTarget()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.association('orders').loadTarget()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@target.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@target.first().klass()).toBe(MyLibrary.Order)
it 'caches the result on the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(@target.size())
describe '#all()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().all()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@result.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@result.first().klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#load()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().where(some: 'value').load()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'returns a collection', ->
@promise4.then =>
expect(@result.klass()).toBe(ActiveResource::CollectionResponse)
it 'returns a collection of resources of reflection klass type', ->
@promise4.then =>
expect(@result.first().klass()).toBe(MyLibrary.Order)
it 'does assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).not.toEqual(0)
it 'queries the first relationship resource with filters', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[some]=value')
describe '#first()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().first()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first resource of the relationship data URL', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('limit=1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#last()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().last()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first resource of the relationship data URL', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('limit=1&offset=-1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#find()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().find(1)
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries a specific member of the relationship data URL', ->
memberLink = 'https://example.com/api/v1/products/1/orders/1'
@promise4.then =>
expect(moxios.requests.mostRecent().url).toContain(memberLink)
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#findBy()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().findBy(token: 'PI:KEY:<KEY>END_PI')
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'queries the first relationship resource with filters', ->
@promise4.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[token]=PI:KEY:<KEY>END_PI', 'limit=1')
it 'gets a resource of the relationship', ->
@promise4.then =>
expect(@result.klass()).toBe(MyLibrary.Order)
it 'does not assign the target', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe 'when using a Relation extension method', ->
it 'extends the association relation', ->
@promise2.then =>
expect(@resource.orders().where().klass()).toBe(ActiveResource::Associations::CollectionProxy)
it 'adds query params to the relationship URL query', ->
@promise3 = @promise2.then =>
@resource.orders().where(price: 5).all()
@resource
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('filter[price]=5')
describe '#select()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().select('price','verificationCode').all()
@resource
it 'uses the correct model name for shallow fields', ->
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('fields[orders]=price,verification_code')
describe '#includes()', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().includes('orderItems').all()
.then window.onSuccess
@resource
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.includes)
.then =>
@result = window.onSuccess.calls.mostRecent().args[0]
it 'associates included resources', ->
@promise4.then =>
expect(@result.first().orderItems().all(cached: true).size()).toEqual(1)
expect(@result.last().orderItems().all(cached: true).size()).toEqual(1)
describe 'reloading', ->
describe 'when nested associations were included', ->
beforeEach ->
MyLibrary.Product.includes(orders: 'comments').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it "adds the nested associations to queryParams['include']", ->
@promise3 = @promise2.then =>
@resource.orders().reload()
@resource
@promise3.then =>
expect(requestParams(moxios.requests.mostRecent())).toContain('include=comments')
describe 'assigning when owner is unpersisted', ->
beforeEach ->
@resource = MyLibrary.Product.build(id: 2)
@target = [MyLibrary.Order.build(id: 1), MyLibrary.Order.build(id: 2)]
@resource.orders().assign(@target)
it 'replaces the target with the resource(s)', ->
_.each @target, (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
it 'replaces the inverse target(s) of the resource(s)', ->
_.each @target, (t) =>
expect(t.product()).toBe(@resource)
it 'replaces the resources(s) foreign key(s)', ->
_.each @target, (t) =>
expect(t.productId).toEqual(@resource.id)
describe 'when assigning wrong type', ->
it 'throws an error', ->
expect(=> @resource.orders().assign(MyLibrary.OrderItem.build())).toThrow()
describe 'when foreignKey defined', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'orders', foreignKey: 'hasManyClassToken'
@resource = MyLibrary.HasManyClass.build(id: 2)
@target = MyLibrary.Order.build()
@resource.orders().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyClassToken).toEqual(2)
describe 'when primaryKey defined', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'orders', primaryKey: 'token', foreignKey: 'hasManyClassToken'
@resource = MyLibrary.HasManyClass.build(token: 'PI:KEY:<KEY>END_PI')
@target = MyLibrary.Order.build()
@resource.orders().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyClassToken).toEqual('PI:KEY:<KEY>END_PI')
describe 'when target is polymorphic', ->
beforeEach ->
class MyLibrary.HasManyClass extends MyLibrary.Base
this.className = 'HasManyClass'
this.queryName = 'has_many_classes'
@hasMany 'belongsToPolymorphics', as: 'hasManyAlias'
class MyLibrary.BelongsToPolymorphic extends MyLibrary.Base
this.className = 'BelongsToPolymorphic'
this.queryName = 'belongs_to_polymorphics'
@belongsTo 'hasManyAlias', polymorphic: true
@resource = MyLibrary.HasManyClass.build(id: 1)
@target = MyLibrary.BelongsToPolymorphic.build()
@resource.belongsToPolymorphics().assign(@target)
it 'assigns the inverse\'s foreign key', ->
expect(@target.hasManyAliasId).toEqual(1)
it 'assigns the inverse\'s foreign type', ->
expect(@target.hasManyAliasType).toEqual('HasManyClass')
# TODO: Make `foreignType` option work with specs
describe 'assigning when owner is persisted', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
@promise2 = @promise.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'in general', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise4 = @promise3.then =>
@resource.orders().assign(@target)
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'persists the update to the relationship URL', ->
relationshipLink = 'https://example.com/api/v1/products/1/relationships/orders/'
@promise4.then =>
expect(moxios.requests.mostRecent().url).toEqual(relationshipLink)
it 'makes a PATCH request', ->
@promise4.then =>
expect(moxios.requests.mostRecent().method).toEqual('patch')
describe 'when assigning collection of resources', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise4 = @promise3.then =>
@resource.orders().assign(@target)
@resource
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{
type: 'orders',
id: '1'
},
{
type: 'orders',
id: '2'
}
]
})
@promise4.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when update succeeds', ->
beforeEach ->
@promise5 = @promise4.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'replaces the target with the resource(s)', ->
@promise5.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
it 'replaces the inverse target(s) of the resource(s)', ->
@promise5.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'replaces the resources(s) foreign key(s)', ->
@promise5.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
describe 'when update fails', ->
beforeEach ->
@promise5 = @promise4.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not replace the target with the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(t)
it 'does not replace the inverse target(s) of the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(t.product()).not.toBe(@resource)
it 'does not replace the foreign key(s) of the resource(s)', ->
@promise5.catch =>
@target.each (t) =>
expect(t.productId).not.toEqual(@resource.id)
describe 'when assigning empty collection', ->
beforeEach ->
@promise3 = @promise2.then =>
@resource.orders().assign([])
@resource
it 'sends an empty document', ->
resourceDocument = JSON.stringify({
data: []
})
@promise3.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when update succeeds', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'replaces the target with an empty collection', ->
@promise4.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe 'when assigning with save: false', ->
beforeEach ->
@promise3 = @promise2.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@priorRequestsCount = moxios.requests.count()
@output = @resource.orders().assign(@target.toCollection(), false)
it 'does not make a request', ->
@promise3.then =>
expect(moxios.requests.count()).toEqual(@priorRequestsCount)
it 'does return assigned resources', ->
@promise3.then =>
expect(@output.klass()).toBe(ActiveResource::Collection)
it 'replaces the target', ->
@promise3.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(@target.size())
describe 'building', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@target = @resource.orders().build([{ price: 1 }, { price: 2 }])
it 'builds resource(s) of reflection klass type', ->
@promise.then =>
@target.each (t) =>
expect(t.klass()).toBe(MyLibrary.Order)
it 'assigns attributes to the resource(s)', ->
@promise.then =>
@target.each (t) =>
expect([1, 2]).toContain(t.price)
it 'assigns the inverse target(s)', ->
@promise.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'assigns the target(s) foreign key(s)', ->
@promise.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
it 'adds the resource to the target', ->
@promise.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
describe 'creating', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
describe 'in general', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3, verificationCode: 'abc123' }, window.onCompletion)
@resource
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
.then =>
@target = window.onCompletion.calls.mostRecent().args[0]
it 'makes a request to the target\'s root URL', ->
targetURL = 'https://example.com/api/v1/orders/'
@promise3.then =>
expect(moxios.requests.mostRecent().url).toEqual(targetURL)
it 'makes a POST request', ->
@promise3.then =>
expect(moxios.requests.mostRecent().method).toEqual('post')
it 'sends a resource document', ->
resourceDocument = JSON.stringify({
data: {
type: 'orders',
attributes: {
price: 3,
verification_code: 'abc123',
product_id: '1'
},
relationships: {
product: {
data: { type: 'products', id: '1' }
}
}
}
})
@promise3.then =>
expect(extractData(moxios.requests.mostRecent().data)).toEqual(resourceDocument)
it 'builds resource(s) of reflection klass type', ->
@promise3.then =>
expect(@target.klass()).toBe(MyLibrary.Order)
it 'assigns attributes to the resource(s)', ->
@promise3.then =>
expect(@target.price).toEqual(3)
it 'assigns the inverse target(s)', ->
@promise3.then =>
expect(@target.product()).toBe(@resource)
it 'assigns the resource(s) foreign key(s)', ->
@promise3.then =>
expect(@target.productId).toEqual(@resource.id)
it 'adds the resource(s) to the target', ->
@promise3.then =>
expect(@resource.orders().all(cached: true).toArray()).toContain(@target)
describe 'when creation succeeds', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3, verificationCode: 'abc123' }, window.onCompletion)
@resource
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.success)
.then =>
@target = window.onCompletion.calls.mostRecent().args[0]
it 'persists the resource', ->
@promise3.then =>
expect(@target.persisted?()).toBeTruthy()
describe 'when creation fails', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().create({ price: 3 }, window.onCompletion)
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.save.failure)
.catch =>
Promise.reject(@target = window.onCompletion.calls.mostRecent().args[0])
it 'does not persist the resource', ->
@promise2.catch =>
expect(@target.persisted?()).toBeFalsy()
it 'adds errors to the resource', ->
@promise2.catch =>
expect(@target.errors().empty?()).toBeFalsy()
describe 'when autosave association is present', ->
beforeEach ->
@promise2 = @promise.then =>
MyLibrary.Order.hasMany 'orderItems', autosave: true
orderItems = [
MyLibrary.OrderItem.build(amount: 1.0),
MyLibrary.OrderItem.build(amount: 2.0)
]
@resource.orders().create({ price: 3, orderItems: orderItems }, window.onCompletion)
@resource
afterEach ->
MyLibrary.Order.hasMany 'orderItems'
MyLibrary.Order.resetQueryParams()
it 'adds the association attributes to the resource document', ->
resourceDocument = {
type: 'orders',
attributes: {
price: 3,
product_id: '1'
},
relationships: {
product: {
data: { type: 'products', id: '1' }
},
order_items: {
data: [
{
type: 'order_items',
attributes: {
amount: 1.0
}
},
{
type: 'order_items',
attributes: {
amount: 2.0
}
}
]
}
}
}
@promise2.then =>
expect(JSON.parse(moxios.requests.mostRecent().data)['data']).toEqual(resourceDocument)
it "adds the autosave association to queryOptions['include']", ->
@promise2.then =>
expect(JSON.parse(moxios.requests.mostRecent().data)['include']).toContain('order_items')
describe 'when creation succeeds', ->
beforeEach ->
@promise3 = @promise2.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.find.includes)
.then =>
@order = window.onCompletion.calls.mostRecent().args[0]
it 'persists the autosave association', ->
@promise3.then =>
@order.orderItems().all(cached: true).each (o) ->
expect(o.persisted()).toBeTruthy()
describe 'when owner is not persisted', ->
it 'throws exception', ->
resource = MyLibrary.Product.build()
expect(-> resource.orders().create({ price: 5 })).toThrow()
describe 'pushing', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@promise2 = @promise.then =>
MyLibrary.Order.all()
.then window.onSuccess
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Order.all.success)
.then =>
@target = window.onSuccess.calls.mostRecent().args[0]
@promise3 = @promise2.then =>
@resource.orders().push(@target)
@resource
describe 'in general', ->
it 'makes a request to the target\'s relationship URL', ->
@promise3.then =>
expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products/1/relationships/orders/')
it 'makes a POST request', ->
@promise3.then =>
expect(moxios.requests.mostRecent().method).toEqual('post')
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' },
{ type: 'orders', id: '2' }
]
})
@promise3.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when pushing succeeds', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'assigns the inverse target(s) of the resource(s)', ->
@promise4.then =>
@target.each (t) =>
expect(t.product()).toBe(@resource)
it 'assigns the resource(s) foreign key(s)', ->
@promise4.then =>
@target.each (t) =>
expect(t.productId).toEqual(@resource.id)
it 'adds the resource(s) to the target', ->
@promise4.then =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).toContain(t)
describe 'when pushing fails', ->
beforeEach ->
@promise4 = @promise3.then =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not assign the inverse target(s) of the resource(s)', ->
@promise4.catch =>
@target.each (t) =>
expect(t.product()).not.toBe(@resource)
it 'does not assign the resource(s) foreign key(s)', ->
@promise4.catch =>
@target.each (t) =>
expect(t.productId).not.toEqual(@resource.id)
it 'does not add the resource(s) to the target', ->
@promise4.catch =>
@target.each (t) =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(t)
describe 'deleting', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
@target = @resource.orders().all(cached: true)
describe 'in general', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
@resource
it 'makes a request to the target\'s relationship URL', ->
@promise2.then =>
expect(moxios.requests.mostRecent().url).toEqual('https://example.com/api/v1/products/1/relationships/orders/')
it 'makes a DELETE request', ->
@promise2.then =>
expect(moxios.requests.mostRecent().method).toEqual('delete')
it 'sends a resource identifier document', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' }
]
})
@promise2.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
describe 'when deleting succeeds', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'removes the inverse target(s) of the resource(s)', ->
@promise2.then =>
expect(@target.first().product()).toBeNull()
it 'removes the resource(s) foreign key(s)', ->
@promise2.then =>
expect(@target.first().productId).toBeNull()
it 'removes the resource(s) from the target', ->
@promise2.then =>
expect(@resource.orders().all(cached: true).toArray()).not.toContain(@target.first())
describe 'when deleting fails', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().delete(@target.first())
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.failure)
it 'does not remove the inverse target(s) of the resource(s)', ->
@promise2.catch =>
expect(@target.first().product()).toBe(@resource)
it 'does not remove the resource(s) foreign key(s)', ->
@promise2.catch =>
expect(@target.first().productId).toEqual(@resource.id)
it 'does not remove the resource(s) from the target', ->
@promise2.catch =>
expect(@resource.orders().all(cached: true).toArray()).toContain(@target.first())
describe '#deleteAll()', ->
beforeEach ->
@promise2 = @promise.then =>
@resource.orders().deleteAll()
moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.relationships.update.success)
it 'sends a resource identifier document with all resources', ->
resourceDocument = JSON.stringify({
data: [
{ type: 'orders', id: '1' },
{ type: 'orders', id: '2' }
]
})
@promise2.then =>
expect(moxios.requests.mostRecent().data).toEqual(resourceDocument)
it 'deletes all resources from the target', ->
@promise2.then =>
expect(@resource.orders().all(cached: true).size()).toEqual(0)
describe '#empty()', ->
describe 'when target is empty', ->
beforeEach ->
MyLibrary.Product.find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.success)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns true', ->
@promise.then =>
expect(@resource.orders().empty()).toBeTruthy()
describe 'when target is not empty', ->
beforeEach ->
MyLibrary.Product.includes('orders').find(1)
.then window.onSuccess
@promise = moxios.wait =>
moxios.requests.mostRecent().respondWith(JsonApiResponses.Product.find.includes)
.then =>
@resource = window.onSuccess.calls.mostRecent().args[0]
it 'returns false', ->
@promise.then =>
expect(@resource.orders().empty()).toBeFalsy()
|
[
{
"context": "name = 'World'\nconsole.log \"Hello, #{name}!\"\n",
"end": 13,
"score": 0.9987467527389526,
"start": 8,
"tag": "NAME",
"value": "World"
}
] | node_modules/grunt-cumulocity-ui-tasks/node_modules/connect-static-transform/examples/file.coffee | kkoStudyAcc/tvtest3 | 10 | name = 'World'
console.log "Hello, #{name}!"
| 42353 | name = '<NAME>'
console.log "Hello, #{name}!"
| true | name = 'PI:NAME:<NAME>END_PI'
console.log "Hello, #{name}!"
|
[
{
"context": "rator.should.eql 3\n client.users.getByEmail \"dor@ethylocle.com\", (err, user) ->\n return next err if err\n ",
"end": 630,
"score": 0.9999330639839172,
"start": 613,
"tag": "EMAIL",
"value": "dor@ethylocle.com"
},
{
"context": " next err if err\n user.email.should.eql \"dor@ethylocle.com\"\n user.picture.should.eql \"null\"\n ",
"end": 811,
"score": 0.9999330043792725,
"start": 794,
"tag": "EMAIL",
"value": "dor@ethylocle.com"
},
{
"context": "ld.eql \"null\"\n user.lastname.should.eql \"Bagur\"\n user.firstname.should.eql \"Dorian\"\n ",
"end": 895,
"score": 0.9996951222419739,
"start": 890,
"tag": "NAME",
"value": "Bagur"
},
{
"context": ".eql \"Bagur\"\n user.firstname.should.eql \"Dorian\"\n user.birthDate.should.eql \"08-09-1993\"",
"end": 940,
"score": 0.9995381832122803,
"start": 934,
"tag": "NAME",
"value": "Dorian"
},
{
"context": "330686329855\"\n user.password.should.eql \"1234\"\n user.latitude.should.eql \"48.888\"\n ",
"end": 1340,
"score": 0.9993184804916382,
"start": 1336,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "2015 15:05:30\"\n client.users.getByEmail \"mao@ethylocle.com\", (err, user) ->\n return next err if e",
"end": 1654,
"score": 0.9999340772628784,
"start": 1637,
"tag": "EMAIL",
"value": "mao@ethylocle.com"
},
{
"context": "t err if err\n user.email.should.eql \"mao@ethylocle.com\"\n user.picture.should.eql \"null\"\n ",
"end": 1851,
"score": 0.9999349117279053,
"start": 1834,
"tag": "EMAIL",
"value": "mao@ethylocle.com"
},
{
"context": "ql \"null\"\n user.lastname.should.eql \"Zho\"\n user.firstname.should.eql \"Mao\"\n ",
"end": 1941,
"score": 0.9998010993003845,
"start": 1938,
"tag": "NAME",
"value": "Zho"
},
{
"context": "ql \"Zho\"\n user.firstname.should.eql \"Mao\"\n user.birthDate.should.eql \"08-09-1",
"end": 1987,
"score": 0.9998378753662109,
"start": 1984,
"tag": "NAME",
"value": "Mao"
},
{
"context": "86329855\"\n user.password.should.eql \"1234\"\n user.latitude.should.eql \"48.888\"\n",
"end": 2404,
"score": 0.9992546439170837,
"start": 2400,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": " 15:05:30\"\n client.users.getByEmail \"rob@ethylocle.com\", (err, user) ->\n return next err ",
"end": 2742,
"score": 0.9999345541000366,
"start": 2725,
"tag": "EMAIL",
"value": "rob@ethylocle.com"
},
{
"context": "r if err\n user.email.should.eql \"rob@ethylocle.com\"\n user.picture.should.eql \"null\"",
"end": 2955,
"score": 0.9999347925186157,
"start": 2938,
"tag": "EMAIL",
"value": "rob@ethylocle.com"
},
{
"context": "null\"\n user.lastname.should.eql \"Bio\"\n user.firstname.should.eql \"Rob",
"end": 3053,
"score": 0.9997768998146057,
"start": 3050,
"tag": "NAME",
"value": "Bio"
},
{
"context": "Bio\"\n user.firstname.should.eql \"Rob\"\n user.birthDate.should.eql \"08-",
"end": 3103,
"score": 0.9998573064804077,
"start": 3100,
"tag": "NAME",
"value": "Rob"
},
{
"context": "9855\"\n user.password.should.eql \"1234\"\n user.latitude.should.eql \"48.8",
"end": 3556,
"score": 0.9994169473648071,
"start": 3552,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "rator.should.eql 3\n client.users.getByEmail \"dor@ethylocle.com\", (err, user) ->\n return next err if err\n ",
"end": 4251,
"score": 0.9999321699142456,
"start": 4234,
"tag": "EMAIL",
"value": "dor@ethylocle.com"
},
{
"context": " next err if err\n user.email.should.eql \"dor@ethylocle.com\"\n user.picture.should.eql \"null\"\n ",
"end": 4432,
"score": 0.9999332427978516,
"start": 4415,
"tag": "EMAIL",
"value": "dor@ethylocle.com"
},
{
"context": "ld.eql \"null\"\n user.lastname.should.eql \"Bagur\"\n user.firstname.should.eql \"Dorian\"\n ",
"end": 4516,
"score": 0.9997344017028809,
"start": 4511,
"tag": "NAME",
"value": "Bagur"
},
{
"context": ".eql \"Bagur\"\n user.firstname.should.eql \"Dorian\"\n user.birthDate.should.eql \"08-09-1993\"",
"end": 4561,
"score": 0.9994223117828369,
"start": 4555,
"tag": "NAME",
"value": "Dorian"
},
{
"context": "2015 15:05:30\"\n client.users.getByEmail \"mao@ethylocle.com\", (err, user) ->\n return next err if e",
"end": 5275,
"score": 0.999934196472168,
"start": 5258,
"tag": "EMAIL",
"value": "mao@ethylocle.com"
},
{
"context": "t err if err\n user.email.should.eql \"mao@ethylocle.com\"\n user.picture.should.eql \"null\"\n ",
"end": 5472,
"score": 0.9999335408210754,
"start": 5455,
"tag": "EMAIL",
"value": "mao@ethylocle.com"
},
{
"context": "ql \"null\"\n user.lastname.should.eql \"Zho\"\n user.firstname.should.eql \"Mao\"\n ",
"end": 5562,
"score": 0.9996415376663208,
"start": 5559,
"tag": "NAME",
"value": "Zho"
},
{
"context": "ql \"Zho\"\n user.firstname.should.eql \"Mao\"\n user.birthDate.should.eql \"08-09-1",
"end": 5608,
"score": 0.9997245073318481,
"start": 5605,
"tag": "NAME",
"value": "Mao"
},
{
"context": "88963477\"\n user.password.should.eql \"1234\"\n user.latitude.should.eql \"48.888\"\n",
"end": 6025,
"score": 0.9993280172348022,
"start": 6021,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": " 15:05:30\"\n client.users.getByEmail \"rob@ethylocle.com\", (err, user) ->\n return next err ",
"end": 6363,
"score": 0.9999344348907471,
"start": 6346,
"tag": "EMAIL",
"value": "rob@ethylocle.com"
},
{
"context": "r if err\n user.email.should.eql \"rob@ethylocle.com\"\n user.picture.should.eql \"null\"",
"end": 6576,
"score": 0.9999295473098755,
"start": 6559,
"tag": "EMAIL",
"value": "rob@ethylocle.com"
},
{
"context": "null\"\n user.lastname.should.eql \"Bio\"\n user.firstname.should.eql \"Rob",
"end": 6674,
"score": 0.9989951252937317,
"start": 6671,
"tag": "NAME",
"value": "Bio"
},
{
"context": "Bio\"\n user.firstname.should.eql \"Rob\"\n user.birthDate.should.eql \"08-",
"end": 6724,
"score": 0.9996597766876221,
"start": 6721,
"tag": "NAME",
"value": "Rob"
},
{
"context": "3477\"\n user.password.should.eql \"1234\"\n user.latitude.should.eql \"48.8",
"end": 7177,
"score": 0.9993860125541687,
"start": 7173,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "r if err\n stop.stop_name.should.eql \"VAL D'OR\"\n stop.stop_desc.should.eql '20",
"end": 9230,
"score": 0.5838043689727783,
"start": 9227,
"tag": "NAME",
"value": "VAL"
}
] | lib/model/levelDB/tool/test/import.coffee | dorianb/Web-application---Ethylocl- | 0 | rimraf = require 'rimraf'
should = require 'should'
fs = require 'fs'
importStream = require '../import'
Down = require '../../down'
describe 'Import', ->
beforeEach (next) ->
rimraf "#{__dirname}/../../../../../db/tmp/user", ->
rimraf "#{__dirname}/../../../../../db/tmp/stop", next
it 'Import users from csv', (next) ->
client = Down "#{__dirname}/../../../../../db/tmp/user"
fs
.createReadStream "#{__dirname}/../../../../../resource/user sample.csv"
.pipe importStream client, 'csv', 'user'
.on 'finish', ->
this.iterator.should.eql 3
client.users.getByEmail "dor@ethylocle.com", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "dor@ethylocle.com"
user.picture.should.eql "null"
user.lastname.should.eql "Bagur"
user.firstname.should.eql "Dorian"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "78700"
user.city.should.eql "Conflans-Sainte-Honorine"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "mao@ethylocle.com", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "mao@ethylocle.com"
user.picture.should.eql "null"
user.lastname.should.eql "Zho"
user.firstname.should.eql "Mao"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "rob@ethylocle.com", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "rob@ethylocle.com"
user.picture.should.eql "null"
user.lastname.should.eql "Bio"
user.firstname.should.eql "Rob"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.close()
next()
it 'Import users from json', (next) ->
client = Down "#{__dirname}/../../../../../db/tmp/user"
fs
.createReadStream "#{__dirname}/../../../../../resource/user sample.json"
.pipe importStream client, 'json', 'user'
.on 'finish', ->
this.iterator.should.eql 3
client.users.getByEmail "dor@ethylocle.com", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "dor@ethylocle.com"
user.picture.should.eql "null"
user.lastname.should.eql "Bagur"
user.firstname.should.eql "Dorian"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "78700"
user.city.should.eql "Conflans-Sainte-Honorine"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "mao@ethylocle.com", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "mao@ethylocle.com"
user.picture.should.eql "null"
user.lastname.should.eql "Zho"
user.firstname.should.eql "Mao"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "rob@ethylocle.com", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "rob@ethylocle.com"
user.picture.should.eql "null"
user.lastname.should.eql "Bio"
user.firstname.should.eql "Rob"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.close()
next()
it 'Import stops from csv', (next) ->
this.timeout 10000
client = Down "#{__dirname}/../../../../../db/tmp/stop"
fs
.createReadStream "#{__dirname}/../../../../../resource/ratp_stops_with_routes.csv"
.pipe importStream client, 'csv', 'stop'
.on 'finish', ->
this.iterator.should.eql 26621
client.stops.get '4035172', (err, stop) ->
return next err if err
stop.stop_name.should.eql 'REPUBLIQUE - DEFORGES'
stop.stop_desc.should.eql 'FACE 91 AVENUE DE LA REPUBLIQUE - 92020'
stop.stop_lat.should.eql '48.80383802353411'
stop.stop_lon.should.eql '2.2978373453843948'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS N63'
client.stops.get '1724', (err, stop) ->
return next err if err
stop.stop_name.should.eql 'Saint-Lazare'
stop.stop_desc.should.eql 'Saint-Lazare (97 rue) - 75108'
stop.stop_lat.should.eql '48.876067814352574'
stop.stop_lon.should.eql '2.324188100771013'
stop.line_type.should.eql 'M;M'
stop.line_name.should.eql 'M 13;M 13'
client.stops.get '3663555', (err, stop) ->
return next err if err
stop.stop_name.should.eql '8 MAI 1945'
stop.stop_desc.should.eql '7 RUE DES MARTYRS DE LA DEPORTATION - 93007'
stop.stop_lat.should.eql '48.94760765462246'
stop.stop_lon.should.eql '2.438002324652052'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS 148'
client.stops.get '4035339', (err, stop) ->
return next err if err
stop.stop_name.should.eql "VAL D'OR"
stop.stop_desc.should.eql '20 BOULEVARD LOUIS LOUCHEUR - 92073'
stop.stop_lat.should.eql '48.860042582683505'
stop.stop_lon.should.eql '2.2133715937731506'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS N53'
client.close()
next()
| 124496 | rimraf = require 'rimraf'
should = require 'should'
fs = require 'fs'
importStream = require '../import'
Down = require '../../down'
describe 'Import', ->
beforeEach (next) ->
rimraf "#{__dirname}/../../../../../db/tmp/user", ->
rimraf "#{__dirname}/../../../../../db/tmp/stop", next
it 'Import users from csv', (next) ->
client = Down "#{__dirname}/../../../../../db/tmp/user"
fs
.createReadStream "#{__dirname}/../../../../../resource/user sample.csv"
.pipe importStream client, 'csv', 'user'
.on 'finish', ->
this.iterator.should.eql 3
client.users.getByEmail "<EMAIL>", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "<EMAIL>"
user.picture.should.eql "null"
user.lastname.should.eql "<NAME>"
user.firstname.should.eql "<NAME>"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "78700"
user.city.should.eql "Conflans-Sainte-Honorine"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "<PASSWORD>"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "<EMAIL>", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "<EMAIL>"
user.picture.should.eql "null"
user.lastname.should.eql "<NAME>"
user.firstname.should.eql "<NAME>"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "<PASSWORD>"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "<EMAIL>", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "<EMAIL>"
user.picture.should.eql "null"
user.lastname.should.eql "<NAME>"
user.firstname.should.eql "<NAME>"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "<PASSWORD>"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.close()
next()
it 'Import users from json', (next) ->
client = Down "#{__dirname}/../../../../../db/tmp/user"
fs
.createReadStream "#{__dirname}/../../../../../resource/user sample.json"
.pipe importStream client, 'json', 'user'
.on 'finish', ->
this.iterator.should.eql 3
client.users.getByEmail "<EMAIL>", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "<EMAIL>"
user.picture.should.eql "null"
user.lastname.should.eql "<NAME>"
user.firstname.should.eql "<NAME>"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "78700"
user.city.should.eql "Conflans-Sainte-Honorine"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "<EMAIL>", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "<EMAIL>"
user.picture.should.eql "null"
user.lastname.should.eql "<NAME>"
user.firstname.should.eql "<NAME>"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "<PASSWORD>"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "<EMAIL>", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "<EMAIL>"
user.picture.should.eql "null"
user.lastname.should.eql "<NAME>"
user.firstname.should.eql "<NAME>"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "<PASSWORD>"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.close()
next()
it 'Import stops from csv', (next) ->
this.timeout 10000
client = Down "#{__dirname}/../../../../../db/tmp/stop"
fs
.createReadStream "#{__dirname}/../../../../../resource/ratp_stops_with_routes.csv"
.pipe importStream client, 'csv', 'stop'
.on 'finish', ->
this.iterator.should.eql 26621
client.stops.get '4035172', (err, stop) ->
return next err if err
stop.stop_name.should.eql 'REPUBLIQUE - DEFORGES'
stop.stop_desc.should.eql 'FACE 91 AVENUE DE LA REPUBLIQUE - 92020'
stop.stop_lat.should.eql '48.80383802353411'
stop.stop_lon.should.eql '2.2978373453843948'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS N63'
client.stops.get '1724', (err, stop) ->
return next err if err
stop.stop_name.should.eql 'Saint-Lazare'
stop.stop_desc.should.eql 'Saint-Lazare (97 rue) - 75108'
stop.stop_lat.should.eql '48.876067814352574'
stop.stop_lon.should.eql '2.324188100771013'
stop.line_type.should.eql 'M;M'
stop.line_name.should.eql 'M 13;M 13'
client.stops.get '3663555', (err, stop) ->
return next err if err
stop.stop_name.should.eql '8 MAI 1945'
stop.stop_desc.should.eql '7 RUE DES MARTYRS DE LA DEPORTATION - 93007'
stop.stop_lat.should.eql '48.94760765462246'
stop.stop_lon.should.eql '2.438002324652052'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS 148'
client.stops.get '4035339', (err, stop) ->
return next err if err
stop.stop_name.should.eql "<NAME> D'OR"
stop.stop_desc.should.eql '20 BOULEVARD LOUIS LOUCHEUR - 92073'
stop.stop_lat.should.eql '48.860042582683505'
stop.stop_lon.should.eql '2.2133715937731506'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS N53'
client.close()
next()
| true | rimraf = require 'rimraf'
should = require 'should'
fs = require 'fs'
importStream = require '../import'
Down = require '../../down'
describe 'Import', ->
beforeEach (next) ->
rimraf "#{__dirname}/../../../../../db/tmp/user", ->
rimraf "#{__dirname}/../../../../../db/tmp/stop", next
it 'Import users from csv', (next) ->
client = Down "#{__dirname}/../../../../../db/tmp/user"
fs
.createReadStream "#{__dirname}/../../../../../resource/user sample.csv"
.pipe importStream client, 'csv', 'user'
.on 'finish', ->
this.iterator.should.eql 3
client.users.getByEmail "PI:EMAIL:<EMAIL>END_PI", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "PI:EMAIL:<EMAIL>END_PI"
user.picture.should.eql "null"
user.lastname.should.eql "PI:NAME:<NAME>END_PI"
user.firstname.should.eql "PI:NAME:<NAME>END_PI"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "78700"
user.city.should.eql "Conflans-Sainte-Honorine"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "PI:PASSWORD:<PASSWORD>END_PI"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "PI:EMAIL:<EMAIL>END_PI", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "PI:EMAIL:<EMAIL>END_PI"
user.picture.should.eql "null"
user.lastname.should.eql "PI:NAME:<NAME>END_PI"
user.firstname.should.eql "PI:NAME:<NAME>END_PI"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "PI:PASSWORD:<PASSWORD>END_PI"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "PI:EMAIL:<EMAIL>END_PI", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "PI:EMAIL:<EMAIL>END_PI"
user.picture.should.eql "null"
user.lastname.should.eql "PI:NAME:<NAME>END_PI"
user.firstname.should.eql "PI:NAME:<NAME>END_PI"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330686329855"
user.password.should.eql "PI:PASSWORD:<PASSWORD>END_PI"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.close()
next()
it 'Import users from json', (next) ->
client = Down "#{__dirname}/../../../../../db/tmp/user"
fs
.createReadStream "#{__dirname}/../../../../../resource/user sample.json"
.pipe importStream client, 'json', 'user'
.on 'finish', ->
this.iterator.should.eql 3
client.users.getByEmail "PI:EMAIL:<EMAIL>END_PI", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "PI:EMAIL:<EMAIL>END_PI"
user.picture.should.eql "null"
user.lastname.should.eql "PI:NAME:<NAME>END_PI"
user.firstname.should.eql "PI:NAME:<NAME>END_PI"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "78700"
user.city.should.eql "Conflans-Sainte-Honorine"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "1234"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "PI:EMAIL:<EMAIL>END_PI", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "PI:EMAIL:<EMAIL>END_PI"
user.picture.should.eql "null"
user.lastname.should.eql "PI:NAME:<NAME>END_PI"
user.firstname.should.eql "PI:NAME:<NAME>END_PI"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "PI:PASSWORD:<PASSWORD>END_PI"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.users.getByEmail "PI:EMAIL:<EMAIL>END_PI", (err, user) ->
return next err if err
client.users.get user.id, (err, user) ->
return next err if err
user.email.should.eql "PI:EMAIL:<EMAIL>END_PI"
user.picture.should.eql "null"
user.lastname.should.eql "PI:NAME:<NAME>END_PI"
user.firstname.should.eql "PI:NAME:<NAME>END_PI"
user.birthDate.should.eql "08-09-1993"
user.gender.should.eql "M"
user.weight.should.eql "75.5"
user.address.should.eql "null"
user.zipCode.should.eql "75000"
user.city.should.eql "Paris"
user.country.should.eql "France"
user.phone.should.eql "+330688963477"
user.password.should.eql "PI:PASSWORD:<PASSWORD>END_PI"
user.latitude.should.eql "48.888"
user.longitude.should.eql "70.55"
user.lastKnownPositionDate.should.eql "15-01-2015 15:05:30"
user.bac.should.eql "0.56"
user.lastBacKnownDate.should.eql "15-01-2015 15:05:30"
client.close()
next()
it 'Import stops from csv', (next) ->
this.timeout 10000
client = Down "#{__dirname}/../../../../../db/tmp/stop"
fs
.createReadStream "#{__dirname}/../../../../../resource/ratp_stops_with_routes.csv"
.pipe importStream client, 'csv', 'stop'
.on 'finish', ->
this.iterator.should.eql 26621
client.stops.get '4035172', (err, stop) ->
return next err if err
stop.stop_name.should.eql 'REPUBLIQUE - DEFORGES'
stop.stop_desc.should.eql 'FACE 91 AVENUE DE LA REPUBLIQUE - 92020'
stop.stop_lat.should.eql '48.80383802353411'
stop.stop_lon.should.eql '2.2978373453843948'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS N63'
client.stops.get '1724', (err, stop) ->
return next err if err
stop.stop_name.should.eql 'Saint-Lazare'
stop.stop_desc.should.eql 'Saint-Lazare (97 rue) - 75108'
stop.stop_lat.should.eql '48.876067814352574'
stop.stop_lon.should.eql '2.324188100771013'
stop.line_type.should.eql 'M;M'
stop.line_name.should.eql 'M 13;M 13'
client.stops.get '3663555', (err, stop) ->
return next err if err
stop.stop_name.should.eql '8 MAI 1945'
stop.stop_desc.should.eql '7 RUE DES MARTYRS DE LA DEPORTATION - 93007'
stop.stop_lat.should.eql '48.94760765462246'
stop.stop_lon.should.eql '2.438002324652052'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS 148'
client.stops.get '4035339', (err, stop) ->
return next err if err
stop.stop_name.should.eql "PI:NAME:<NAME>END_PI D'OR"
stop.stop_desc.should.eql '20 BOULEVARD LOUIS LOUCHEUR - 92073'
stop.stop_lat.should.eql '48.860042582683505'
stop.stop_lon.should.eql '2.2133715937731506'
stop.line_type.should.eql 'BUS'
stop.line_name.should.eql 'BUS N53'
client.close()
next()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9990230202674866,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/events.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.
EventEmitter = ->
EventEmitter.init.call this
return
"use strict"
domain = undefined
util = require("util")
module.exports = EventEmitter
# Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter
EventEmitter.usingDomains = false
EventEmitter::domain = `undefined`
EventEmitter::_events = `undefined`
EventEmitter::_maxListeners = `undefined`
# By default EventEmitters will print a warning if more than 10 listeners are
# added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10
EventEmitter.init = ->
@domain = null
if EventEmitter.usingDomains
# if there is an active domain, then attach to it.
domain = domain or require("domain")
@domain = domain.active if domain.active and (this instanceof domain.Domain)
@_events = {} if not @_events or @_events is Object.getPrototypeOf(this)._events
@_maxListeners = @_maxListeners or `undefined`
return
# Obviously not all Emitters should be limited to 10. This function allows
# that to be increased. Set to zero for unlimited.
EventEmitter::setMaxListeners = setMaxListeners = (n) ->
throw TypeError("n must be a positive number") if not util.isNumber(n) or n < 0 or isNaN(n)
@_maxListeners = n
this
EventEmitter::getMaxListeners = getMaxListeners = ->
unless util.isUndefined(@_maxListeners)
@_maxListeners
else
EventEmitter.defaultMaxListeners
EventEmitter::emit = emit = (type) ->
er = undefined
handler = undefined
len = undefined
args = undefined
i = undefined
listeners = undefined
@_events = {} unless @_events
# If there is no 'error' event listener then throw.
if type is "error" and not @_events.error
er = arguments[1]
if @domain
er = new Error("Uncaught, unspecified \"error\" event.") unless er
er.domainEmitter = this
er.domain = @domain
er.domainThrown = false
@domain.emit "error", er
else if er instanceof Error
throw er # Unhandled 'error' event
else
throw Error("Uncaught, unspecified \"error\" event.")
return false
handler = @_events[type]
return false if util.isUndefined(handler)
@domain.enter() if @domain and this isnt process
if util.isFunction(handler)
switch arguments.length
# fast cases
when 1
handler.call this
when 2
handler.call this, arguments[1]
when 3
handler.call this, arguments[1], arguments[2]
# slower
else
len = arguments.length
args = new Array(len - 1)
i = 1
while i < len
args[i - 1] = arguments[i]
i++
handler.apply this, args
else if util.isObject(handler)
len = arguments.length
args = new Array(len - 1)
i = 1
while i < len
args[i - 1] = arguments[i]
i++
listeners = handler.slice()
len = listeners.length
i = 0
while i < len
listeners[i].apply this, args
i++
@domain.exit() if @domain and this isnt process
true
EventEmitter::addListener = addListener = (type, listener) ->
m = undefined
throw TypeError("listener must be a function") unless util.isFunction(listener)
@_events = {} unless @_events
# To avoid recursion in the case that type === "newListener"! Before
# adding it to the listeners, first emit "newListener".
@emit "newListener", type, (if util.isFunction(listener.listener) then listener.listener else listener) if @_events.newListener
unless @_events[type]
# Optimize the case of one listener. Don't need the extra array object.
@_events[type] = listener
else if util.isObject(@_events[type])
# If we've already got an array, just append.
@_events[type].push listener
# Adding the second element, need to change to array.
else
@_events[type] = [
@_events[type]
listener
]
# Check for listener leak
if util.isObject(@_events[type]) and not @_events[type].warned
m = @getMaxListeners()
if m and m > 0 and @_events[type].length > m
@_events[type].warned = true
console.error "(node) warning: possible EventEmitter memory " + "leak detected. %d %s listeners added. " + "Use emitter.setMaxListeners() to increase limit.", @_events[type].length, type
console.trace()
this
EventEmitter::on = EventEmitter::addListener
EventEmitter::once = once = (type, listener) ->
g = ->
@removeListener type, g
unless fired
fired = true
listener.apply this, arguments
return
throw TypeError("listener must be a function") unless util.isFunction(listener)
fired = false
g.listener = listener
@on type, g
this
# emits a 'removeListener' event iff the listener was removed
EventEmitter::removeListener = removeListener = (type, listener) ->
list = undefined
position = undefined
length = undefined
i = undefined
throw TypeError("listener must be a function") unless util.isFunction(listener)
return this if not @_events or not @_events[type]
list = @_events[type]
length = list.length
position = -1
if list is listener or (util.isFunction(list.listener) and list.listener is listener)
delete @_events[type]
@emit "removeListener", type, listener if @_events.removeListener
else if util.isObject(list)
i = length
while i-- > 0
if list[i] is listener or (list[i].listener and list[i].listener is listener)
position = i
break
return this if position < 0
if list.length is 1
list.length = 0
delete @_events[type]
else
list.splice position, 1
@emit "removeListener", type, listener if @_events.removeListener
this
EventEmitter::removeAllListeners = removeAllListeners = (type) ->
key = undefined
listeners = undefined
return this unless @_events
# not listening for removeListener, no need to emit
unless @_events.removeListener
if arguments.length is 0
@_events = {}
else delete @_events[type] if @_events[type]
return this
# emit removeListener for all listeners on all events
if arguments.length is 0
for key of @_events
continue if key is "removeListener"
@removeAllListeners key
@removeAllListeners "removeListener"
@_events = {}
return this
listeners = @_events[type]
if util.isFunction(listeners)
@removeListener type, listeners
# LIFO order
else @removeListener type, listeners[listeners.length - 1] while listeners.length if Array.isArray(listeners)
delete @_events[type]
this
EventEmitter::listeners = listeners = (type) ->
ret = undefined
if not @_events or not @_events[type]
ret = []
else if util.isFunction(@_events[type])
ret = [@_events[type]]
else
ret = @_events[type].slice()
ret
EventEmitter.listenerCount = (emitter, type) ->
ret = undefined
if not emitter._events or not emitter._events[type]
ret = 0
else if util.isFunction(emitter._events[type])
ret = 1
else
ret = emitter._events[type].length
ret
| 12297 | # 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.
EventEmitter = ->
EventEmitter.init.call this
return
"use strict"
domain = undefined
util = require("util")
module.exports = EventEmitter
# Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter
EventEmitter.usingDomains = false
EventEmitter::domain = `undefined`
EventEmitter::_events = `undefined`
EventEmitter::_maxListeners = `undefined`
# By default EventEmitters will print a warning if more than 10 listeners are
# added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10
EventEmitter.init = ->
@domain = null
if EventEmitter.usingDomains
# if there is an active domain, then attach to it.
domain = domain or require("domain")
@domain = domain.active if domain.active and (this instanceof domain.Domain)
@_events = {} if not @_events or @_events is Object.getPrototypeOf(this)._events
@_maxListeners = @_maxListeners or `undefined`
return
# Obviously not all Emitters should be limited to 10. This function allows
# that to be increased. Set to zero for unlimited.
EventEmitter::setMaxListeners = setMaxListeners = (n) ->
throw TypeError("n must be a positive number") if not util.isNumber(n) or n < 0 or isNaN(n)
@_maxListeners = n
this
EventEmitter::getMaxListeners = getMaxListeners = ->
unless util.isUndefined(@_maxListeners)
@_maxListeners
else
EventEmitter.defaultMaxListeners
EventEmitter::emit = emit = (type) ->
er = undefined
handler = undefined
len = undefined
args = undefined
i = undefined
listeners = undefined
@_events = {} unless @_events
# If there is no 'error' event listener then throw.
if type is "error" and not @_events.error
er = arguments[1]
if @domain
er = new Error("Uncaught, unspecified \"error\" event.") unless er
er.domainEmitter = this
er.domain = @domain
er.domainThrown = false
@domain.emit "error", er
else if er instanceof Error
throw er # Unhandled 'error' event
else
throw Error("Uncaught, unspecified \"error\" event.")
return false
handler = @_events[type]
return false if util.isUndefined(handler)
@domain.enter() if @domain and this isnt process
if util.isFunction(handler)
switch arguments.length
# fast cases
when 1
handler.call this
when 2
handler.call this, arguments[1]
when 3
handler.call this, arguments[1], arguments[2]
# slower
else
len = arguments.length
args = new Array(len - 1)
i = 1
while i < len
args[i - 1] = arguments[i]
i++
handler.apply this, args
else if util.isObject(handler)
len = arguments.length
args = new Array(len - 1)
i = 1
while i < len
args[i - 1] = arguments[i]
i++
listeners = handler.slice()
len = listeners.length
i = 0
while i < len
listeners[i].apply this, args
i++
@domain.exit() if @domain and this isnt process
true
EventEmitter::addListener = addListener = (type, listener) ->
m = undefined
throw TypeError("listener must be a function") unless util.isFunction(listener)
@_events = {} unless @_events
# To avoid recursion in the case that type === "newListener"! Before
# adding it to the listeners, first emit "newListener".
@emit "newListener", type, (if util.isFunction(listener.listener) then listener.listener else listener) if @_events.newListener
unless @_events[type]
# Optimize the case of one listener. Don't need the extra array object.
@_events[type] = listener
else if util.isObject(@_events[type])
# If we've already got an array, just append.
@_events[type].push listener
# Adding the second element, need to change to array.
else
@_events[type] = [
@_events[type]
listener
]
# Check for listener leak
if util.isObject(@_events[type]) and not @_events[type].warned
m = @getMaxListeners()
if m and m > 0 and @_events[type].length > m
@_events[type].warned = true
console.error "(node) warning: possible EventEmitter memory " + "leak detected. %d %s listeners added. " + "Use emitter.setMaxListeners() to increase limit.", @_events[type].length, type
console.trace()
this
EventEmitter::on = EventEmitter::addListener
EventEmitter::once = once = (type, listener) ->
g = ->
@removeListener type, g
unless fired
fired = true
listener.apply this, arguments
return
throw TypeError("listener must be a function") unless util.isFunction(listener)
fired = false
g.listener = listener
@on type, g
this
# emits a 'removeListener' event iff the listener was removed
EventEmitter::removeListener = removeListener = (type, listener) ->
list = undefined
position = undefined
length = undefined
i = undefined
throw TypeError("listener must be a function") unless util.isFunction(listener)
return this if not @_events or not @_events[type]
list = @_events[type]
length = list.length
position = -1
if list is listener or (util.isFunction(list.listener) and list.listener is listener)
delete @_events[type]
@emit "removeListener", type, listener if @_events.removeListener
else if util.isObject(list)
i = length
while i-- > 0
if list[i] is listener or (list[i].listener and list[i].listener is listener)
position = i
break
return this if position < 0
if list.length is 1
list.length = 0
delete @_events[type]
else
list.splice position, 1
@emit "removeListener", type, listener if @_events.removeListener
this
EventEmitter::removeAllListeners = removeAllListeners = (type) ->
key = undefined
listeners = undefined
return this unless @_events
# not listening for removeListener, no need to emit
unless @_events.removeListener
if arguments.length is 0
@_events = {}
else delete @_events[type] if @_events[type]
return this
# emit removeListener for all listeners on all events
if arguments.length is 0
for key of @_events
continue if key is "removeListener"
@removeAllListeners key
@removeAllListeners "removeListener"
@_events = {}
return this
listeners = @_events[type]
if util.isFunction(listeners)
@removeListener type, listeners
# LIFO order
else @removeListener type, listeners[listeners.length - 1] while listeners.length if Array.isArray(listeners)
delete @_events[type]
this
EventEmitter::listeners = listeners = (type) ->
ret = undefined
if not @_events or not @_events[type]
ret = []
else if util.isFunction(@_events[type])
ret = [@_events[type]]
else
ret = @_events[type].slice()
ret
EventEmitter.listenerCount = (emitter, type) ->
ret = undefined
if not emitter._events or not emitter._events[type]
ret = 0
else if util.isFunction(emitter._events[type])
ret = 1
else
ret = emitter._events[type].length
ret
| 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.
EventEmitter = ->
EventEmitter.init.call this
return
"use strict"
domain = undefined
util = require("util")
module.exports = EventEmitter
# Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter
EventEmitter.usingDomains = false
EventEmitter::domain = `undefined`
EventEmitter::_events = `undefined`
EventEmitter::_maxListeners = `undefined`
# By default EventEmitters will print a warning if more than 10 listeners are
# added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10
EventEmitter.init = ->
@domain = null
if EventEmitter.usingDomains
# if there is an active domain, then attach to it.
domain = domain or require("domain")
@domain = domain.active if domain.active and (this instanceof domain.Domain)
@_events = {} if not @_events or @_events is Object.getPrototypeOf(this)._events
@_maxListeners = @_maxListeners or `undefined`
return
# Obviously not all Emitters should be limited to 10. This function allows
# that to be increased. Set to zero for unlimited.
EventEmitter::setMaxListeners = setMaxListeners = (n) ->
throw TypeError("n must be a positive number") if not util.isNumber(n) or n < 0 or isNaN(n)
@_maxListeners = n
this
EventEmitter::getMaxListeners = getMaxListeners = ->
unless util.isUndefined(@_maxListeners)
@_maxListeners
else
EventEmitter.defaultMaxListeners
EventEmitter::emit = emit = (type) ->
er = undefined
handler = undefined
len = undefined
args = undefined
i = undefined
listeners = undefined
@_events = {} unless @_events
# If there is no 'error' event listener then throw.
if type is "error" and not @_events.error
er = arguments[1]
if @domain
er = new Error("Uncaught, unspecified \"error\" event.") unless er
er.domainEmitter = this
er.domain = @domain
er.domainThrown = false
@domain.emit "error", er
else if er instanceof Error
throw er # Unhandled 'error' event
else
throw Error("Uncaught, unspecified \"error\" event.")
return false
handler = @_events[type]
return false if util.isUndefined(handler)
@domain.enter() if @domain and this isnt process
if util.isFunction(handler)
switch arguments.length
# fast cases
when 1
handler.call this
when 2
handler.call this, arguments[1]
when 3
handler.call this, arguments[1], arguments[2]
# slower
else
len = arguments.length
args = new Array(len - 1)
i = 1
while i < len
args[i - 1] = arguments[i]
i++
handler.apply this, args
else if util.isObject(handler)
len = arguments.length
args = new Array(len - 1)
i = 1
while i < len
args[i - 1] = arguments[i]
i++
listeners = handler.slice()
len = listeners.length
i = 0
while i < len
listeners[i].apply this, args
i++
@domain.exit() if @domain and this isnt process
true
EventEmitter::addListener = addListener = (type, listener) ->
m = undefined
throw TypeError("listener must be a function") unless util.isFunction(listener)
@_events = {} unless @_events
# To avoid recursion in the case that type === "newListener"! Before
# adding it to the listeners, first emit "newListener".
@emit "newListener", type, (if util.isFunction(listener.listener) then listener.listener else listener) if @_events.newListener
unless @_events[type]
# Optimize the case of one listener. Don't need the extra array object.
@_events[type] = listener
else if util.isObject(@_events[type])
# If we've already got an array, just append.
@_events[type].push listener
# Adding the second element, need to change to array.
else
@_events[type] = [
@_events[type]
listener
]
# Check for listener leak
if util.isObject(@_events[type]) and not @_events[type].warned
m = @getMaxListeners()
if m and m > 0 and @_events[type].length > m
@_events[type].warned = true
console.error "(node) warning: possible EventEmitter memory " + "leak detected. %d %s listeners added. " + "Use emitter.setMaxListeners() to increase limit.", @_events[type].length, type
console.trace()
this
EventEmitter::on = EventEmitter::addListener
EventEmitter::once = once = (type, listener) ->
g = ->
@removeListener type, g
unless fired
fired = true
listener.apply this, arguments
return
throw TypeError("listener must be a function") unless util.isFunction(listener)
fired = false
g.listener = listener
@on type, g
this
# emits a 'removeListener' event iff the listener was removed
EventEmitter::removeListener = removeListener = (type, listener) ->
list = undefined
position = undefined
length = undefined
i = undefined
throw TypeError("listener must be a function") unless util.isFunction(listener)
return this if not @_events or not @_events[type]
list = @_events[type]
length = list.length
position = -1
if list is listener or (util.isFunction(list.listener) and list.listener is listener)
delete @_events[type]
@emit "removeListener", type, listener if @_events.removeListener
else if util.isObject(list)
i = length
while i-- > 0
if list[i] is listener or (list[i].listener and list[i].listener is listener)
position = i
break
return this if position < 0
if list.length is 1
list.length = 0
delete @_events[type]
else
list.splice position, 1
@emit "removeListener", type, listener if @_events.removeListener
this
EventEmitter::removeAllListeners = removeAllListeners = (type) ->
key = undefined
listeners = undefined
return this unless @_events
# not listening for removeListener, no need to emit
unless @_events.removeListener
if arguments.length is 0
@_events = {}
else delete @_events[type] if @_events[type]
return this
# emit removeListener for all listeners on all events
if arguments.length is 0
for key of @_events
continue if key is "removeListener"
@removeAllListeners key
@removeAllListeners "removeListener"
@_events = {}
return this
listeners = @_events[type]
if util.isFunction(listeners)
@removeListener type, listeners
# LIFO order
else @removeListener type, listeners[listeners.length - 1] while listeners.length if Array.isArray(listeners)
delete @_events[type]
this
EventEmitter::listeners = listeners = (type) ->
ret = undefined
if not @_events or not @_events[type]
ret = []
else if util.isFunction(@_events[type])
ret = [@_events[type]]
else
ret = @_events[type].slice()
ret
EventEmitter.listenerCount = (emitter, type) ->
ret = undefined
if not emitter._events or not emitter._events[type]
ret = 0
else if util.isFunction(emitter._events[type])
ret = 1
else
ret = emitter._events[type].length
ret
|
[
{
"context": " @descriptionValueStreams.switch()\n password: @passwordValueStreams.switch()\n isPrivate: @isPrivateStreams.switch()\n\n ",
"end": 2288,
"score": 0.7715869545936584,
"start": 2260,
"tag": "PASSWORD",
"value": "@passwordValueStreams.switch"
}
] | src/components/group_settings/index.coffee | FreeRoamApp/free-roam | 14 | z = require 'zorium'
_map = require 'lodash/map'
_defaults = require 'lodash/defaults'
RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject
RxReplaySubject = require('rxjs/ReplaySubject').ReplaySubject
RxObservable = require('rxjs/Observable').Observable
require 'rxjs/add/observable/of'
require 'rxjs/add/operator/map'
require 'rxjs/add/operator/switchMap'
require 'rxjs/add/operator/switch'
ActionBar = require '../action_bar'
Toggle = require '../toggle'
PrimaryInput = require '../primary_input'
PrimaryButton = require '../primary_button'
PrimaryTextarea = require '../primary_textarea'
Icon = require '../icon'
config = require '../../config'
colors = require '../../colors'
if window?
require './index.styl'
module.exports = class GroupSettings
constructor: ({@model, @router, group}) ->
@$actionBar = new ActionBar {@model}
me = @model.user.getMe()
@nameValueStreams = new RxReplaySubject 1
@nameValueStreams.next (group?.map (group) ->
group.name) or RxObservable.of null
@nameError = new RxBehaviorSubject null
@descriptionValueStreams = new RxReplaySubject 1
@descriptionValueStreams.next (group?.map (group) ->
group.description) or RxObservable.of null
@descriptionError = new RxBehaviorSubject null
@passwordValueStreams = new RxReplaySubject 1
@passwordValueStreams.next (group?.map (group) ->
group.password) or RxObservable.of null
@passwordError = new RxBehaviorSubject null
@isPrivateStreams = new RxReplaySubject 1
@isPrivateStreams.next (group?.map (group) ->
group.privacy is 'private') or RxObservable.of null
@$nameInput = new PrimaryInput
valueStreams: @nameValueStreams
error: @nameError
@$descriptionTextarea = new PrimaryTextarea
valueStreams: @descriptionValueStreams
error: @descriptionError
@$passwordInput = new PrimaryInput
valueStreams: @passwordValueStreams
error: @passwordError
@$isPrivateToggle = new Toggle {isSelectedStreams: @isPrivateStreams}
@state = z.state
me: me
group: group
isSaving: false
isLeaveGroupLoading: false
name: @nameValueStreams.switch()
description: @descriptionValueStreams.switch()
password: @passwordValueStreams.switch()
isPrivate: @isPrivateStreams.switch()
save: =>
{group, name, description, password,
isPrivate, isSaving} = @state.getValue()
if isSaving
return
@state.set isSaving: true
@passwordError.next null
@model.group.updateById group.id, {name, description, password, isPrivate}
.then =>
@state.set isSaving: false
@model.group.goPath group, 'groupChat', {@router}
render: =>
{me, group, isSaving, isPrivate} = @state.getValue()
items = []
hasAdminPermission = @model.groupUser.hasPermission {
meGroupUser: group?.meGroupUser, me, permissions: ['manageRole']
}
z '.z-group-settings',
z @$actionBar, {
isSaving: isSaving
cancel:
text: @model.l.get 'general.discard'
onclick: =>
@router.back()
save:
text: @model.l.get 'general.done'
onclick: @save
}
z '.g-grid',
z '.title', @model.l.get 'general.general'
if hasAdminPermission
[
z '.input',
z @$nameInput,
hintText: @model.l.get 'groupSettings.groupName'
z '.input',
z @$descriptionTextarea,
hintText: @model.l.get 'general.description'
if isPrivate
z '.input',
z @$passwordInput,
hintText: @model.l.get 'groupSettings.passwordToJoin'
]
z 'ul.list',
# if hasAdminPermission
# z 'li.item',
# z '.text', 'Private (password required)'
# z '.toggle',
# @$isPrivateToggle
_map items, ({$icon, icon, text, onclick}) ->
z 'li.item', {onclick},
z '.icon',
z $icon,
icon: icon
isTouchTarget: false
color: colors.$primaryMain
z '.text', text
| 202946 | z = require 'zorium'
_map = require 'lodash/map'
_defaults = require 'lodash/defaults'
RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject
RxReplaySubject = require('rxjs/ReplaySubject').ReplaySubject
RxObservable = require('rxjs/Observable').Observable
require 'rxjs/add/observable/of'
require 'rxjs/add/operator/map'
require 'rxjs/add/operator/switchMap'
require 'rxjs/add/operator/switch'
ActionBar = require '../action_bar'
Toggle = require '../toggle'
PrimaryInput = require '../primary_input'
PrimaryButton = require '../primary_button'
PrimaryTextarea = require '../primary_textarea'
Icon = require '../icon'
config = require '../../config'
colors = require '../../colors'
if window?
require './index.styl'
module.exports = class GroupSettings
constructor: ({@model, @router, group}) ->
@$actionBar = new ActionBar {@model}
me = @model.user.getMe()
@nameValueStreams = new RxReplaySubject 1
@nameValueStreams.next (group?.map (group) ->
group.name) or RxObservable.of null
@nameError = new RxBehaviorSubject null
@descriptionValueStreams = new RxReplaySubject 1
@descriptionValueStreams.next (group?.map (group) ->
group.description) or RxObservable.of null
@descriptionError = new RxBehaviorSubject null
@passwordValueStreams = new RxReplaySubject 1
@passwordValueStreams.next (group?.map (group) ->
group.password) or RxObservable.of null
@passwordError = new RxBehaviorSubject null
@isPrivateStreams = new RxReplaySubject 1
@isPrivateStreams.next (group?.map (group) ->
group.privacy is 'private') or RxObservable.of null
@$nameInput = new PrimaryInput
valueStreams: @nameValueStreams
error: @nameError
@$descriptionTextarea = new PrimaryTextarea
valueStreams: @descriptionValueStreams
error: @descriptionError
@$passwordInput = new PrimaryInput
valueStreams: @passwordValueStreams
error: @passwordError
@$isPrivateToggle = new Toggle {isSelectedStreams: @isPrivateStreams}
@state = z.state
me: me
group: group
isSaving: false
isLeaveGroupLoading: false
name: @nameValueStreams.switch()
description: @descriptionValueStreams.switch()
password: <PASSWORD>()
isPrivate: @isPrivateStreams.switch()
save: =>
{group, name, description, password,
isPrivate, isSaving} = @state.getValue()
if isSaving
return
@state.set isSaving: true
@passwordError.next null
@model.group.updateById group.id, {name, description, password, isPrivate}
.then =>
@state.set isSaving: false
@model.group.goPath group, 'groupChat', {@router}
render: =>
{me, group, isSaving, isPrivate} = @state.getValue()
items = []
hasAdminPermission = @model.groupUser.hasPermission {
meGroupUser: group?.meGroupUser, me, permissions: ['manageRole']
}
z '.z-group-settings',
z @$actionBar, {
isSaving: isSaving
cancel:
text: @model.l.get 'general.discard'
onclick: =>
@router.back()
save:
text: @model.l.get 'general.done'
onclick: @save
}
z '.g-grid',
z '.title', @model.l.get 'general.general'
if hasAdminPermission
[
z '.input',
z @$nameInput,
hintText: @model.l.get 'groupSettings.groupName'
z '.input',
z @$descriptionTextarea,
hintText: @model.l.get 'general.description'
if isPrivate
z '.input',
z @$passwordInput,
hintText: @model.l.get 'groupSettings.passwordToJoin'
]
z 'ul.list',
# if hasAdminPermission
# z 'li.item',
# z '.text', 'Private (password required)'
# z '.toggle',
# @$isPrivateToggle
_map items, ({$icon, icon, text, onclick}) ->
z 'li.item', {onclick},
z '.icon',
z $icon,
icon: icon
isTouchTarget: false
color: colors.$primaryMain
z '.text', text
| true | z = require 'zorium'
_map = require 'lodash/map'
_defaults = require 'lodash/defaults'
RxBehaviorSubject = require('rxjs/BehaviorSubject').BehaviorSubject
RxReplaySubject = require('rxjs/ReplaySubject').ReplaySubject
RxObservable = require('rxjs/Observable').Observable
require 'rxjs/add/observable/of'
require 'rxjs/add/operator/map'
require 'rxjs/add/operator/switchMap'
require 'rxjs/add/operator/switch'
ActionBar = require '../action_bar'
Toggle = require '../toggle'
PrimaryInput = require '../primary_input'
PrimaryButton = require '../primary_button'
PrimaryTextarea = require '../primary_textarea'
Icon = require '../icon'
config = require '../../config'
colors = require '../../colors'
if window?
require './index.styl'
module.exports = class GroupSettings
constructor: ({@model, @router, group}) ->
@$actionBar = new ActionBar {@model}
me = @model.user.getMe()
@nameValueStreams = new RxReplaySubject 1
@nameValueStreams.next (group?.map (group) ->
group.name) or RxObservable.of null
@nameError = new RxBehaviorSubject null
@descriptionValueStreams = new RxReplaySubject 1
@descriptionValueStreams.next (group?.map (group) ->
group.description) or RxObservable.of null
@descriptionError = new RxBehaviorSubject null
@passwordValueStreams = new RxReplaySubject 1
@passwordValueStreams.next (group?.map (group) ->
group.password) or RxObservable.of null
@passwordError = new RxBehaviorSubject null
@isPrivateStreams = new RxReplaySubject 1
@isPrivateStreams.next (group?.map (group) ->
group.privacy is 'private') or RxObservable.of null
@$nameInput = new PrimaryInput
valueStreams: @nameValueStreams
error: @nameError
@$descriptionTextarea = new PrimaryTextarea
valueStreams: @descriptionValueStreams
error: @descriptionError
@$passwordInput = new PrimaryInput
valueStreams: @passwordValueStreams
error: @passwordError
@$isPrivateToggle = new Toggle {isSelectedStreams: @isPrivateStreams}
@state = z.state
me: me
group: group
isSaving: false
isLeaveGroupLoading: false
name: @nameValueStreams.switch()
description: @descriptionValueStreams.switch()
password: PI:PASSWORD:<PASSWORD>END_PI()
isPrivate: @isPrivateStreams.switch()
save: =>
{group, name, description, password,
isPrivate, isSaving} = @state.getValue()
if isSaving
return
@state.set isSaving: true
@passwordError.next null
@model.group.updateById group.id, {name, description, password, isPrivate}
.then =>
@state.set isSaving: false
@model.group.goPath group, 'groupChat', {@router}
render: =>
{me, group, isSaving, isPrivate} = @state.getValue()
items = []
hasAdminPermission = @model.groupUser.hasPermission {
meGroupUser: group?.meGroupUser, me, permissions: ['manageRole']
}
z '.z-group-settings',
z @$actionBar, {
isSaving: isSaving
cancel:
text: @model.l.get 'general.discard'
onclick: =>
@router.back()
save:
text: @model.l.get 'general.done'
onclick: @save
}
z '.g-grid',
z '.title', @model.l.get 'general.general'
if hasAdminPermission
[
z '.input',
z @$nameInput,
hintText: @model.l.get 'groupSettings.groupName'
z '.input',
z @$descriptionTextarea,
hintText: @model.l.get 'general.description'
if isPrivate
z '.input',
z @$passwordInput,
hintText: @model.l.get 'groupSettings.passwordToJoin'
]
z 'ul.list',
# if hasAdminPermission
# z 'li.item',
# z '.text', 'Private (password required)'
# z '.toggle',
# @$isPrivateToggle
_map items, ({$icon, icon, text, onclick}) ->
z 'li.item', {onclick},
z '.icon',
z $icon,
icon: icon
isTouchTarget: false
color: colors.$primaryMain
z '.text', text
|
[
{
"context": "Accounts.ui.config\n passwordSignupFields: \"USERNAME_ONLY\"\n\nSession.set \"momentDateFormat\", \"MM/DD/YYYY\"\nSe",
"end": 59,
"score": 0.923882782459259,
"start": 46,
"tag": "PASSWORD",
"value": "USERNAME_ONLY"
}
] | client/helpers/config.coffee | drobbins/kassebaum | 0 | Accounts.ui.config
passwordSignupFields: "USERNAME_ONLY"
Session.set "momentDateFormat", "MM/DD/YYYY"
Session.set "datepickerDateFormat", "mm/dd/yyyy"
Session.set "momentLogDateFormat", "MM/DD/YYYY h:mm:ss a" | 67974 | Accounts.ui.config
passwordSignupFields: "<PASSWORD>"
Session.set "momentDateFormat", "MM/DD/YYYY"
Session.set "datepickerDateFormat", "mm/dd/yyyy"
Session.set "momentLogDateFormat", "MM/DD/YYYY h:mm:ss a" | true | Accounts.ui.config
passwordSignupFields: "PI:PASSWORD:<PASSWORD>END_PI"
Session.set "momentDateFormat", "MM/DD/YYYY"
Session.set "datepickerDateFormat", "mm/dd/yyyy"
Session.set "momentLogDateFormat", "MM/DD/YYYY h:mm:ss a" |
[
{
"context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nhQEMA+bZw3a+syp5AQgAqqimwGjRe/m9d74f2Itu4rAs/BJUjgPprCSn1JTOBurK\nnneix4XLQM9slGNJANiOhjEmGR011+Dhk4PV2SNaJrgXI0RS43O3UAjI4gHUHpKF\nlHit1/UBwK24dTzl8G8LSBoI9g1p3QZTZqszsrsYOZfzpoObE1If0IlYvP6VTURC\nQUsHoOKaWXbVQFaUqW8tYqpCgiBZ3BLQbzdO8Wy20R3qRr/zEltvK62o4fitW1j/\nt8vjzKXHxKCcE+Rqwdn+qb1/KLf+AOrqGJL8gDXytVeQlxMmiV3J/GDgaq/Ikjzk\nwhot7+b4kLwypxB8/fqNO2alFICwnXtlUMeqwtJFT9LqATfV9f85EEfr3Q4ejsB9\n1eMHkubjSbj/SMIw+HlA/dYo4SFVxbej1ur3eY+VQFNA43IqSSsTKp2o9ZEvyXOt\nzOHZSscVSPg1h7huqi9LWgAYUzPTqQHYkzRs7ckJ/jb+LBKesX4n6yUhuO0XZzNi\nEC1qNueJjkNOy0T+NCSuTdMYq3P8De0hBu/5HnrUwgsujgWrrUMmSaTmCezyUkSo\n4tBaPu8PtWaC97TPYefTCu5eI5L28NAAlrGVxtxkdWJs2IJZqGDR0O6X+xzxkFsH\njc1chiypfpEa4XsuvqfAkdU0I036ebwo+65lQwiVnbf0+XKxup3QspI9lmlMoKL3\nA6Th+sqaLEv4GOca1YyI40on6ESg24TaC4WQK+SIVTuYqNdWvhb2lCcdK/WdzkIw\nJwiv2OGfAh5S8yg8c6r1k/WoWv1/hK6wj+MhBX7QSAtkde5BYX3P0ZpAUYXIBqZz\nTscMwNiHdgS1FcQGk105wbfztfpBLAkIlVD3PmHxE8rIhvAcS+1GFn+TYSwbZE3M\nkYyFvOKHjwnQEdQCSQuPc4YgfWChFYBtE6TNvp/e4rhcIf+7U6uRKLkXSS80jzDM\n9sRp11/CxDXx4nZPF9zXd9sKBLXcsEs0QTpxwAzU0GCj9jc8AOZTQXFolzal40S9\nC4HoctsmAb2ybX9+4E0SvcBGoMpmWDdXH3KB4MfJoSFLP2ErdGGuIIlDf94oqprv\nsNOCls/STmI9L3RR1/g9AuwIElm0HKa3YIzJHE8hgMjsOAvDM1VQqRBLoYbKI74w\nbLwXTajt2kN4gdJgHHZ0dZjZQZlf5D7DukY7qdghOOOOxrbPgrN1Qy8QLvdDcio7\nlRe/HZUJkihmw4YfMaYfR5c0tVjfPVB/le14iz5E8gLFbWq0tANgEX5h8ylUepu/\nN8eJSajVl+ybJtl+YmijM2viR03BJjnyWQLcTk+ZXqH30ti7cGFqtBrnLuIIn8sV\nm1U9CgicfSMzg/ASflw6U6Zb290uheY1rFte1ZfrKoIBjGIV07s243VDR1I464zj\n6xqr6dX7IuC0iP4BcdLEAUe2r99s5dVcuccHrgq7Me7tTYWSyxEbGfw2N1H00kGb\nuOftACanYOkJT6j1m3k1c7XohZsOL43JK3yOkprGZczHRwrrQrbdHHXB27PhVq8e\nYyjPQTmufZtWXgkdv1Q4f/oJks7NK9RATBfD/7qgOYpWNDDkmFX9qK23HA4shJu+\nYnS6s8MBxyb+3HSkqL2z1Vv5JjEDpeuVFtUsJ4dr3BO0MzrqHVPRDJsjiIPqyb2A\nbXX1zefINu0l1zgnDW0lggN/Fxqyrw7654yQGR1uRyEAVMO3QeoWaBSMIf39XiRN\nYcDJo56SFcZQovBMuz6YzddJNal5/BFAdWhkEbwzkqJa3QEjm69YwQem9+ZB2n4I\nRsLjWln6APXtNeTi4YAXgcb7KifnLSvprwGcna+H0b4UJVfs3IXYjvi1bggTGTj+\n1rWAX2+f+fis8i40nH+zHQznZKtwZ/s7qb0KlwNui3moXSOd3YVSNwgmDMAPlPun\nB5A13/wvLDwXP7j3gUZ2MJcm3x6VrX1LTcCRu/AqJFLyKHqovCeYSdGRotFRNDzv\nNHw3ZbXgcyHyOtSoepHh+idb+F02oIDRkjQwezPRAiZk/vFbjAXGCcYQ9UBmScLM\nQJlOr7Ua+tqT2rKmb1PwJYQz39SnUDdUD2+7VckUH/ioCL16k2x0XaK9KfSIpmzh\nQwe+4+nd17Jpj5jFfg2mYr5ccDIEugfCcplExI/VcgS+drlFSMgP871rzeJyIpCy\nmqG0bSbMM3VJ307AWDqoiP2hSW5wZ9YweVeFh1DdH2I2Xwt5xYkQDx27M/H9LO1A\nWYxrooYFv+qVvVMS\n=euQN\n-----END PGP MESSAGE-----\"\"\",\n \"\"\"-----BEGIN PGP",
"end": 2902,
"score": 0.9989599585533142,
"start": 605,
"tag": "KEY",
"value": "hQEMA+bZw3a+syp5AQgAqqimwGjRe/m9d74f2Itu4rAs/BJUjgPprCSn1JTOBurK\nnneix4XLQM9slGNJANiOhjEmGR011+Dhk4PV2SNaJrgXI0RS43O3UAjI4gHUHpKF\nlHit1/UBwK24dTzl8G8LSBoI9g1p3QZTZqszsrsYOZfzpoObE1If0IlYvP6VTURC\nQUsHoOKaWXbVQFaUqW8tYqpCgiBZ3BLQbzdO8Wy20R3qRr/zEltvK62o4fitW1j/\nt8vjzKXHxKCcE+Rqwdn+qb1/KLf+AOrqGJL8gDXytVeQlxMmiV3J/GDgaq/Ikjzk\nwhot7+b4kLwypxB8/fqNO2alFICwnXtlUMeqwtJFT9LqATfV9f85EEfr3Q4ejsB9\n1eMHkubjSbj/SMIw+HlA/dYo4SFVxbej1ur3eY+VQFNA43IqSSsTKp2o9ZEvyXOt\nzOHZSscVSPg1h7huqi9LWgAYUzPTqQHYkzRs7ckJ/jb+LBKesX4n6yUhuO0XZzNi\nEC1qNueJjkNOy0T+NCSuTdMYq3P8De0hBu/5HnrUwgsujgWrrUMmSaTmCezyUkSo\n4tBaPu8PtWaC97TPYefTCu5eI5L28NAAlrGVxtxkdWJs2IJZqGDR0O6X+xzxkFsH\njc1chiypfpEa4XsuvqfAkdU0I036ebwo+65lQwiVnbf0+XKxup3QspI9lmlMoKL3\nA6Th+sqaLEv4GOca1YyI40on6ESg24TaC4WQK+SIVTuYqNdWvhb2lCcdK/WdzkIw\nJwiv2OGfAh5S8yg8c6r1k/WoWv1/hK6wj+MhBX7QSAtkde5BYX3P0ZpAUYXIBqZz\nTscMwNiHdgS1FcQGk105wbfztfpBLAkIlVD3PmHxE8rIhvAcS+1GFn+TYSwbZE3M\nkYyFvOKHjwnQEdQCSQuPc4YgfWChFYBtE6TNvp/e4rhcIf+7U6uRKLkXSS80jzDM\n9sRp11/CxDXx4nZPF9zXd9sKBLXcsEs0QTpxwAzU0GCj9jc8AOZTQXFolzal40S9\nC4HoctsmAb2ybX9+4E0SvcBGoMpmWDdXH3KB4MfJoSFLP2ErdGGuIIlDf94oqprv\nsNOCls/STmI9L3RR1/g9AuwIElm0HKa3YIzJHE8hgMjsOAvDM1VQqRBLoYbKI74w\nbLwXTajt2kN4gdJgHHZ0dZjZQZlf5D7DukY7qdghOOOOxrbPgrN1Qy8QLvdDcio7\nlRe/HZUJkihmw4YfMaYfR5c0tVjfPVB/le14iz5E8gLFbWq0tANgEX5h8ylUepu/\nN8eJSajVl+ybJtl+YmijM2viR03BJjnyWQLcTk+ZXqH30ti7cGFqtBrnLuIIn8sV\nm1U9CgicfSMzg/ASflw6U6Zb290uheY1rFte1ZfrKoIBjGIV07s243VDR1I464zj\n6xqr6dX7IuC0iP4BcdLEAUe2r99s5dVcuccHrgq7Me7tTYWSyxEbGfw2N1H00kGb\nuOftACanYOkJT6j1m3k1c7XohZsOL43JK3yOkprGZczHRwrrQrbdHHXB27PhVq8e\nYyjPQTmufZtWXgkdv1Q4f/oJks7NK9RATBfD/7qgOYpWNDDkmFX9qK23HA4shJu+\nYnS6s8MBxyb+3HSkqL2z1Vv5JjEDpeuVFtUsJ4dr3BO0MzrqHVPRDJsjiIPqyb2A\nbXX1zefINu0l1zgnDW0lggN/Fxqyrw7654yQGR1uRyEAVMO3QeoWaBSMIf39XiRN\nYcDJo56SFcZQovBMuz6YzddJNal5/BFAdWhkEbwzkqJa3QEjm69YwQem9+ZB2n4I\nRsLjWln6APXtNeTi4YAXgcb7KifnLSvprwGcna+H0b4UJVfs3IXYjvi1bggTGTj+\n1rWAX2+f+fis8i40nH+zHQznZKtwZ/s7qb0KlwNui3moXSOd3YVSNwgmDMAPlPun\nB5A13/wvLDwXP7j3gUZ2MJcm3x6VrX1LTcCRu/AqJFLyKHqovCeYSdGRotFRNDzv\nNHw3ZbXgcyHyOtSoepHh+idb+F02oIDRkjQwezPRAiZk/vFbjAXGCcYQ9UBmScLM\nQJlOr7Ua+tqT2rKmb1PwJYQz39SnUDdUD2+7VckUH/ioCL16k2x0XaK9KfSIpmzh\nQwe+4+nd17Jpj5jFfg2mYr5ccDIEugfCcplExI/VcgS+drlFSMgP871rzeJyIpCy\nmqG0bSbMM3VJ307AWDqoiP2hSW5wZ9YweVeFh1DdH2I2Xwt5xYkQDx27M/H9LO1A\nWYxrooYFv+qVvVMS\n=euQN"
},
{
"context": "(Darwin)\nComment: GPGTools - http://gpgtools.org\n\nhQEMA+bZw3a+syp5AQf6ArI5PQg+kzq4h7T4nZA9q/Li4kjf7eN2C4m1XuBm/B08\n245kUmI5iOkfFe9HbT3azrvdNYe9VzFweoKKJkWbYLRQsw8BN4lGlixpETDle4cz\nbd94yIbs//Xe+505h7jU+RY+cAqamaSPTpZG901dIB5XJwdP8qM2mYacCeBXIWmE\nBMUYUT9MtYZFESstbMHI/pKUiJRhhBpJLO0FP5KdGyuO9JOQZui0cagnxUynqVTU\n+/DOMNf3nQeXBM4lyZQx3pFcXzNwL6URXz/yRa25CxDP4bpVcrZ5qSiJqZ+jpSRs\nF8WKEkGCftzwsWIxsUPcs+6ClBruLbSKSroP4+ci/dLBDgHoMF+R6Efj5sU8tWlE\n1Z3KQjB2ENqu7XIKf49cpnY06K3QKWppexflWT5UbHzOwn5O9Ih1NPL3PbFqQV+/\nyJDO2qjxvq6PXOOwRbxvasYzpYXoLO5soyoEbmQ/VwTZL8Pw0Gima1s1GejTHcvv\nZ3BvqyuiJGAnYq5ShI+SlDVI2uRwJ6nThQtGdIjaQZo3ilSPuFE8sWSO03IKKxQy\nZyNwKj0miHaIOqevu88588zwsAKAxUw7gYd0GWSN9G6MHf6P1P7dZyd92dPnBJu0\nL8AFMrYN1HcLuLG12BeONPUty4ZGUwjnFn9wu83RRKZ0d+yjVzhoAv7VbQxKBE/p\neQntRg76DYwOmTBV+ZGsO+rezxQ/1sEMRq0bvJIybpDLFUwg3QmGc4ZGJyBQ/FKA\nV7xwSJBg5wSzZ9pSo4HQFi6pF/UPTc9xbbKQDIEnZlYdaIiTS0J/Xx321f5Paicw\nwa/vt7tlsS8evxmVvhgMWZ0tc8B82ZM8o1AHLewmty2PFPuGVMG9W3DJJSBH+fRC\n7jB2iHwfhUQ5ntFkxMcmVY1IYK2WtHQ4nzYdvhiSp9MTuBqXfy1RzWq6LAbUUGfU\no7cJyIX4q4MjzvkYEjxxnw==\n=S4AK\n-----END PG",
"end": 4014,
"score": 0.9928148984909058,
"start": 3047,
"tag": "KEY",
"value": "hQEMA+bZw3a+syp5AQf6ArI5PQg+kzq4h7T4nZA9q/Li4kjf7eN2C4m1XuBm/B08\n245kUmI5iOkfFe9HbT3azrvdNYe9VzFweoKKJkWbYLRQsw8BN4lGlixpETDle4cz\nbd94yIbs//Xe+505h7jU+RY+cAqamaSPTpZG901dIB5XJwdP8qM2mYacCeBXIWmE\nBMUYUT9MtYZFESstbMHI/pKUiJRhhBpJLO0FP5KdGyuO9JOQZui0cagnxUynqVTU\n+/DOMNf3nQeXBM4lyZQx3pFcXzNwL6URXz/yRa25CxDP4bpVcrZ5qSiJqZ+jpSRs\nF8WKEkGCftzwsWIxsUPcs+6ClBruLbSKSroP4+ci/dLBDgHoMF+R6Efj5sU8tWlE\n1Z3KQjB2ENqu7XIKf49cpnY06K3QKWppexflWT5UbHzOwn5O9Ih1NPL3PbFqQV+/\nyJDO2qjxvq6PXOOwRbxvasYzpYXoLO5soyoEbmQ/VwTZL8Pw0Gima1s1GejTHcvv\nZ3BvqyuiJGAnYq5ShI+SlDVI2uRwJ6nThQtGdIjaQZo3ilSPuFE8sWSO03IKKxQy\nZyNwKj0miHaIOqevu88588zwsAKAxUw7gYd0GWSN9G6MHf6P1P7dZyd92dPnBJu0\nL8AFMrYN1HcLuLG12BeONPUty4ZGUwjnFn9wu83RRKZ0d+yjVzhoAv7VbQxKBE/p\neQntRg76DYwOmTBV+ZGsO+rezxQ/1sEMRq0bvJIybpDLFUwg3QmGc4ZGJyBQ/FKA\nV7xwSJBg5wSzZ9pSo4HQFi6pF/UPTc9xbbKQDIEnZlYdaIiTS0J/Xx321f5Paicw\nwa/vt7tlsS8evxmVvhgMWZ0tc8B82ZM8o1AHLewmty2PFPuGVMG9W3DJJSBH+fRC\n7jB2iHwfhUQ5ntFkxMcmVY1IYK2WtHQ4nzYdvhiSp9MTuBqXfy1RzWq6L"
},
{
"context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nowGbwMvMwMSo/0DG1dnjliXj6ZdJDEFZhebVXAoKSnmJualKVgowoJSdVJBeoKQD\nkkpJLU4uyiwoyczPA6lQ8k6tTEosTlUvVghwD1DwzC3ISc1NzStJBCsA68hOrSzP\nL0ophhoYrZRcVFlQkq+ko6AENhWsAmSGkkIsWENiaUlGfhHcfiXfxIry1JwcBe+i\n/AyomWWpRcVQF4CVGOgZ6BlCpHIyk1PzilPh1oE8BBQuqSxIRTLSMwSsGsgsLcpB\neFVJCShYC3FGbmJmnpICQkpPPyczSR8kqpdVDA2MzKLU5JL8okygdQpApVC7gOpA\nGsE0yDyw2oz83NSCxHSYI5QySkoKrPT10zNLMkqT9JLzc/WhwaCPFNpJpenFyBEB\n0lSMR5d+ZnFxaSrUdUWpBfnFmUDnVYKNQA0IJaARqEFw4B5IDI/heiAtcP+kpBak\n5qWk5iWDPQ/3e0Ep0NrE5GxwANjZGiJrKHPBriepKL+8OLUoM60SrEsL5q7k/Jz8\nomJUMWDspuiWpBaXQC0Axbw5TLIEmDJzUotTk8GSMMcjRKHKkvJQ5JPyUAxPzk9L\nS03VhSRzVMvzgek+N7MYTTQlNbVAN7WwNDEH3anFGF4C25BaVARM3wj3m8Fkq4Ap\nRhcjNEAhyFXL1ckkw8LAyMTAxsoEyqgMXJwCsNzLsIf/v8vd8sUme3UElO58Zrko\nlcM7/0fuk6KiE15KcfZr7Sau0+44GZAguGBXYFeH/Q5lwcXFfzb9PnFF10l5V1LX\nPnZVni9PZ/74785esCHmTmGTcerPta9fnSnTtDad+HlDe379gx2ONu/9Poaavn0S\n9TBA5WT869nvTx2JXJrqb11X3loi+eKkUq5eJj/3A8Ng27gkCb6WFUo9firKEXvy\ntA6d4Sr+Hjz1qJDjyi2Or+te337+onL+2puytjwr9uebnZx+bl/jrIe3xbYo/Vz8\nMKht7nndOYc8St/t3bLghWHn/tz4cz2GUR6LV+/d++7MdeXjWldb+59xVb2azVMb\n4MrV23v89ZpY5ZMLzDe+s9J5uXvn0hl3jE1yVO2yrgXOK88RTsi2/r02Y7/PfIa1\nuxXme4gyeVUEZ2/tfzP3bFRKhYRSzytdLeMyswvXbuw23t8vZ5Cd1fgptEEqTz1u\nbZjQoZViEVEa986Vv98wiW+eQsikYoNXl/Qt9oRHTvkxOaE+a6FxoHjr7YJz1iEP\n7n719BOuS+nkkeqPPT93AQvvwxK7PydyUi4YdO4XkExRZPY8uznL10ilmOfaXfcm\nZubtJlEMmxiKY7nanMukz9XoaGyU0vUKyfdSlKlatkmLpeMF38Sdq6zumce8n77Z\n+2alsv4GBtmYKYsloiQbrW/a2dwQn2TzWlzkmOXLOuOzDVUiy",
"end": 5564,
"score": 0.9973530769348145,
"start": 4200,
"tag": "KEY",
"value": "owGbwMvMwMSo/0DG1dnjliXj6ZdJDEFZhebVXAoKSnmJualKVgowoJSdVJBeoKQD\nkkpJLU4uyiwoyczPA6lQ8k6tTEosTlUvVghwD1DwzC3ISc1NzStJBCsA68hOrSzP\nL0ophhoYrZRcVFlQkq+ko6AENhWsAmSGkkIsWENiaUlGfhHcfiXfxIry1JwcBe+i\n/AyomWWpRcVQF4CVGOgZ6BlCpHIyk1PzilPh1oE8BBQuqSxIRTLSMwSsGsgsLcpB\neFVJCShYC3FGbmJmnpICQkpPPyczSR8kqpdVDA2MzKLU5JL8okygdQpApVC7gOpA\nGsE0yDyw2oz83NSCxHSYI5QySkoKrPT10zNLMkqT9JLzc/WhwaCPFNpJpenFyBEB\n0lSMR5d+ZnFxaSrUdUWpBfnFmUDnVYKNQA0IJaARqEFw4B5IDI/heiAtcP+kpBak\n5qWk5iWDPQ/3e0Ep0NrE5GxwANjZGiJrKHPBriepKL+8OLUoM60SrEsL5q7k/Jz8\nomJUMWDspuiWpBaXQC0Axbw5TLIEmDJzUotTk8GSMMcjRKHKkvJQ5JPyUAxPzk9L\nS03VhSRzVMvzgek+N7MYTTQlNbVAN7WwNDEH3anFGF4C25BaVARM3wj3m8Fkq4Ap\nRhcjNEAhyFXL1ckkw8LAyMTAxsoEyqgMXJwCsNzLsIf/v8vd8sUme3UElO58Zrko\nlcM7/0fuk6KiE15KcfZr7Sau0+44GZAguGBXYFeH/Q5lwcXFfzb9PnFF10l5V1LX\nPnZVni9PZ/74785esCHmTmGTcerPta9fnSnTtDad+HlDe379gx2ONu/9Poaavn0S\n9TBA5WT869nvTx2JXJrqb11X3loi+eKkUq5eJj/3A8Ng27gkCb6WFUo9firKEXvy\ntA6d4Sr+Hjz1qJDjyi2Or+te337+onL+2puytjwr9uebnZx+bl/jrIe3xbYo/Vz8\nMKht7nndOYc8St/t3bLghWHn/tz4cz2GUR6LV+/d++7MdeXjWldb+59xVb2azVMb\n4MrV23v89ZpY5ZMLzDe+s9J5uXvn0hl3jE1yVO2yrgXOK88RTsi2/r02Y7/PfIa1\nuxXme4gyeVUEZ2/tfzP3bFRKhYRSzytdLeMyswvXbuw23t8vZ5Cd1fgptEEqTz1u\nbZjQoZViEVEa986Vv98wiW+eQsikYoNXl/Qt9oRHTvkxOaE+a6FxoHjr7YJz1iEP\n7n719BOuS+nkkeqPPT93AQvvwxK7PydyUi4YdO4XkExRZPY8uznL10ilmOfaXfcm\nZubtJlEMmxiKY7nanMukz9XoaGyU0vUKyfdSlKlatkmLpeMF38Sdq6zumce8n77Z"
},
{
"context": "anMukz9XoaGyU0vUKyfdSlKlatkmLpeMF38Sdq6zumce8n77Z\n+2alsv4GBtmYKYsloiQbrW/a2dwQn2TzWlzkmOXLOuOzDVUiyx3T86q6DQA=\n=kOKo\n-----END PGP MESSAGE-----\"\"\",\n \"\"\"-----BEG",
"end": 5625,
"score": 0.9634312391281128,
"start": 5566,
"tag": "KEY",
"value": "2alsv4GBtmYKYsloiQbrW/a2dwQn2TzWlzkmOXLOuOzDVUiyx3T86q6DQA="
},
{
"context": "(Darwin)\nComment: GPGTools - https://gpgtools.org\nhQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr\nU3fm/0/SxTdTJRaZsAjbVLH4jYg6cXyNIxdE5uw2ywxQ9Zi8iWylDixsPT5bD6Q7\nxlFLhr4BTt7P/oTUMANybuFU6ntss8jbzKZ7SdHbylLrkaUylSWqH1d7bffMxCAl\nJOOAHBOXowpcswAurwQpaDZGX3rGUXjAcMDS5ykr/tgHIwo25A+WbIdNCYMkYm0d\nBT83PUMIZm351LJWIv/tBqraNc9kEyftAMbVlh5xC0EfPt+ipyRJDh5XKTvh0xQW\nT6nM9Z0qLVwUhaG9RqRM1H6D083IE9fKF6sFdce7MtI/ARo3wPa7qll1hyY5vfaT\nbaAzKLJPcPDf1vu2+S1c1kt5ljvao8MCCebgK7E8CPT/ajLr1xU05G7Eg0zrkstk\n=ni0M\n-----END PGP MESSAGE-----\"\"\" ],\n keys : {\n de",
"end": 6236,
"score": 0.9981959462165833,
"start": 5776,
"tag": "KEY",
"value": "hQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr\nU3fm/0/SxTdTJRaZsAjbVLH4jYg6cXyNIxdE5uw2ywxQ9Zi8iWylDixsPT5bD6Q7\nxlFLhr4BTt7P/oTUMANybuFU6ntss8jbzKZ7SdHbylLrkaUylSWqH1d7bffMxCAl\nJOOAHBOXowpcswAurwQpaDZGX3rGUXjAcMDS5ykr/tgHIwo25A+WbIdNCYMkYm0d\nBT83PUMIZm351LJWIv/tBqraNc9kEyftAMbVlh5xC0EfPt+ipyRJDh5XKTvh0xQW\nT6nM9Z0qLVwUhaG9RqRM1H6D083IE9fKF6sFdce7MtI/ARo3wPa7qll1hyY5vfaT\nbaAzKLJPcPDf1vu2+S1c1kt5ljvao8MCCebgK7E8CPT/ajLr1xU05G7Eg0zrkstk\n=ni0M"
},
{
"context": "\n keys : {\n decryption: {\n passphrase : \"catsdogs\",\n key : \"\"\"-----BEGIN PGP PRIVATE KEY BLOCK",
"end": 6326,
"score": 0.9989979863166809,
"start": 6318,
"tag": "PASSWORD",
"value": "catsdogs"
},
{
"context": "t: GPGTools - http://gpgtools.org\n\nlQO+BFJVxK0BCAC5JHmJ2MoDDUwzXWwnECMFbGF/6mGospOgLuQwGCjg0SMBRZ8j\nSbtucJNZIKzCvk6se6wy+i1DH2+KzMSKDyINKgVjjA1rIpcvoFuDt1qBvDFNbQBZ\nEiGSdnIYUn7cAJat+0SLIBmn6y7Mtz2ANt89/qwYV8dvMWyTcnR/FU9QhptaSF5Y\nTyO8j54mwkoJqi47dm0L164u30uImObsJpRPxww/fwyxfbhFt3ptYIUhgxJjn3Ha\nRIlVww/Z7Z7hROVdaPXDwTVjYrk406WtvFEewhigSP4ryf39kxhHPz4BOeD1wyJl\nBiW1bWqwuj06VsZlaZXB1w/D+1A06yMZJfhTABEBAAH+AwMCelsOFYDjyITOymsx\nMA7I2T+o8drgvaQi1Fv5t5VXjePJdo9KiqXNVVeQfU2o0DWN7Aau3vhFGA95EHbG\nOOOPeikQDrbFWUoppeQSzExzcdwr/ySP/ETke3GKvaANzqBp8rVs4QkAD+EaPgm/\n8MQxpMre8APRavxfI9ofkAEDMUrvBqJ2gzhmIY43ulFVrkUWBAZxfTC9AyiwkitP\nUOau3Be9PUPcJvTJLNueB9KYdKn55gmAHwcMGPrKWFKnL9mhdFCfTotUpPLnu2G9\noOJLexcy+9CoClSkiZXJFg/uQaTKtZQEE/R6IafNL/hN0SiPz0WkcfTRIjDHOoQr\nPuYnR1T+7twAKMWLq7EUwjnzov4UTOOS31+1cswaCSUduknJTDPaAMmm7+jwD+Av\nnmLMNc7nmvQqr34vKRuq65nTLZgEUkj2hb8I4EmqH8W57aPIYkC/s9zCtRjf7y9G\ntNpry48GupqVO92LpIzs6prr7lHsawy30MY50/dHWsxJ+xRUAQQJh1yoTQgOOBgf\n0tL+ZKnMM58/eOhmj9+G4DCeJQPrkIONiXYlwSDU1ok6BfdFstKqvtX5Vib0ujLu\n3pir+eOXTSqVM3lz+0PIEgNyT5Fq+0zA5usF99owUgYZJm1lTBpVJElOliM0zIJz\ntvGZS6jS5X1qNfbL6hFbuTEfDHukRWnwn2ZQelGdCG3MRUpleFhbY8eQL4UtW2nR\nHVQzXTRQfSo3PVwVak2gzItcS608gAPqLqKH+X9jPk3Ihn6XGyqwR7g/h8Ggq8ee\nUMdbZzNUzdxGstyMwBEyXZA0Hxlojk1VyB20+xlcaLfFq11oTUAHeVNZxVTN/Yzz\nymgGu8yPU5CNRXxTMSg+MZfXqFJBAaWIdYJRw8r6MGzDCD6Erz+y6PUbLLi57zQv\nqbQfQ2F0cyBNY0RvZyAobWVvdykgPGNhdEBkb2cuY29tPokBPgQTAQIAKAUCUlXE\nrQIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQJ2DcSvj/sywk\nxAgAob/ZasZzj8iPNRtCXKGdUDvLu7x8CON3hhfvsa3qcBG0ETUUihaJ9gRonHQd\nNuVoMKHMV81TqpIYJKyzaL3vkRx8cZk4etQ4HY+TVXboKKI40apFU4kTiZQMOs39\niVbnm+WuWWSg0OS+3ujAj1VaFQ0y5F9CLBlhYlDlssA/94gDLEPtpqmX19bqewcv\n7alrBN2s257dn9wx26HZsE7w/OHaCWElbdcT+nX/SdtdXYsXj1ufjEbi8IPNtAKQ\nxjFDNnLdv1qnzHWVdpz6q0ZBdNsCEuXgBI0U3ui/5UJl6mnm99gqTdcKZguySZ60\nD1LkyzHJMeMSPdljI/sqfMjX3Z0DvgRSVcStAQgAu8VwtMvJ1D+HqFuLCd1S6pp8\n0fYpPRlXMXvGL3W46XXv0WYer835wTtWrSHHpsmUdzto9Q6YaGmXvQi7+4Vt1apy\nWbSwVGJpTkn0v76Sma/TmLq2u/FWpT11kB31ytYX2w6xzYZlRepSs9PFIxYg2ukf\nXIjuSetps5O4juVFHNPylRYy41gDkj/40BPlaiMs7EOmd6COTO6ns/VfpOc1AYjG\ntRG8vcCufPdf68xSHJNYq3SOpDtaAPIcCAeiUAUfdzSqbXSCQPZhvu/GnN8mokvt\nLnRBPuCxxCBdAHqaEh9rjGSgievH6/XpzTtnR1A41Wap+CQp5uznGugTAGrIAQAR\nAQAB/gMDAnpbDhWA48iEzuIn7APerKvybuDBuPV7MXmk/jhF6FuO/CEtzbX5i8nv\nT5fkyxA/9q9brWhytS2/+2j6hLLyqgt5z2d6y5VeJlcXfPligTZfmbNTcH4KpIub\nNYny9JGS7pGT1Ku3lc5PnKgOpAz9fLIB9xL1zFvWXn7wxcJSX7AY4HS6RiiSr9AV\nRxTVKiF2T0DFA7erbk/aUPyMAio7IbonhWrV3d+3ajuXHF5mhqvdqFXncGXY7LpG\n56ynLKFYMv+yorx0f3N3AwpNOLZWC1j8YstTzIefphuC+75mKyotuOJrGvzFtngi\nAaRx64ecQBJhdDVhdUmapEK9y9gpAiILjrRLZMKEC1ZTsUZX5gFWh3wwxpaQmrMe\nJSdkqmDXEY3LjlpwyCvQeZFnumMCrkTulEBh92ylHN0KN6rrOsnwBHEa6u277Q+s\n/vDSN4ZQQ6jPvw1vXDtCf1v6+WUhpjab8/Wh8vTu4LPKYViOqD+LU9d/gzr5hGQa\nKvqD3ut16yesLI8yjpLVSdQ8d3FpN/o96kLUnvX8+2q2mVdQoogeTFDnBmaYNeQ3\nwFmCJ9cDd+GTqyhW+hBIt42DscSES/5AL1nzUFp2X0RFzVH1H9EyYlrMm+9j1JIQ\nKdGi+f4vYvvtmI1LmUY8dOmhHYw/Q+4Z6F1skR4+Ufgn+gCR5JlM8JEDFNG7HejC\nMqDeHdGRSHhwVwxx7X4vqf4DkhoEkPrO6//J8SHJMHrAYl3a+DB/B6YA/7ok1qpx\naGSZBKXzh+O9fXksuoRqWMZRdWCP7m26sLCnaH0HzrfxxPnaCcBfNbV2zE/yqEUc\nVeJcdcyT1q7ysx2C3YT5y/katPgwl6f2TpAwsnVNlkjlgp3g4ww5iIaIDEb/Wjbp\noKjD0uOb3onQ/PHqrkNMkmg+pAKJASUEGAECAA8FAlJVxK0CGwwFCRLMAwAACgkQ\nJ2DcSvj/syxaOgf/e5e/4OMSKY8/+aIQ7i4DWj+VSncNfixrbNjX4NH//Bg/UYRS\n8b+TKgpEuR8uTslF+/BGCHncv5SQRy7fgFTejMJSRkBPwb8CzirWoo5bTvjEs2tp\n4rSLLg1gM5+SdY4NinKEo9pH3fKxszQIMzk/z0rSK9JDhVBzfpQXAEEd1pdMo+t3\nJETDfjWhRAuFcE/6nFeVGTGwQn0dX/lQ9xxxhx+/K4PYAx1mYKsIFPtj9Y3C3uIg\nBl0yUJx3nJUTCBO4Wunn60UI/WRix9HcGhf/kbfF/IILuZoTSodvKYUxwcJ/iAAj\nObMKV7f7yqGEQNpyrXlHl4qGSzkvgxQ6IzTA1g==\n=DRiu\n-----END PGP PRIVATE KEY BLOCK-----\"\"\"\n },\n ",
"end": 9954,
"score": 0.999609649181366,
"start": 6478,
"tag": "KEY",
"value": "5JHmJ2MoDDUwzXWwnECMFbGF/6mGospOgLuQwGCjg0SMBRZ8j\nSbtucJNZIKzCvk6se6wy+i1DH2+KzMSKDyINKgVjjA1rIpcvoFuDt1qBvDFNbQBZ\nEiGSdnIYUn7cAJat+0SLIBmn6y7Mtz2ANt89/qwYV8dvMWyTcnR/FU9QhptaSF5Y\nTyO8j54mwkoJqi47dm0L164u30uImObsJpRPxww/fwyxfbhFt3ptYIUhgxJjn3Ha\nRIlVww/Z7Z7hROVdaPXDwTVjYrk406WtvFEewhigSP4ryf39kxhHPz4BOeD1wyJl\nBiW1bWqwuj06VsZlaZXB1w/D+1A06yMZJfhTABEBAAH+AwMCelsOFYDjyITOymsx\nMA7I2T+o8drgvaQi1Fv5t5VXjePJdo9KiqXNVVeQfU2o0DWN7Aau3vhFGA95EHbG\nOOOPeikQDrbFWUoppeQSzExzcdwr/ySP/ETke3GKvaANzqBp8rVs4QkAD+EaPgm/\n8MQxpMre8APRavxfI9ofkAEDMUrvBqJ2gzhmIY43ulFVrkUWBAZxfTC9AyiwkitP\nUOau3Be9PUPcJvTJLNueB9KYdKn55gmAHwcMGPrKWFKnL9mhdFCfTotUpPLnu2G9\noOJLexcy+9CoClSkiZXJFg/uQaTKtZQEE/R6IafNL/hN0SiPz0WkcfTRIjDHOoQr\nPuYnR1T+7twAKMWLq7EUwjnzov4UTOOS31+1cswaCSUduknJTDPaAMmm7+jwD+Av\nnmLMNc7nmvQqr34vKRuq65nTLZgEUkj2hb8I4EmqH8W57aPIYkC/s9zCtRjf7y9G\ntNpry48GupqVO92LpIzs6prr7lHsawy30MY50/dHWsxJ+xRUAQQJh1yoTQgOOBgf\n0tL+ZKnMM58/eOhmj9+G4DCeJQPrkIONiXYlwSDU1ok6BfdFstKqvtX5Vib0ujLu\n3pir+eOXTSqVM3lz+0PIEgNyT5Fq+0zA5usF99owUgYZJm1lTBpVJElOliM0zIJz\ntvGZS6jS5X1qNfbL6hFbuTEfDHukRWnwn2ZQelGdCG3MRUpleFhbY8eQL4UtW2nR\nHVQzXTRQfSo3PVwVak2gzItcS608gAPqLqKH+X9jPk3Ihn6XGyqwR7g/h8Ggq8ee\nUMdbZzNUzdxGstyMwBEyXZA0Hxlojk1VyB20+xlcaLfFq11oTUAHeVNZxVTN/Yzz\nymgGu8yPU5CNRXxTMSg+MZfXqFJBAaWIdYJRw8r6MGzDCD6Erz+y6PUbLLi57zQv\nqbQfQ2F0cyBNY0RvZyAobWVvdykgPGNhdEBkb2cuY29tPokBPgQTAQIAKAUCUlXE\nrQIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQJ2DcSvj/sywk\nxAgAob/ZasZzj8iPNRtCXKGdUDvLu7x8CON3hhfvsa3qcBG0ETUUihaJ9gRonHQd\nNuVoMKHMV81TqpIYJKyzaL3vkRx8cZk4etQ4HY+TVXboKKI40apFU4kTiZQMOs39\niVbnm+WuWWSg0OS+3ujAj1VaFQ0y5F9CLBlhYlDlssA/94gDLEPtpqmX19bqewcv\n7alrBN2s257dn9wx26HZsE7w/OHaCWElbdcT+nX/SdtdXYsXj1ufjEbi8IPNtAKQ\nxjFDNnLdv1qnzHWVdpz6q0ZBdNsCEuXgBI0U3ui/5UJl6mnm99gqTdcKZguySZ60\nD1LkyzHJMeMSPdljI/sqfMjX3Z0DvgRSVcStAQgAu8VwtMvJ1D+HqFuLCd1S6pp8\n0fYpPRlXMXvGL3W46XXv0WYer835wTtWrSHHpsmUdzto9Q6YaGmXvQi7+4Vt1apy\nWbSwVGJpTkn0v76Sma/TmLq2u/FWpT11kB31ytYX2w6xzYZlRepSs9PFIxYg2ukf\nXIjuSetps5O4juVFHNPylRYy41gDkj/40BPlaiMs7EOmd6COTO6ns/VfpOc1AYjG\ntRG8vcCufPdf68xSHJNYq3SOpDtaAPIcCAeiUAUfdzSqbXSCQPZhvu/GnN8mokvt\nLnRBPuCxxCBdAHqaEh9rjGSgievH6/XpzTtnR1A41Wap+CQp5uznGugTAGrIAQAR\nAQAB/gMDAnpbDhWA48iEzuIn7APerKvybuDBuPV7MXmk/jhF6FuO/CEtzbX5i8nv\nT5fkyxA/9q9brWhytS2/+2j6hLLyqgt5z2d6y5VeJlcXfPligTZfmbNTcH4KpIub\nNYny9JGS7pGT1Ku3lc5PnKgOpAz9fLIB9xL1zFvWXn7wxcJSX7AY4HS6RiiSr9AV\nRxTVKiF2T0DFA7erbk/aUPyMAio7IbonhWrV3d+3ajuXHF5mhqvdqFXncGXY7LpG\n56ynLKFYMv+yorx0f3N3AwpNOLZWC1j8YstTzIefphuC+75mKyotuOJrGvzFtngi\nAaRx64ecQBJhdDVhdUmapEK9y9gpAiILjrRLZMKEC1ZTsUZX5gFWh3wwxpaQmrMe\nJSdkqmDXEY3LjlpwyCvQeZFnumMCrkTulEBh92ylHN0KN6rrOsnwBHEa6u277Q+s\n/vDSN4ZQQ6jPvw1vXDtCf1v6+WUhpjab8/Wh8vTu4LPKYViOqD+LU9d/gzr5hGQa\nKvqD3ut16yesLI8yjpLVSdQ8d3FpN/o96kLUnvX8+2q2mVdQoogeTFDnBmaYNeQ3\nwFmCJ9cDd+GTqyhW+hBIt42DscSES/5AL1nzUFp2X0RFzVH1H9EyYlrMm+9j1JIQ\nKdGi+f4vYvvtmI1LmUY8dOmhHYw/Q+4Z6F1skR4+Ufgn+gCR5JlM8JEDFNG7HejC\nMqDeHdGRSHhwVwxx7X4vqf4DkhoEkPrO6//J8SHJMHrAYl3a+DB/B6YA/7ok1qpx\naGSZBKXzh+O9fXksuoRqWMZRdWCP7m26sLCnaH0HzrfxxPnaCcBfNbV2zE/yqEUc\nVeJcdcyT1q7ysx2C3YT5y/katPgwl6f2TpAwsnVNlkjlgp3g4ww5iIaIDEb/Wjbp\noKjD0uOb3onQ/PHqrkNMkmg+pAKJASUEGAECAA8FAlJVxK0CGwwFCRLMAwAACgkQ\nJ2DcSvj/syxaOgf/e5e/4OMSKY8/+aIQ7i4DWj+VSncNfixrbNjX4NH//Bg/UYRS\n8b+TKgpEuR8uTslF+/BGCHncv5SQRy7fgFTejMJSRkBPwb8CzirWoo5bTvjEs2tp\n4rSLLg1gM5+SdY4NinKEo9pH3fKxszQIMzk/z0rSK9JDhVBzfpQXAEEd1pdMo+t3\nJETDfjWhRAuFcE/6nFeVGTGwQn0dX/lQ9xxxhx+/K4PYAx1mYKsIFPtj9Y3C3uIg\nBl0yUJx3nJUTCBO4Wunn60UI/WRix9HcGhf/kbfF/IILuZoTSodvKYUxwcJ/iAAj\nObMKV7f7yqGEQNpyrXlHl4qGSzkvgxQ6IzTA1g==\n=DRiu"
},
{
"context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nmQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk\n5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt\nGWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp\nukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1\nwdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B\n1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq\ndWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4\nuY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0\nclTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4\nggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft\nvNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB\ntBxNYXggS3JvaG4gPHRoZW1heEBnbWFpbC5jb20+iQI+BBMBAgAoBQJST0/PAhsv\nBQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBjhHtLg5MPDEV6EADG\ndMwseeQ9ie+zjRx9F8yAM9vMKMQXA36Tqb1CdgT35hVfGNxut2I87O0CkECbQ8xl\njicUt2GmGIDO/hw124yM6sui2FH8rxiiWHVfKEIq/rF3mZTzKJhs2Bv//+JFfWAE\nvAmWfdhZPptHuRoN47VfK60KP49BwbFwTV3QOdoe99eFmuDJvW5KTlXEk+Ib9uZY\nipQL1R7zlh1ivjP+b7/WkptE1adbzyC/N3ghcgZUD5lWYh7kNibx5zA01gOMLBSX\numtIOoI4ksf6b+M0Os4ADeyO+BiGbEbPfpuigrFQvKIhUj7lYwe5BlwLwxIag8WL\nD+Nlcot5x7EulonbjF5PzLKmC9mW2p1QnseSPS3rYTmYkpBzIQxvcBgfqcbuMEhR\nkFCuMMS1esARRLhKcGe9GWwztMYAVJUFtFuwe9Th43gvK66lbrkaIh1gfRnFW5vx\nrNjY0zddM39WFUo7WCfEr3bYbZAoSMEbayz1SDZu2noMRsETVaiVccknw1FNRLXx\n0n+HVAb7pWqcHOgodrrwA3kuCA8QdgMYF1aJAgzmEH4q8NtggaRQNqfDsGcDToYw\nAjGxzrQRJ/xIIct3PSamBTfiDVbFiY2y0LS0Jc2Uj0ptPfvlWRaxM6CHwxt7rcyi\nZPzW1cj9+z6eC3pmlJoNoxLx5jj3V1ZxYvIvA7tZ6bkCDQRST0/PARAA09+Bpd24\n5vd46Dh+Qwro43f+3KQbjsZGJuWbMSmu8JTAePPclJtU6bFxbjbz1hahXJISRVu7\n4FIN5grqytX7/RI6WbtSQ9vVftWZ2xzThK+RSz/nwxv4GzMpEUWAX7HJ6bqkogkO\n7g4lV9H4r8lF21Tpcx5FfKYJIJZcix1Ac6LMZKuRJoT81jm057iWa8WQ/CWDxA9Y\n2X/CeEAsjBQxwr59T2NR51DNpSri9OFjX44rpCIcdBHEzWODPDyDtyfp8p+UMUwv\nSd0ihaJ5ER9hbbU5Fm+n0GJSgcND3oyfeKOhlsr32yxYfQfVhQdlq30h/nAqso9Q\nsyy8/AY51srDfHGc6NXFcc8C7M9+vjWnjOlr+iWvaBWsNChPjXWLmeEKevcqs1br\npMmnkwhqhCT+B6z6hEAfXYjFaLVihqtraRikIAZUfUJSUmalvmtYpEHAcAGf7C0r\nM6aQ9PwkFNbqTleC5OxYWG2hrNCPWgDY/M1/NxnB64+XTdbk+3hTAhgY6+QvkkFq\nMQ9ReRcwv/t9ixHg2mjyPZmBOSCjdK23BKqUoT9C7mpQQ8ibM5XxC1rOS63QVuwM\ntvFao0k9movsNdqcUhX+oouPYxfiNluZV6GLWP/DobqEYdmwOCOTjWkibNeg8JfO\n89S1GZTtPs4kVEhZPOE8oqMpMDyi5i1D3+UAEQEAAYkERAQYAQIADwUCUk9PzwIb\nLgUJB4YfgAIpCRBjhHtLg5MPDMFdIAQZAQIABgUCUk9PzwAKCRAv4BxFQ0jaOTmM\nEACp8FZ+7f7C0knvVrx2O1u2NwYsUUcoE7XZIVZGgvlqFmSfEYMF5TPHettMetWh\nwMQosIaORU3P+5qAelhT8lDHz1lhFTX8L2JMC/iPwwtYw3cKUJTHke8XSuwzlNqu\nsqTfcc8/Qn49TSEymtl+tPciqKDDSnRPnUgNIiCN4WEcvTglx40LHQ00CuDj0Rao\nKNNmVTupC8MGtzWPXb7ZtRlBYBCKJoBZzfKozmimXCHCqddRw76g6rAScPesNJxE\nhvNe/3ZM3hL2vYI0s6zIy8n2hqI9Qn4312qJusSf6V6IMwkss/v8sTseGigMmH2R\n1hX/as0ZO8S2y78Fy1OK9bZ2G5mTKI1ovKi7ba0xtudl5cbozpDM8GPwtkCAQ1ca\ny/FyUwBH3CfATSdSbdx/nnZgSJyplU+xMEl/glMRY5iTvnLH1+oZnJN40lxvmVKZ\nOHe3PDsB0ECBNa9kHY/LRGbnMAOwKUPKBGu42YiMeAAsVbNSgBb+smQj1qq1813c\nB3FO+t4u7kuDcr0aM+ged5d8IiAbRrHP8gQduidCOe7/HRluW6FIZVs9TVxv41FY\nHFj5c7/4D6zAYOZ77Pc8uT+HlXwZLcrXHOq1uiBalU5CEK0oIYxgP/IFitJZdDdL\nTuKd2rsNuJnnrTn6qJyw0FIf8cxChTCTKFPCterCmhp3jo84EAC87mBws7GMAI9G\nF9e9uBVTp7K5lskjBNq+vZMR0dpXBfLbci7dchqk5jPv9eChR5O+VsW8/CKY5OPJ\nqYBjhqnxr3d65ywnNIs6j8Ty1P0UCCtjom6lnsipJ+BPoe1nyMyFkDCJxRiiE0nl\n/qvQ3gmq/kTlkbd112denN0M3xReUryvmH1fH8QqTI6y2BlMRIJfDWShEUUqV3J4\njah5WR8mIgGv2UEBvK4OJrtHkIzEgKkLYJFijiHS1Jnc4S6aXHliKEaYPXXtU1Om\nBzWxYSbkTDtZ98KoWs+OzNfT4+gu4wHbH98tPOUlq/ryEbeFeNv+29ngRIx9FNQx\nQY4TiYD00vF2ifCwC/FVWQ0ybyiufago1h0hnvdu5x6pw3h811cWFuPcbN1M0opp\nGajvutV2PEoXx7NIHsg8F+++eVwqmLKcw3EJw6AFNBzs7lFFiAzzV/PGoRRW/D/c\n0QqTitcuFJ66xzueImZp+oKfjmO1gEsNg15P4iQjpWCFmpdi3Fzq4NsIDjzpBMWq\nmNuq4W0HeVlK6RXv8IcySE+sFCCsqtDEhSBY68aepbCwlFz2kuAvr+jbuT0BTKA5\nyh4J89ZwGA87CFabOeXtqeyS9z7ux5xKATv1bXoE9GuG5X5PsdNr3Awr1RAufdLH\nnMd8vYZjDx7ro+5buf2cPmeiYlJdKQ==\n=UGvW\n-----END PGP PUBLIC KEY BLOCK-----\n\"\"\"\n }\n }\n",
"end": 13892,
"score": 0.9995737671852112,
"start": 10149,
"tag": "KEY",
"value": "mQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk\n5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt\nGWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp\nukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1\nwdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B\n1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq\ndWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4\nuY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0\nclTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4\nggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft\nvNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB\ntBxNYXggS3JvaG4gPHRoZW1heEBnbWFpbC5jb20+iQI+BBMBAgAoBQJST0/PAhsv\nBQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBjhHtLg5MPDEV6EADG\ndMwseeQ9ie+zjRx9F8yAM9vMKMQXA36Tqb1CdgT35hVfGNxut2I87O0CkECbQ8xl\njicUt2GmGIDO/hw124yM6sui2FH8rxiiWHVfKEIq/rF3mZTzKJhs2Bv//+JFfWAE\nvAmWfdhZPptHuRoN47VfK60KP49BwbFwTV3QOdoe99eFmuDJvW5KTlXEk+Ib9uZY\nipQL1R7zlh1ivjP+b7/WkptE1adbzyC/N3ghcgZUD5lWYh7kNibx5zA01gOMLBSX\numtIOoI4ksf6b+M0Os4ADeyO+BiGbEbPfpuigrFQvKIhUj7lYwe5BlwLwxIag8WL\nD+Nlcot5x7EulonbjF5PzLKmC9mW2p1QnseSPS3rYTmYkpBzIQxvcBgfqcbuMEhR\nkFCuMMS1esARRLhKcGe9GWwztMYAVJUFtFuwe9Th43gvK66lbrkaIh1gfRnFW5vx\nrNjY0zddM39WFUo7WCfEr3bYbZAoSMEbayz1SDZu2noMRsETVaiVccknw1FNRLXx\n0n+HVAb7pWqcHOgodrrwA3kuCA8QdgMYF1aJAgzmEH4q8NtggaRQNqfDsGcDToYw\nAjGxzrQRJ/xIIct3PSamBTfiDVbFiY2y0LS0Jc2Uj0ptPfvlWRaxM6CHwxt7rcyi\nZPzW1cj9+z6eC3pmlJoNoxLx5jj3V1ZxYvIvA7tZ6bkCDQRST0/PARAA09+Bpd24\n5vd46Dh+Qwro43f+3KQbjsZGJuWbMSmu8JTAePPclJtU6bFxbjbz1hahXJISRVu7\n4FIN5grqytX7/RI6WbtSQ9vVftWZ2xzThK+RSz/nwxv4GzMpEUWAX7HJ6bqkogkO\n7g4lV9H4r8lF21Tpcx5FfKYJIJZcix1Ac6LMZKuRJoT81jm057iWa8WQ/CWDxA9Y\n2X/CeEAsjBQxwr59T2NR51DNpSri9OFjX44rpCIcdBHEzWODPDyDtyfp8p+UMUwv\nSd0ihaJ5ER9hbbU5Fm+n0GJSgcND3oyfeKOhlsr32yxYfQfVhQdlq30h/nAqso9Q\nsyy8/AY51srDfHGc6NXFcc8C7M9+vjWnjOlr+iWvaBWsNChPjXWLmeEKevcqs1br\npMmnkwhqhCT+B6z6hEAfXYjFaLVihqtraRikIAZUfUJSUmalvmtYpEHAcAGf7C0r\nM6aQ9PwkFNbqTleC5OxYWG2hrNCPWgDY/M1/NxnB64+XTdbk+3hTAhgY6+QvkkFq\nMQ9ReRcwv/t9ixHg2mjyPZmBOSCjdK23BKqUoT9C7mpQQ8ibM5XxC1rOS63QVuwM\ntvFao0k9movsNdqcUhX+oouPYxfiNluZV6GLWP/DobqEYdmwOCOTjWkibNeg8JfO\n89S1GZTtPs4kVEhZPOE8oqMpMDyi5i1D3+UAEQEAAYkERAQYAQIADwUCUk9PzwIb\nLgUJB4YfgAIpCRBjhHtLg5MPDMFdIAQZAQIABgUCUk9PzwAKCRAv4BxFQ0jaOTmM\nEACp8FZ+7f7C0knvVrx2O1u2NwYsUUcoE7XZIVZGgvlqFmSfEYMF5TPHettMetWh\nwMQosIaORU3P+5qAelhT8lDHz1lhFTX8L2JMC/iPwwtYw3cKUJTHke8XSuwzlNqu\nsqTfcc8/Qn49TSEymtl+tPciqKDDSnRPnUgNIiCN4WEcvTglx40LHQ00CuDj0Rao\nKNNmVTupC8MGtzWPXb7ZtRlBYBCKJoBZzfKozmimXCHCqddRw76g6rAScPesNJxE\nhvNe/3ZM3hL2vYI0s6zIy8n2hqI9Qn4312qJusSf6V6IMwkss/v8sTseGigMmH2R\n1hX/as0ZO8S2y78Fy1OK9bZ2G5mTKI1ovKi7ba0xtudl5cbozpDM8GPwtkCAQ1ca\ny/FyUwBH3CfATSdSbdx/nnZgSJyplU+xMEl/glMRY5iTvnLH1+oZnJN40lxvmVKZ\nOHe3PDsB0ECBNa9kHY/LRGbnMAOwKUPKBGu42YiMeAAsVbNSgBb+smQj1qq1813c\nB3FO+t4u7kuDcr0aM+ged5d8IiAbRrHP8gQduidCOe7/HRluW6FIZVs9TVxv41FY\nHFj5c7/4D6zAYOZ77Pc8uT+HlXwZLcrXHOq1uiBalU5CEK0oIYxgP/IFitJZdDdL\nTuKd2rsNuJnnrTn6qJyw0FIf8cxChTCTKFPCterCmhp3jo84EAC87mBws7GMAI9G\nF9e9uBVTp7K5lskjBNq+vZMR0dpXBfLbci7dchqk5jPv9eChR5O+VsW8/CKY5OPJ\nqYBjhqnxr3d65ywnNIs6j8Ty1P0UCCtjom6lnsipJ+BPoe1nyMyFkDCJxRiiE0nl\n/qvQ3gmq/kTlkbd112denN0M3xReUryvmH1fH8QqTI6y2BlMRIJfDWShEUUqV3J4\njah5WR8mIgGv2UEBvK4OJrtHkIzEgKkLYJFijiHS1Jnc4S6aXHliKEaYPXXtU1Om\nBzWxYSbkTDtZ98KoWs+OzNfT4+gu4wHbH98tPOUlq/ryEbeFeNv+29ngRIx9FNQx\nQY4TiYD00vF2ifCwC/FVWQ0ybyiufago1h0hnvdu5x6pw3h811cWFuPcbN1M0opp\nGajvutV2PEoXx7NIHsg8F+++eVwqmLKcw3EJw6AFNBzs7lFFiAzzV/PGoRRW/D/c\n0QqTitcuFJ66xzueImZp+oKfjmO1gEsNg15P4iQjpWCFmpdi3Fzq4NsIDjzpBMWq\nmNuq4W0HeVlK6RXv8IcySE+sFCCsqtDEhSBY68aepbCwlFz2kuAvr+jbuT0BTKA5\nyh4J89ZwGA87CFabOeXtqeyS9z7ux5xKATv1bXoE9GuG5X5PsdNr3Awr1RAufdLH\nnMd8vYZjDx7ro+5buf2cPmeiYlJdKQ==\n=UGvW"
}
] | test/files/decrypt_verify_msg.iced | samkenxstream/kbpgp | 464 | testing_unixtime = Math.floor(new Date(2013, 10, 24)/1000)
{parse} = require '../../lib/openpgp/parser'
armor = require '../../lib/openpgp/armor'
C = require '../../lib/const'
{do_message,Message} = require '../../lib/openpgp/processor'
util = require 'util'
{katch,ASP} = require '../../lib/util'
{KeyManager} = require '../../'
{import_key_pgp} = require '../../lib/symmetric'
{decrypt} = require '../../lib/openpgp/ocfb'
{PgpKeyRing} = require '../../lib/keyring'
data = {
msgs : [
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
hQEMA+bZw3a+syp5AQgAqqimwGjRe/m9d74f2Itu4rAs/BJUjgPprCSn1JTOBurK
nneix4XLQM9slGNJANiOhjEmGR011+Dhk4PV2SNaJrgXI0RS43O3UAjI4gHUHpKF
lHit1/UBwK24dTzl8G8LSBoI9g1p3QZTZqszsrsYOZfzpoObE1If0IlYvP6VTURC
QUsHoOKaWXbVQFaUqW8tYqpCgiBZ3BLQbzdO8Wy20R3qRr/zEltvK62o4fitW1j/
t8vjzKXHxKCcE+Rqwdn+qb1/KLf+AOrqGJL8gDXytVeQlxMmiV3J/GDgaq/Ikjzk
whot7+b4kLwypxB8/fqNO2alFICwnXtlUMeqwtJFT9LqATfV9f85EEfr3Q4ejsB9
1eMHkubjSbj/SMIw+HlA/dYo4SFVxbej1ur3eY+VQFNA43IqSSsTKp2o9ZEvyXOt
zOHZSscVSPg1h7huqi9LWgAYUzPTqQHYkzRs7ckJ/jb+LBKesX4n6yUhuO0XZzNi
EC1qNueJjkNOy0T+NCSuTdMYq3P8De0hBu/5HnrUwgsujgWrrUMmSaTmCezyUkSo
4tBaPu8PtWaC97TPYefTCu5eI5L28NAAlrGVxtxkdWJs2IJZqGDR0O6X+xzxkFsH
jc1chiypfpEa4XsuvqfAkdU0I036ebwo+65lQwiVnbf0+XKxup3QspI9lmlMoKL3
A6Th+sqaLEv4GOca1YyI40on6ESg24TaC4WQK+SIVTuYqNdWvhb2lCcdK/WdzkIw
Jwiv2OGfAh5S8yg8c6r1k/WoWv1/hK6wj+MhBX7QSAtkde5BYX3P0ZpAUYXIBqZz
TscMwNiHdgS1FcQGk105wbfztfpBLAkIlVD3PmHxE8rIhvAcS+1GFn+TYSwbZE3M
kYyFvOKHjwnQEdQCSQuPc4YgfWChFYBtE6TNvp/e4rhcIf+7U6uRKLkXSS80jzDM
9sRp11/CxDXx4nZPF9zXd9sKBLXcsEs0QTpxwAzU0GCj9jc8AOZTQXFolzal40S9
C4HoctsmAb2ybX9+4E0SvcBGoMpmWDdXH3KB4MfJoSFLP2ErdGGuIIlDf94oqprv
sNOCls/STmI9L3RR1/g9AuwIElm0HKa3YIzJHE8hgMjsOAvDM1VQqRBLoYbKI74w
bLwXTajt2kN4gdJgHHZ0dZjZQZlf5D7DukY7qdghOOOOxrbPgrN1Qy8QLvdDcio7
lRe/HZUJkihmw4YfMaYfR5c0tVjfPVB/le14iz5E8gLFbWq0tANgEX5h8ylUepu/
N8eJSajVl+ybJtl+YmijM2viR03BJjnyWQLcTk+ZXqH30ti7cGFqtBrnLuIIn8sV
m1U9CgicfSMzg/ASflw6U6Zb290uheY1rFte1ZfrKoIBjGIV07s243VDR1I464zj
6xqr6dX7IuC0iP4BcdLEAUe2r99s5dVcuccHrgq7Me7tTYWSyxEbGfw2N1H00kGb
uOftACanYOkJT6j1m3k1c7XohZsOL43JK3yOkprGZczHRwrrQrbdHHXB27PhVq8e
YyjPQTmufZtWXgkdv1Q4f/oJks7NK9RATBfD/7qgOYpWNDDkmFX9qK23HA4shJu+
YnS6s8MBxyb+3HSkqL2z1Vv5JjEDpeuVFtUsJ4dr3BO0MzrqHVPRDJsjiIPqyb2A
bXX1zefINu0l1zgnDW0lggN/Fxqyrw7654yQGR1uRyEAVMO3QeoWaBSMIf39XiRN
YcDJo56SFcZQovBMuz6YzddJNal5/BFAdWhkEbwzkqJa3QEjm69YwQem9+ZB2n4I
RsLjWln6APXtNeTi4YAXgcb7KifnLSvprwGcna+H0b4UJVfs3IXYjvi1bggTGTj+
1rWAX2+f+fis8i40nH+zHQznZKtwZ/s7qb0KlwNui3moXSOd3YVSNwgmDMAPlPun
B5A13/wvLDwXP7j3gUZ2MJcm3x6VrX1LTcCRu/AqJFLyKHqovCeYSdGRotFRNDzv
NHw3ZbXgcyHyOtSoepHh+idb+F02oIDRkjQwezPRAiZk/vFbjAXGCcYQ9UBmScLM
QJlOr7Ua+tqT2rKmb1PwJYQz39SnUDdUD2+7VckUH/ioCL16k2x0XaK9KfSIpmzh
Qwe+4+nd17Jpj5jFfg2mYr5ccDIEugfCcplExI/VcgS+drlFSMgP871rzeJyIpCy
mqG0bSbMM3VJ307AWDqoiP2hSW5wZ9YweVeFh1DdH2I2Xwt5xYkQDx27M/H9LO1A
WYxrooYFv+qVvVMS
=euQN
-----END PGP MESSAGE-----""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
hQEMA+bZw3a+syp5AQf6ArI5PQg+kzq4h7T4nZA9q/Li4kjf7eN2C4m1XuBm/B08
245kUmI5iOkfFe9HbT3azrvdNYe9VzFweoKKJkWbYLRQsw8BN4lGlixpETDle4cz
bd94yIbs//Xe+505h7jU+RY+cAqamaSPTpZG901dIB5XJwdP8qM2mYacCeBXIWmE
BMUYUT9MtYZFESstbMHI/pKUiJRhhBpJLO0FP5KdGyuO9JOQZui0cagnxUynqVTU
+/DOMNf3nQeXBM4lyZQx3pFcXzNwL6URXz/yRa25CxDP4bpVcrZ5qSiJqZ+jpSRs
F8WKEkGCftzwsWIxsUPcs+6ClBruLbSKSroP4+ci/dLBDgHoMF+R6Efj5sU8tWlE
1Z3KQjB2ENqu7XIKf49cpnY06K3QKWppexflWT5UbHzOwn5O9Ih1NPL3PbFqQV+/
yJDO2qjxvq6PXOOwRbxvasYzpYXoLO5soyoEbmQ/VwTZL8Pw0Gima1s1GejTHcvv
Z3BvqyuiJGAnYq5ShI+SlDVI2uRwJ6nThQtGdIjaQZo3ilSPuFE8sWSO03IKKxQy
ZyNwKj0miHaIOqevu88588zwsAKAxUw7gYd0GWSN9G6MHf6P1P7dZyd92dPnBJu0
L8AFMrYN1HcLuLG12BeONPUty4ZGUwjnFn9wu83RRKZ0d+yjVzhoAv7VbQxKBE/p
eQntRg76DYwOmTBV+ZGsO+rezxQ/1sEMRq0bvJIybpDLFUwg3QmGc4ZGJyBQ/FKA
V7xwSJBg5wSzZ9pSo4HQFi6pF/UPTc9xbbKQDIEnZlYdaIiTS0J/Xx321f5Paicw
wa/vt7tlsS8evxmVvhgMWZ0tc8B82ZM8o1AHLewmty2PFPuGVMG9W3DJJSBH+fRC
7jB2iHwfhUQ5ntFkxMcmVY1IYK2WtHQ4nzYdvhiSp9MTuBqXfy1RzWq6LAbUUGfU
o7cJyIX4q4MjzvkYEjxxnw==
=S4AK
-----END PGP MESSAGE-----
""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
owGbwMvMwMSo/0DG1dnjliXj6ZdJDEFZhebVXAoKSnmJualKVgowoJSdVJBeoKQD
kkpJLU4uyiwoyczPA6lQ8k6tTEosTlUvVghwD1DwzC3ISc1NzStJBCsA68hOrSzP
L0ophhoYrZRcVFlQkq+ko6AENhWsAmSGkkIsWENiaUlGfhHcfiXfxIry1JwcBe+i
/AyomWWpRcVQF4CVGOgZ6BlCpHIyk1PzilPh1oE8BBQuqSxIRTLSMwSsGsgsLcpB
eFVJCShYC3FGbmJmnpICQkpPPyczSR8kqpdVDA2MzKLU5JL8okygdQpApVC7gOpA
GsE0yDyw2oz83NSCxHSYI5QySkoKrPT10zNLMkqT9JLzc/WhwaCPFNpJpenFyBEB
0lSMR5d+ZnFxaSrUdUWpBfnFmUDnVYKNQA0IJaARqEFw4B5IDI/heiAtcP+kpBak
5qWk5iWDPQ/3e0Ep0NrE5GxwANjZGiJrKHPBriepKL+8OLUoM60SrEsL5q7k/Jz8
omJUMWDspuiWpBaXQC0Axbw5TLIEmDJzUotTk8GSMMcjRKHKkvJQ5JPyUAxPzk9L
S03VhSRzVMvzgek+N7MYTTQlNbVAN7WwNDEH3anFGF4C25BaVARM3wj3m8Fkq4Ap
RhcjNEAhyFXL1ckkw8LAyMTAxsoEyqgMXJwCsNzLsIf/v8vd8sUme3UElO58Zrko
lcM7/0fuk6KiE15KcfZr7Sau0+44GZAguGBXYFeH/Q5lwcXFfzb9PnFF10l5V1LX
PnZVni9PZ/74785esCHmTmGTcerPta9fnSnTtDad+HlDe379gx2ONu/9Poaavn0S
9TBA5WT869nvTx2JXJrqb11X3loi+eKkUq5eJj/3A8Ng27gkCb6WFUo9firKEXvy
tA6d4Sr+Hjz1qJDjyi2Or+te337+onL+2puytjwr9uebnZx+bl/jrIe3xbYo/Vz8
MKht7nndOYc8St/t3bLghWHn/tz4cz2GUR6LV+/d++7MdeXjWldb+59xVb2azVMb
4MrV23v89ZpY5ZMLzDe+s9J5uXvn0hl3jE1yVO2yrgXOK88RTsi2/r02Y7/PfIa1
uxXme4gyeVUEZ2/tfzP3bFRKhYRSzytdLeMyswvXbuw23t8vZ5Cd1fgptEEqTz1u
bZjQoZViEVEa986Vv98wiW+eQsikYoNXl/Qt9oRHTvkxOaE+a6FxoHjr7YJz1iEP
7n719BOuS+nkkeqPPT93AQvvwxK7PydyUi4YdO4XkExRZPY8uznL10ilmOfaXfcm
ZubtJlEMmxiKY7nanMukz9XoaGyU0vUKyfdSlKlatkmLpeMF38Sdq6zumce8n77Z
+2alsv4GBtmYKYsloiQbrW/a2dwQn2TzWlzkmOXLOuOzDVUiyx3T86q6DQA=
=kOKo
-----END PGP MESSAGE-----""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
hQEMA+bZw3a+syp5AQf6A1kTq0lwT+L1WCr7N2twHbvOnAorb+PJiVHIp2hTW2gr
U3fm/0/SxTdTJRaZsAjbVLH4jYg6cXyNIxdE5uw2ywxQ9Zi8iWylDixsPT5bD6Q7
xlFLhr4BTt7P/oTUMANybuFU6ntss8jbzKZ7SdHbylLrkaUylSWqH1d7bffMxCAl
JOOAHBOXowpcswAurwQpaDZGX3rGUXjAcMDS5ykr/tgHIwo25A+WbIdNCYMkYm0d
BT83PUMIZm351LJWIv/tBqraNc9kEyftAMbVlh5xC0EfPt+ipyRJDh5XKTvh0xQW
T6nM9Z0qLVwUhaG9RqRM1H6D083IE9fKF6sFdce7MtI/ARo3wPa7qll1hyY5vfaT
baAzKLJPcPDf1vu2+S1c1kt5ljvao8MCCebgK7E8CPT/ajLr1xU05G7Eg0zrkstk
=ni0M
-----END PGP MESSAGE-----""" ],
keys : {
decryption: {
passphrase : "catsdogs",
key : """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
lQO+BFJVxK0BCAC5JHmJ2MoDDUwzXWwnECMFbGF/6mGospOgLuQwGCjg0SMBRZ8j
SbtucJNZIKzCvk6se6wy+i1DH2+KzMSKDyINKgVjjA1rIpcvoFuDt1qBvDFNbQBZ
EiGSdnIYUn7cAJat+0SLIBmn6y7Mtz2ANt89/qwYV8dvMWyTcnR/FU9QhptaSF5Y
TyO8j54mwkoJqi47dm0L164u30uImObsJpRPxww/fwyxfbhFt3ptYIUhgxJjn3Ha
RIlVww/Z7Z7hROVdaPXDwTVjYrk406WtvFEewhigSP4ryf39kxhHPz4BOeD1wyJl
BiW1bWqwuj06VsZlaZXB1w/D+1A06yMZJfhTABEBAAH+AwMCelsOFYDjyITOymsx
MA7I2T+o8drgvaQi1Fv5t5VXjePJdo9KiqXNVVeQfU2o0DWN7Aau3vhFGA95EHbG
OOOPeikQDrbFWUoppeQSzExzcdwr/ySP/ETke3GKvaANzqBp8rVs4QkAD+EaPgm/
8MQxpMre8APRavxfI9ofkAEDMUrvBqJ2gzhmIY43ulFVrkUWBAZxfTC9AyiwkitP
UOau3Be9PUPcJvTJLNueB9KYdKn55gmAHwcMGPrKWFKnL9mhdFCfTotUpPLnu2G9
oOJLexcy+9CoClSkiZXJFg/uQaTKtZQEE/R6IafNL/hN0SiPz0WkcfTRIjDHOoQr
PuYnR1T+7twAKMWLq7EUwjnzov4UTOOS31+1cswaCSUduknJTDPaAMmm7+jwD+Av
nmLMNc7nmvQqr34vKRuq65nTLZgEUkj2hb8I4EmqH8W57aPIYkC/s9zCtRjf7y9G
tNpry48GupqVO92LpIzs6prr7lHsawy30MY50/dHWsxJ+xRUAQQJh1yoTQgOOBgf
0tL+ZKnMM58/eOhmj9+G4DCeJQPrkIONiXYlwSDU1ok6BfdFstKqvtX5Vib0ujLu
3pir+eOXTSqVM3lz+0PIEgNyT5Fq+0zA5usF99owUgYZJm1lTBpVJElOliM0zIJz
tvGZS6jS5X1qNfbL6hFbuTEfDHukRWnwn2ZQelGdCG3MRUpleFhbY8eQL4UtW2nR
HVQzXTRQfSo3PVwVak2gzItcS608gAPqLqKH+X9jPk3Ihn6XGyqwR7g/h8Ggq8ee
UMdbZzNUzdxGstyMwBEyXZA0Hxlojk1VyB20+xlcaLfFq11oTUAHeVNZxVTN/Yzz
ymgGu8yPU5CNRXxTMSg+MZfXqFJBAaWIdYJRw8r6MGzDCD6Erz+y6PUbLLi57zQv
qbQfQ2F0cyBNY0RvZyAobWVvdykgPGNhdEBkb2cuY29tPokBPgQTAQIAKAUCUlXE
rQIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQJ2DcSvj/sywk
xAgAob/ZasZzj8iPNRtCXKGdUDvLu7x8CON3hhfvsa3qcBG0ETUUihaJ9gRonHQd
NuVoMKHMV81TqpIYJKyzaL3vkRx8cZk4etQ4HY+TVXboKKI40apFU4kTiZQMOs39
iVbnm+WuWWSg0OS+3ujAj1VaFQ0y5F9CLBlhYlDlssA/94gDLEPtpqmX19bqewcv
7alrBN2s257dn9wx26HZsE7w/OHaCWElbdcT+nX/SdtdXYsXj1ufjEbi8IPNtAKQ
xjFDNnLdv1qnzHWVdpz6q0ZBdNsCEuXgBI0U3ui/5UJl6mnm99gqTdcKZguySZ60
D1LkyzHJMeMSPdljI/sqfMjX3Z0DvgRSVcStAQgAu8VwtMvJ1D+HqFuLCd1S6pp8
0fYpPRlXMXvGL3W46XXv0WYer835wTtWrSHHpsmUdzto9Q6YaGmXvQi7+4Vt1apy
WbSwVGJpTkn0v76Sma/TmLq2u/FWpT11kB31ytYX2w6xzYZlRepSs9PFIxYg2ukf
XIjuSetps5O4juVFHNPylRYy41gDkj/40BPlaiMs7EOmd6COTO6ns/VfpOc1AYjG
tRG8vcCufPdf68xSHJNYq3SOpDtaAPIcCAeiUAUfdzSqbXSCQPZhvu/GnN8mokvt
LnRBPuCxxCBdAHqaEh9rjGSgievH6/XpzTtnR1A41Wap+CQp5uznGugTAGrIAQAR
AQAB/gMDAnpbDhWA48iEzuIn7APerKvybuDBuPV7MXmk/jhF6FuO/CEtzbX5i8nv
T5fkyxA/9q9brWhytS2/+2j6hLLyqgt5z2d6y5VeJlcXfPligTZfmbNTcH4KpIub
NYny9JGS7pGT1Ku3lc5PnKgOpAz9fLIB9xL1zFvWXn7wxcJSX7AY4HS6RiiSr9AV
RxTVKiF2T0DFA7erbk/aUPyMAio7IbonhWrV3d+3ajuXHF5mhqvdqFXncGXY7LpG
56ynLKFYMv+yorx0f3N3AwpNOLZWC1j8YstTzIefphuC+75mKyotuOJrGvzFtngi
AaRx64ecQBJhdDVhdUmapEK9y9gpAiILjrRLZMKEC1ZTsUZX5gFWh3wwxpaQmrMe
JSdkqmDXEY3LjlpwyCvQeZFnumMCrkTulEBh92ylHN0KN6rrOsnwBHEa6u277Q+s
/vDSN4ZQQ6jPvw1vXDtCf1v6+WUhpjab8/Wh8vTu4LPKYViOqD+LU9d/gzr5hGQa
KvqD3ut16yesLI8yjpLVSdQ8d3FpN/o96kLUnvX8+2q2mVdQoogeTFDnBmaYNeQ3
wFmCJ9cDd+GTqyhW+hBIt42DscSES/5AL1nzUFp2X0RFzVH1H9EyYlrMm+9j1JIQ
KdGi+f4vYvvtmI1LmUY8dOmhHYw/Q+4Z6F1skR4+Ufgn+gCR5JlM8JEDFNG7HejC
MqDeHdGRSHhwVwxx7X4vqf4DkhoEkPrO6//J8SHJMHrAYl3a+DB/B6YA/7ok1qpx
aGSZBKXzh+O9fXksuoRqWMZRdWCP7m26sLCnaH0HzrfxxPnaCcBfNbV2zE/yqEUc
VeJcdcyT1q7ysx2C3YT5y/katPgwl6f2TpAwsnVNlkjlgp3g4ww5iIaIDEb/Wjbp
oKjD0uOb3onQ/PHqrkNMkmg+pAKJASUEGAECAA8FAlJVxK0CGwwFCRLMAwAACgkQ
J2DcSvj/syxaOgf/e5e/4OMSKY8/+aIQ7i4DWj+VSncNfixrbNjX4NH//Bg/UYRS
8b+TKgpEuR8uTslF+/BGCHncv5SQRy7fgFTejMJSRkBPwb8CzirWoo5bTvjEs2tp
4rSLLg1gM5+SdY4NinKEo9pH3fKxszQIMzk/z0rSK9JDhVBzfpQXAEEd1pdMo+t3
JETDfjWhRAuFcE/6nFeVGTGwQn0dX/lQ9xxxhx+/K4PYAx1mYKsIFPtj9Y3C3uIg
Bl0yUJx3nJUTCBO4Wunn60UI/WRix9HcGhf/kbfF/IILuZoTSodvKYUxwcJ/iAAj
ObMKV7f7yqGEQNpyrXlHl4qGSzkvgxQ6IzTA1g==
=DRiu
-----END PGP PRIVATE KEY BLOCK-----"""
},
verify : {
key : """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
mQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk
5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt
GWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp
ukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1
wdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B
1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq
dWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4
uY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0
clTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4
ggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft
vNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB
tBxNYXggS3JvaG4gPHRoZW1heEBnbWFpbC5jb20+iQI+BBMBAgAoBQJST0/PAhsv
BQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBjhHtLg5MPDEV6EADG
dMwseeQ9ie+zjRx9F8yAM9vMKMQXA36Tqb1CdgT35hVfGNxut2I87O0CkECbQ8xl
jicUt2GmGIDO/hw124yM6sui2FH8rxiiWHVfKEIq/rF3mZTzKJhs2Bv//+JFfWAE
vAmWfdhZPptHuRoN47VfK60KP49BwbFwTV3QOdoe99eFmuDJvW5KTlXEk+Ib9uZY
ipQL1R7zlh1ivjP+b7/WkptE1adbzyC/N3ghcgZUD5lWYh7kNibx5zA01gOMLBSX
umtIOoI4ksf6b+M0Os4ADeyO+BiGbEbPfpuigrFQvKIhUj7lYwe5BlwLwxIag8WL
D+Nlcot5x7EulonbjF5PzLKmC9mW2p1QnseSPS3rYTmYkpBzIQxvcBgfqcbuMEhR
kFCuMMS1esARRLhKcGe9GWwztMYAVJUFtFuwe9Th43gvK66lbrkaIh1gfRnFW5vx
rNjY0zddM39WFUo7WCfEr3bYbZAoSMEbayz1SDZu2noMRsETVaiVccknw1FNRLXx
0n+HVAb7pWqcHOgodrrwA3kuCA8QdgMYF1aJAgzmEH4q8NtggaRQNqfDsGcDToYw
AjGxzrQRJ/xIIct3PSamBTfiDVbFiY2y0LS0Jc2Uj0ptPfvlWRaxM6CHwxt7rcyi
ZPzW1cj9+z6eC3pmlJoNoxLx5jj3V1ZxYvIvA7tZ6bkCDQRST0/PARAA09+Bpd24
5vd46Dh+Qwro43f+3KQbjsZGJuWbMSmu8JTAePPclJtU6bFxbjbz1hahXJISRVu7
4FIN5grqytX7/RI6WbtSQ9vVftWZ2xzThK+RSz/nwxv4GzMpEUWAX7HJ6bqkogkO
7g4lV9H4r8lF21Tpcx5FfKYJIJZcix1Ac6LMZKuRJoT81jm057iWa8WQ/CWDxA9Y
2X/CeEAsjBQxwr59T2NR51DNpSri9OFjX44rpCIcdBHEzWODPDyDtyfp8p+UMUwv
Sd0ihaJ5ER9hbbU5Fm+n0GJSgcND3oyfeKOhlsr32yxYfQfVhQdlq30h/nAqso9Q
syy8/AY51srDfHGc6NXFcc8C7M9+vjWnjOlr+iWvaBWsNChPjXWLmeEKevcqs1br
pMmnkwhqhCT+B6z6hEAfXYjFaLVihqtraRikIAZUfUJSUmalvmtYpEHAcAGf7C0r
M6aQ9PwkFNbqTleC5OxYWG2hrNCPWgDY/M1/NxnB64+XTdbk+3hTAhgY6+QvkkFq
MQ9ReRcwv/t9ixHg2mjyPZmBOSCjdK23BKqUoT9C7mpQQ8ibM5XxC1rOS63QVuwM
tvFao0k9movsNdqcUhX+oouPYxfiNluZV6GLWP/DobqEYdmwOCOTjWkibNeg8JfO
89S1GZTtPs4kVEhZPOE8oqMpMDyi5i1D3+UAEQEAAYkERAQYAQIADwUCUk9PzwIb
LgUJB4YfgAIpCRBjhHtLg5MPDMFdIAQZAQIABgUCUk9PzwAKCRAv4BxFQ0jaOTmM
EACp8FZ+7f7C0knvVrx2O1u2NwYsUUcoE7XZIVZGgvlqFmSfEYMF5TPHettMetWh
wMQosIaORU3P+5qAelhT8lDHz1lhFTX8L2JMC/iPwwtYw3cKUJTHke8XSuwzlNqu
sqTfcc8/Qn49TSEymtl+tPciqKDDSnRPnUgNIiCN4WEcvTglx40LHQ00CuDj0Rao
KNNmVTupC8MGtzWPXb7ZtRlBYBCKJoBZzfKozmimXCHCqddRw76g6rAScPesNJxE
hvNe/3ZM3hL2vYI0s6zIy8n2hqI9Qn4312qJusSf6V6IMwkss/v8sTseGigMmH2R
1hX/as0ZO8S2y78Fy1OK9bZ2G5mTKI1ovKi7ba0xtudl5cbozpDM8GPwtkCAQ1ca
y/FyUwBH3CfATSdSbdx/nnZgSJyplU+xMEl/glMRY5iTvnLH1+oZnJN40lxvmVKZ
OHe3PDsB0ECBNa9kHY/LRGbnMAOwKUPKBGu42YiMeAAsVbNSgBb+smQj1qq1813c
B3FO+t4u7kuDcr0aM+ged5d8IiAbRrHP8gQduidCOe7/HRluW6FIZVs9TVxv41FY
HFj5c7/4D6zAYOZ77Pc8uT+HlXwZLcrXHOq1uiBalU5CEK0oIYxgP/IFitJZdDdL
TuKd2rsNuJnnrTn6qJyw0FIf8cxChTCTKFPCterCmhp3jo84EAC87mBws7GMAI9G
F9e9uBVTp7K5lskjBNq+vZMR0dpXBfLbci7dchqk5jPv9eChR5O+VsW8/CKY5OPJ
qYBjhqnxr3d65ywnNIs6j8Ty1P0UCCtjom6lnsipJ+BPoe1nyMyFkDCJxRiiE0nl
/qvQ3gmq/kTlkbd112denN0M3xReUryvmH1fH8QqTI6y2BlMRIJfDWShEUUqV3J4
jah5WR8mIgGv2UEBvK4OJrtHkIzEgKkLYJFijiHS1Jnc4S6aXHliKEaYPXXtU1Om
BzWxYSbkTDtZ98KoWs+OzNfT4+gu4wHbH98tPOUlq/ryEbeFeNv+29ngRIx9FNQx
QY4TiYD00vF2ifCwC/FVWQ0ybyiufago1h0hnvdu5x6pw3h811cWFuPcbN1M0opp
GajvutV2PEoXx7NIHsg8F+++eVwqmLKcw3EJw6AFNBzs7lFFiAzzV/PGoRRW/D/c
0QqTitcuFJ66xzueImZp+oKfjmO1gEsNg15P4iQjpWCFmpdi3Fzq4NsIDjzpBMWq
mNuq4W0HeVlK6RXv8IcySE+sFCCsqtDEhSBY68aepbCwlFz2kuAvr+jbuT0BTKA5
yh4J89ZwGA87CFabOeXtqeyS9z7ux5xKATv1bXoE9GuG5X5PsdNr3Awr1RAufdLH
nMd8vYZjDx7ro+5buf2cPmeiYlJdKQ==
=UGvW
-----END PGP PUBLIC KEY BLOCK-----
"""
}
}
}
#===============================================================
load_keyring = (T,cb) ->
ring = new PgpKeyRing()
asp = new ASP {}
opts = now: testing_unixtime
await KeyManager.import_from_armored_pgp { raw : data.keys.decryption.key, asp, opts }, defer err, dkm
T.no_error err
T.waypoint "imported decryption key"
await dkm.unlock_pgp { passphrase : data.keys.decryption.passphrase }, defer err
T.no_error err
T.waypoint "unlocked decryption key"
await KeyManager.import_from_armored_pgp { raw : data.keys.verify.key, asp, opts }, defer err, vkm
T.no_error err
T.waypoint "imported verification key"
ring.add_key_manager vkm
ring.add_key_manager dkm
cb ring
#===============================================================
ring = null
exports.init = (T,cb) ->
await load_keyring T, defer tmp
ring = tmp
cb()
#===============================================================
exports.run_test_msg_0 = (T, cb) ->
[err,msg] = armor.decode data.msgs[0]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
[err, packets] = parse msg.body
T.no_error err
T.waypoint "parsed incoming message"
await load_keyring T, defer ring
dkey = ring.lookup packets[0].key_id
T.assert dkey?, "found the right decryption key"
await dkey.key.decrypt_and_unpad packets[0].ekey, {}, defer err, sesskey
T.no_error err
T.waypoint "decrypted the session key"
cipher = import_key_pgp sesskey
await decrypt { cipher, ciphertext : packets[1].ciphertext }, defer err, pt
T.no_error err
T.waypoint "decrypted the message using the session key"
[err, packets] = parse pt
T.no_error err
T.waypoint "parsed the decrypted message body"
await packets[0].inflate defer err, res
T.no_error err
T.waypoint "inflated the compressed message body"
[err, packets] = parse res
T.no_error err
T.waypoint "parsed the inflated message body"
vkey = ring.lookup packets[0].key_id
T.assert vkey?, "found the right verification key"
packets[2].key = vkey.key
await packets[2].verify [ packets[1] ], defer err
T.no_error err
T.waypoint "signature verified properly"
ind = packets[1].toString().indexOf 'Buffer "cats1122", "utf8"'
T.assert (ind > 0), "found some text we expected"
cb()
#===============================================================
exports.process_msg_0 = (T,cb) ->
[err,msg] = armor.decode data.msgs[0]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf 'Buffer "cats1122", "utf8"'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_msg_1 = (T,cb) ->
[err,msg] = armor.decode data.msgs[1]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert not literals[0].get_data_signer(), "was not signed"
cb()
#===============================================================
exports.process_msg_2 = (T,cb) ->
[err,msg] = armor.decode data.msgs[2]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_msg_3 = (T,cb) ->
await do_message { armored : data.msgs[2] , keyfetch : ring, now : testing_unixtime }, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_corrupted_armor = (T,cb) ->
await do_message { armored : data.msgs[3] , keyfetch : ring }, defer err, literals
T.assert err?, "got a bad armor error"
T.assert err.toString().indexOf('bad PGP armor'), "got the right error"
cb()
#===============================================================
| 203318 | testing_unixtime = Math.floor(new Date(2013, 10, 24)/1000)
{parse} = require '../../lib/openpgp/parser'
armor = require '../../lib/openpgp/armor'
C = require '../../lib/const'
{do_message,Message} = require '../../lib/openpgp/processor'
util = require 'util'
{katch,ASP} = require '../../lib/util'
{KeyManager} = require '../../'
{import_key_pgp} = require '../../lib/symmetric'
{decrypt} = require '../../lib/openpgp/ocfb'
{PgpKeyRing} = require '../../lib/keyring'
data = {
msgs : [
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
-----END PGP MESSAGE-----""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>AbUUGfU
o7cJyIX4q4MjzvkYEjxxnw==
=S4AK
-----END PGP MESSAGE-----
""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
+<KEY>
=kOKo
-----END PGP MESSAGE-----""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
<KEY>
-----END PGP MESSAGE-----""" ],
keys : {
decryption: {
passphrase : "<PASSWORD>",
key : """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
lQO+BFJVxK0BCAC<KEY>
-----END PGP PRIVATE KEY BLOCK-----"""
},
verify : {
key : """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
}
}
}
#===============================================================
load_keyring = (T,cb) ->
ring = new PgpKeyRing()
asp = new ASP {}
opts = now: testing_unixtime
await KeyManager.import_from_armored_pgp { raw : data.keys.decryption.key, asp, opts }, defer err, dkm
T.no_error err
T.waypoint "imported decryption key"
await dkm.unlock_pgp { passphrase : data.keys.decryption.passphrase }, defer err
T.no_error err
T.waypoint "unlocked decryption key"
await KeyManager.import_from_armored_pgp { raw : data.keys.verify.key, asp, opts }, defer err, vkm
T.no_error err
T.waypoint "imported verification key"
ring.add_key_manager vkm
ring.add_key_manager dkm
cb ring
#===============================================================
ring = null
exports.init = (T,cb) ->
await load_keyring T, defer tmp
ring = tmp
cb()
#===============================================================
exports.run_test_msg_0 = (T, cb) ->
[err,msg] = armor.decode data.msgs[0]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
[err, packets] = parse msg.body
T.no_error err
T.waypoint "parsed incoming message"
await load_keyring T, defer ring
dkey = ring.lookup packets[0].key_id
T.assert dkey?, "found the right decryption key"
await dkey.key.decrypt_and_unpad packets[0].ekey, {}, defer err, sesskey
T.no_error err
T.waypoint "decrypted the session key"
cipher = import_key_pgp sesskey
await decrypt { cipher, ciphertext : packets[1].ciphertext }, defer err, pt
T.no_error err
T.waypoint "decrypted the message using the session key"
[err, packets] = parse pt
T.no_error err
T.waypoint "parsed the decrypted message body"
await packets[0].inflate defer err, res
T.no_error err
T.waypoint "inflated the compressed message body"
[err, packets] = parse res
T.no_error err
T.waypoint "parsed the inflated message body"
vkey = ring.lookup packets[0].key_id
T.assert vkey?, "found the right verification key"
packets[2].key = vkey.key
await packets[2].verify [ packets[1] ], defer err
T.no_error err
T.waypoint "signature verified properly"
ind = packets[1].toString().indexOf 'Buffer "cats1122", "utf8"'
T.assert (ind > 0), "found some text we expected"
cb()
#===============================================================
exports.process_msg_0 = (T,cb) ->
[err,msg] = armor.decode data.msgs[0]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf 'Buffer "cats1122", "utf8"'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_msg_1 = (T,cb) ->
[err,msg] = armor.decode data.msgs[1]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert not literals[0].get_data_signer(), "was not signed"
cb()
#===============================================================
exports.process_msg_2 = (T,cb) ->
[err,msg] = armor.decode data.msgs[2]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_msg_3 = (T,cb) ->
await do_message { armored : data.msgs[2] , keyfetch : ring, now : testing_unixtime }, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_corrupted_armor = (T,cb) ->
await do_message { armored : data.msgs[3] , keyfetch : ring }, defer err, literals
T.assert err?, "got a bad armor error"
T.assert err.toString().indexOf('bad PGP armor'), "got the right error"
cb()
#===============================================================
| true | testing_unixtime = Math.floor(new Date(2013, 10, 24)/1000)
{parse} = require '../../lib/openpgp/parser'
armor = require '../../lib/openpgp/armor'
C = require '../../lib/const'
{do_message,Message} = require '../../lib/openpgp/processor'
util = require 'util'
{katch,ASP} = require '../../lib/util'
{KeyManager} = require '../../'
{import_key_pgp} = require '../../lib/symmetric'
{decrypt} = require '../../lib/openpgp/ocfb'
{PgpKeyRing} = require '../../lib/keyring'
data = {
msgs : [
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PIAbUUGfU
o7cJyIX4q4MjzvkYEjxxnw==
=S4AK
-----END PGP MESSAGE-----
""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
+PI:KEY:<KEY>END_PI
=kOKo
-----END PGP MESSAGE-----""",
"""-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - https://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----""" ],
keys : {
decryption: {
passphrase : "PI:PASSWORD:<PASSWORD>END_PI",
key : """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
lQO+BFJVxK0BCACPI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----"""
},
verify : {
key : """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
}
}
}
#===============================================================
load_keyring = (T,cb) ->
ring = new PgpKeyRing()
asp = new ASP {}
opts = now: testing_unixtime
await KeyManager.import_from_armored_pgp { raw : data.keys.decryption.key, asp, opts }, defer err, dkm
T.no_error err
T.waypoint "imported decryption key"
await dkm.unlock_pgp { passphrase : data.keys.decryption.passphrase }, defer err
T.no_error err
T.waypoint "unlocked decryption key"
await KeyManager.import_from_armored_pgp { raw : data.keys.verify.key, asp, opts }, defer err, vkm
T.no_error err
T.waypoint "imported verification key"
ring.add_key_manager vkm
ring.add_key_manager dkm
cb ring
#===============================================================
ring = null
exports.init = (T,cb) ->
await load_keyring T, defer tmp
ring = tmp
cb()
#===============================================================
exports.run_test_msg_0 = (T, cb) ->
[err,msg] = armor.decode data.msgs[0]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
[err, packets] = parse msg.body
T.no_error err
T.waypoint "parsed incoming message"
await load_keyring T, defer ring
dkey = ring.lookup packets[0].key_id
T.assert dkey?, "found the right decryption key"
await dkey.key.decrypt_and_unpad packets[0].ekey, {}, defer err, sesskey
T.no_error err
T.waypoint "decrypted the session key"
cipher = import_key_pgp sesskey
await decrypt { cipher, ciphertext : packets[1].ciphertext }, defer err, pt
T.no_error err
T.waypoint "decrypted the message using the session key"
[err, packets] = parse pt
T.no_error err
T.waypoint "parsed the decrypted message body"
await packets[0].inflate defer err, res
T.no_error err
T.waypoint "inflated the compressed message body"
[err, packets] = parse res
T.no_error err
T.waypoint "parsed the inflated message body"
vkey = ring.lookup packets[0].key_id
T.assert vkey?, "found the right verification key"
packets[2].key = vkey.key
await packets[2].verify [ packets[1] ], defer err
T.no_error err
T.waypoint "signature verified properly"
ind = packets[1].toString().indexOf 'Buffer "cats1122", "utf8"'
T.assert (ind > 0), "found some text we expected"
cb()
#===============================================================
exports.process_msg_0 = (T,cb) ->
[err,msg] = armor.decode data.msgs[0]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf 'Buffer "cats1122", "utf8"'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_msg_1 = (T,cb) ->
[err,msg] = armor.decode data.msgs[1]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert not literals[0].get_data_signer(), "was not signed"
cb()
#===============================================================
exports.process_msg_2 = (T,cb) ->
[err,msg] = armor.decode data.msgs[2]
T.no_error err
T.equal msg.type, C.openpgp.message_types.generic, "Got a generic message type"
proc = new Message { keyfetch : ring, now : testing_unixtime }
await proc.parse_and_process msg, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_msg_3 = (T,cb) ->
await do_message { armored : data.msgs[2] , keyfetch : ring, now : testing_unixtime }, defer err, literals
T.no_error err
ind = literals[0].toString().indexOf '"devDependencies" : {'
T.assert (ind > 0), "found some text we expected"
T.assert literals[0].get_data_signer(), "was signed"
cb()
#===============================================================
exports.process_corrupted_armor = (T,cb) ->
await do_message { armored : data.msgs[3] , keyfetch : ring }, defer err, literals
T.assert err?, "got a bad armor error"
T.assert err.toString().indexOf('bad PGP armor'), "got the right error"
cb()
#===============================================================
|
[
{
"context": " @setBody \"About\"\n @_setViewProperty \"title\", \"Balázs Pete\"\n @_setViewProperty 'collapse', false, false\n\n",
"end": 150,
"score": 0.9998742341995239,
"start": 139,
"tag": "NAME",
"value": "Balázs Pete"
},
{
"context": " }\n {\n id: \"responsabilities_scisoc\"\n title: \"Webmaster\"\n descrip",
"end": 7065,
"score": 0.5460101962089539,
"start": 7063,
"tag": "USERNAME",
"value": "is"
},
{
"context": " id: \"responsabilities_scisoc\"\n title: \"Webmaster\"\n description: \"Senior-Committee\"\n ",
"end": 7096,
"score": 0.7182378768920898,
"start": 7087,
"tag": "NAME",
"value": "Webmaster"
}
] | models/AboutModel.coffee | balazspete/eliendrae.net | 0 |
Model = require './index'
class AboutModel extends Model
_setup: ->
super()
@setBody "About"
@_setViewProperty "title", "Balázs Pete"
@_setViewProperty 'collapse', false, false
@add "education", {
section: "education"
structure: [
{
id: "education_tcd"
title: "MSc in Computer Science"
description: "Mobile and Ubiquitous Computing"
subtext: "Trinity College, University of Dublin"
date: "2013 - 2014"
details: [
"Studied networks, distributed systems, information architecture, and HCI in mobile contexts to follow my interests in mobile and personal computing."
"The course was very intensive, however it taught me a lot, not just about mobile and ubiquitous computing, but about team and project management, scheduling, and managing workload."
]
skills: ["Distributed systems", "Networks", "Computer vision", "Mobile and Autonomous Systems", "Human-Computer Interaction", "Real-time and Embedded Systems", "Context Awareness", "Information Architecture"]
at: true
collapse: false
}
{
id: "education_ucd"
title: "BSc in Computer Science"
description: "2.1 honours"
subtext: "University College Dublin"
date: "2009 - 2013"
details: ["Studied machine learning and artificial intelligence in final year"]
at: true
}
{
id: "education_ib"
title: "International Baccalaureate"
description: "and Leaving Certificate"
subtext: "St Andrews College, Dublin"
date: "2007 - 2009"
details: ["Completed the International Baccalaureate and Maths HL and Hungarian in the Leaving Certificate"]
at: true
}
]
}
@add "experience", {
section: "experience"
structure: [
{
id: "sap-dev-bi-aa"
title: "Developer"
description: "Advanced Analytics, Line of Business Apps Integration Team"
subtext: "SAP Ireland, SAP AppHaus, Citywest Business Campus, Ireland"
date: "Current"
details: [
"I am part of the team responsible for embedding Advanced Analytics and predictive capabilities to different SAP line of business products.",
"In addition to assisting teams in finding out what and developing the best integration solution for their application, we are developing utilities that facilitate these integration tasks, such as simplified APIs and tools, along with other unified solutions to the management of predictive scenarios that are available right within SAP HANA. The ultimate goal is to make SAP's predictive functionality seamlessly available to the end business user."
]
}
{
id: "experience_sf2013"
title: "Intern"
description: "Software Development Engineer"
subtext: "ServiceFrame Limited, NovaUCD, Belfield"
date: "Summer 2013"
details: [
"Throughout the internship, I was tasked with automating tests and set up continuous integration. Building on these, I had to implement a system, working together with another intern, capable to automatically build, test, and deploy solutions either on schedule or on demand.",
"My other duties involved the migration of customer data from the old environment to the new version of the solution. In addition, I have gained additional experience in web development, Node.js, and unit testing."
]
at: true
}
{
id: "experience_sf2012"
title: "Intern"
description: "Solutions Analyst"
subtext: "ServiceFrame Limited, NovaUCD, Belfield"
date: "Summer 2012"
details: [
"I have had the chance to work in a startup environment, where I worked with experts in the field of web development, working on a large scale web based data analytics tool. I was tasked with both front and back end development, including interface design and feature development. I also had the chance to design and develop some of the product’s REST API end points.",
"I also had insight into product testing, agile development techniques and working collaboratively with team members."
]
at: true
}
{
id: "experience_ucdsci"
title: "Intern"
description: "Research in Multi-agent Systems"
subtext: "School of Computer Science, University College Dublin"
date: "Summer 2011"
details: [
"I was involved in a team of lecturers and post graduates developing several strategies for a multi agent programming competition. I had the chance to learn a lot about the multi-agent systems, how these systems work and how to improve existing strategies.",
"I also had the chance to develop different strategies based on my ideas. The team published a paper, detailing the proceedings of the project."
]
at: true
}
]
}
@add "responsibilities", {
section: "responsibilities"
structure: [
{
id: "responsabilities_tcdgsu"
title: "Class and School Representative"
description: ""
subtext: "Trinity College Dublin Graduate Students' Union"
date: "2013 - 2014"
at: true
details: [
"I have represented the Mobile and Ubiquitous Computing class at Students' Union and course meetings.",
"I have also represented the Students' Union on several committees of the School of Computer Science and Statistics."
]
}
{
id: "responsabilities_netsoc"
title: "Auditor"
description: "Chair of the Committee"
subtext: "UCD Netsoc (Internet and Computer Science Society)"
date: "2012 - 2013"
details: ["I was in charge of and responsible for the UCD Internet and Computer Science Society.",
"""My duties included<br>
- overseeing the day to day operations of the Society,<br>
- management of the Committee,<br>
- management of the members,<br>
- ensure the presence of communication within the committee and between the committee and the members,<br>
- make contact with companies within the Industry and find sponsorship and other opportunities,<br>
- act as a liaison between the college and the Society,<br>
- be a member of the Societies Council and have an impact on the decision of the representatives of the student body.""",
"""Throughout my time as the Auditor of the Society, we have<br>
- achieved a significant increase in both interest in the society and the number of members,<br>
- established relationships with companies from the Industry,<br>
- received several sponsorships,<br>
- ensured the future activity of the Society."""]
at: true
}
{
id: "responsabilities_scisoc"
title: "Webmaster"
description: "Senior-Committee"
subtext: "UCD Science Society"
date: "2011 - 2012"
details: ["I was elected to the position of webmaster of UCD Science Society. I have developed the society's website to help the committee to easily track and manage their important information.", " I was also involved in the running of the society, organising and managing events. These responsibilities helped me learn how to communicate and manage people on a large scale."]
at: true
}
]
}
@add "achievements", {
section: "achievements"
structure: [
{
id: "achievements_nwerc"
title: "Team member"
description: "Team BSD"
subtext: "North-Western European Regional Programming Competition 2012"
date: "November 2012"
details: ["Participated in the regional competition, held in the Netherlands, along with two other team members."]
}
{
id: "achievements_ucdsci"
title: "Winner"
description: ""
subtext: "UCD SCI Programming Competition"
date: "March 2012"
details: ["A day long programming competition where I competed using Ruby."]
}
]
}
@add "skills", {
section: "skills"
structure: [
{ name: "JavaScript", class: "big" }
{ name: "Swift", class: "big" }
{ name: "Java", class: "big" }
{ name: "Ruby", class: "medium" }
{ name: "CoffeeScript", class: "medium" }
{ name: "Objective-C", class: "medium" }
{ name: "C++", class: "medium" }
{ name: "Shell", class: "small" }
{ name: "iOS", class: "big" }
{ name: "Android", class: "big" }
{ name: "HTML", class: "medium" }
{ name: "CSS", class: "big" }
{ name: "Node.js", class: "big" }
{ name: "Arduino", class: "medium" }
{ name: "Software Development", class: "big" }
{ name: "Git", class: "big" }
{ name: "NoSQL", class: "medium" }
{ name: "SAP HANA", class: "big" }
{ name: "Object Oriented Design", class: "medium" }
{ name: "Linked data", class: "small" }
{ name: "jQuery", class: "medium" }
{ name: "SPARQL", class: "small" }
{ name: "Embedded Systems", class: "medium" }
{ name: "Web development", class: "big" }
{ name: "Agile development", class: "medium" }
{ name: "Scrum", class: "medium" }
{ name: "Test-driven development", class: "small" }
{ name: "Machine learning", class: "medium" }
]
}
module.exports = AboutModel
| 170087 |
Model = require './index'
class AboutModel extends Model
_setup: ->
super()
@setBody "About"
@_setViewProperty "title", "<NAME>"
@_setViewProperty 'collapse', false, false
@add "education", {
section: "education"
structure: [
{
id: "education_tcd"
title: "MSc in Computer Science"
description: "Mobile and Ubiquitous Computing"
subtext: "Trinity College, University of Dublin"
date: "2013 - 2014"
details: [
"Studied networks, distributed systems, information architecture, and HCI in mobile contexts to follow my interests in mobile and personal computing."
"The course was very intensive, however it taught me a lot, not just about mobile and ubiquitous computing, but about team and project management, scheduling, and managing workload."
]
skills: ["Distributed systems", "Networks", "Computer vision", "Mobile and Autonomous Systems", "Human-Computer Interaction", "Real-time and Embedded Systems", "Context Awareness", "Information Architecture"]
at: true
collapse: false
}
{
id: "education_ucd"
title: "BSc in Computer Science"
description: "2.1 honours"
subtext: "University College Dublin"
date: "2009 - 2013"
details: ["Studied machine learning and artificial intelligence in final year"]
at: true
}
{
id: "education_ib"
title: "International Baccalaureate"
description: "and Leaving Certificate"
subtext: "St Andrews College, Dublin"
date: "2007 - 2009"
details: ["Completed the International Baccalaureate and Maths HL and Hungarian in the Leaving Certificate"]
at: true
}
]
}
@add "experience", {
section: "experience"
structure: [
{
id: "sap-dev-bi-aa"
title: "Developer"
description: "Advanced Analytics, Line of Business Apps Integration Team"
subtext: "SAP Ireland, SAP AppHaus, Citywest Business Campus, Ireland"
date: "Current"
details: [
"I am part of the team responsible for embedding Advanced Analytics and predictive capabilities to different SAP line of business products.",
"In addition to assisting teams in finding out what and developing the best integration solution for their application, we are developing utilities that facilitate these integration tasks, such as simplified APIs and tools, along with other unified solutions to the management of predictive scenarios that are available right within SAP HANA. The ultimate goal is to make SAP's predictive functionality seamlessly available to the end business user."
]
}
{
id: "experience_sf2013"
title: "Intern"
description: "Software Development Engineer"
subtext: "ServiceFrame Limited, NovaUCD, Belfield"
date: "Summer 2013"
details: [
"Throughout the internship, I was tasked with automating tests and set up continuous integration. Building on these, I had to implement a system, working together with another intern, capable to automatically build, test, and deploy solutions either on schedule or on demand.",
"My other duties involved the migration of customer data from the old environment to the new version of the solution. In addition, I have gained additional experience in web development, Node.js, and unit testing."
]
at: true
}
{
id: "experience_sf2012"
title: "Intern"
description: "Solutions Analyst"
subtext: "ServiceFrame Limited, NovaUCD, Belfield"
date: "Summer 2012"
details: [
"I have had the chance to work in a startup environment, where I worked with experts in the field of web development, working on a large scale web based data analytics tool. I was tasked with both front and back end development, including interface design and feature development. I also had the chance to design and develop some of the product’s REST API end points.",
"I also had insight into product testing, agile development techniques and working collaboratively with team members."
]
at: true
}
{
id: "experience_ucdsci"
title: "Intern"
description: "Research in Multi-agent Systems"
subtext: "School of Computer Science, University College Dublin"
date: "Summer 2011"
details: [
"I was involved in a team of lecturers and post graduates developing several strategies for a multi agent programming competition. I had the chance to learn a lot about the multi-agent systems, how these systems work and how to improve existing strategies.",
"I also had the chance to develop different strategies based on my ideas. The team published a paper, detailing the proceedings of the project."
]
at: true
}
]
}
@add "responsibilities", {
section: "responsibilities"
structure: [
{
id: "responsabilities_tcdgsu"
title: "Class and School Representative"
description: ""
subtext: "Trinity College Dublin Graduate Students' Union"
date: "2013 - 2014"
at: true
details: [
"I have represented the Mobile and Ubiquitous Computing class at Students' Union and course meetings.",
"I have also represented the Students' Union on several committees of the School of Computer Science and Statistics."
]
}
{
id: "responsabilities_netsoc"
title: "Auditor"
description: "Chair of the Committee"
subtext: "UCD Netsoc (Internet and Computer Science Society)"
date: "2012 - 2013"
details: ["I was in charge of and responsible for the UCD Internet and Computer Science Society.",
"""My duties included<br>
- overseeing the day to day operations of the Society,<br>
- management of the Committee,<br>
- management of the members,<br>
- ensure the presence of communication within the committee and between the committee and the members,<br>
- make contact with companies within the Industry and find sponsorship and other opportunities,<br>
- act as a liaison between the college and the Society,<br>
- be a member of the Societies Council and have an impact on the decision of the representatives of the student body.""",
"""Throughout my time as the Auditor of the Society, we have<br>
- achieved a significant increase in both interest in the society and the number of members,<br>
- established relationships with companies from the Industry,<br>
- received several sponsorships,<br>
- ensured the future activity of the Society."""]
at: true
}
{
id: "responsabilities_scisoc"
title: "<NAME>"
description: "Senior-Committee"
subtext: "UCD Science Society"
date: "2011 - 2012"
details: ["I was elected to the position of webmaster of UCD Science Society. I have developed the society's website to help the committee to easily track and manage their important information.", " I was also involved in the running of the society, organising and managing events. These responsibilities helped me learn how to communicate and manage people on a large scale."]
at: true
}
]
}
@add "achievements", {
section: "achievements"
structure: [
{
id: "achievements_nwerc"
title: "Team member"
description: "Team BSD"
subtext: "North-Western European Regional Programming Competition 2012"
date: "November 2012"
details: ["Participated in the regional competition, held in the Netherlands, along with two other team members."]
}
{
id: "achievements_ucdsci"
title: "Winner"
description: ""
subtext: "UCD SCI Programming Competition"
date: "March 2012"
details: ["A day long programming competition where I competed using Ruby."]
}
]
}
@add "skills", {
section: "skills"
structure: [
{ name: "JavaScript", class: "big" }
{ name: "Swift", class: "big" }
{ name: "Java", class: "big" }
{ name: "Ruby", class: "medium" }
{ name: "CoffeeScript", class: "medium" }
{ name: "Objective-C", class: "medium" }
{ name: "C++", class: "medium" }
{ name: "Shell", class: "small" }
{ name: "iOS", class: "big" }
{ name: "Android", class: "big" }
{ name: "HTML", class: "medium" }
{ name: "CSS", class: "big" }
{ name: "Node.js", class: "big" }
{ name: "Arduino", class: "medium" }
{ name: "Software Development", class: "big" }
{ name: "Git", class: "big" }
{ name: "NoSQL", class: "medium" }
{ name: "SAP HANA", class: "big" }
{ name: "Object Oriented Design", class: "medium" }
{ name: "Linked data", class: "small" }
{ name: "jQuery", class: "medium" }
{ name: "SPARQL", class: "small" }
{ name: "Embedded Systems", class: "medium" }
{ name: "Web development", class: "big" }
{ name: "Agile development", class: "medium" }
{ name: "Scrum", class: "medium" }
{ name: "Test-driven development", class: "small" }
{ name: "Machine learning", class: "medium" }
]
}
module.exports = AboutModel
| true |
Model = require './index'
class AboutModel extends Model
_setup: ->
super()
@setBody "About"
@_setViewProperty "title", "PI:NAME:<NAME>END_PI"
@_setViewProperty 'collapse', false, false
@add "education", {
section: "education"
structure: [
{
id: "education_tcd"
title: "MSc in Computer Science"
description: "Mobile and Ubiquitous Computing"
subtext: "Trinity College, University of Dublin"
date: "2013 - 2014"
details: [
"Studied networks, distributed systems, information architecture, and HCI in mobile contexts to follow my interests in mobile and personal computing."
"The course was very intensive, however it taught me a lot, not just about mobile and ubiquitous computing, but about team and project management, scheduling, and managing workload."
]
skills: ["Distributed systems", "Networks", "Computer vision", "Mobile and Autonomous Systems", "Human-Computer Interaction", "Real-time and Embedded Systems", "Context Awareness", "Information Architecture"]
at: true
collapse: false
}
{
id: "education_ucd"
title: "BSc in Computer Science"
description: "2.1 honours"
subtext: "University College Dublin"
date: "2009 - 2013"
details: ["Studied machine learning and artificial intelligence in final year"]
at: true
}
{
id: "education_ib"
title: "International Baccalaureate"
description: "and Leaving Certificate"
subtext: "St Andrews College, Dublin"
date: "2007 - 2009"
details: ["Completed the International Baccalaureate and Maths HL and Hungarian in the Leaving Certificate"]
at: true
}
]
}
@add "experience", {
section: "experience"
structure: [
{
id: "sap-dev-bi-aa"
title: "Developer"
description: "Advanced Analytics, Line of Business Apps Integration Team"
subtext: "SAP Ireland, SAP AppHaus, Citywest Business Campus, Ireland"
date: "Current"
details: [
"I am part of the team responsible for embedding Advanced Analytics and predictive capabilities to different SAP line of business products.",
"In addition to assisting teams in finding out what and developing the best integration solution for their application, we are developing utilities that facilitate these integration tasks, such as simplified APIs and tools, along with other unified solutions to the management of predictive scenarios that are available right within SAP HANA. The ultimate goal is to make SAP's predictive functionality seamlessly available to the end business user."
]
}
{
id: "experience_sf2013"
title: "Intern"
description: "Software Development Engineer"
subtext: "ServiceFrame Limited, NovaUCD, Belfield"
date: "Summer 2013"
details: [
"Throughout the internship, I was tasked with automating tests and set up continuous integration. Building on these, I had to implement a system, working together with another intern, capable to automatically build, test, and deploy solutions either on schedule or on demand.",
"My other duties involved the migration of customer data from the old environment to the new version of the solution. In addition, I have gained additional experience in web development, Node.js, and unit testing."
]
at: true
}
{
id: "experience_sf2012"
title: "Intern"
description: "Solutions Analyst"
subtext: "ServiceFrame Limited, NovaUCD, Belfield"
date: "Summer 2012"
details: [
"I have had the chance to work in a startup environment, where I worked with experts in the field of web development, working on a large scale web based data analytics tool. I was tasked with both front and back end development, including interface design and feature development. I also had the chance to design and develop some of the product’s REST API end points.",
"I also had insight into product testing, agile development techniques and working collaboratively with team members."
]
at: true
}
{
id: "experience_ucdsci"
title: "Intern"
description: "Research in Multi-agent Systems"
subtext: "School of Computer Science, University College Dublin"
date: "Summer 2011"
details: [
"I was involved in a team of lecturers and post graduates developing several strategies for a multi agent programming competition. I had the chance to learn a lot about the multi-agent systems, how these systems work and how to improve existing strategies.",
"I also had the chance to develop different strategies based on my ideas. The team published a paper, detailing the proceedings of the project."
]
at: true
}
]
}
@add "responsibilities", {
section: "responsibilities"
structure: [
{
id: "responsabilities_tcdgsu"
title: "Class and School Representative"
description: ""
subtext: "Trinity College Dublin Graduate Students' Union"
date: "2013 - 2014"
at: true
details: [
"I have represented the Mobile and Ubiquitous Computing class at Students' Union and course meetings.",
"I have also represented the Students' Union on several committees of the School of Computer Science and Statistics."
]
}
{
id: "responsabilities_netsoc"
title: "Auditor"
description: "Chair of the Committee"
subtext: "UCD Netsoc (Internet and Computer Science Society)"
date: "2012 - 2013"
details: ["I was in charge of and responsible for the UCD Internet and Computer Science Society.",
"""My duties included<br>
- overseeing the day to day operations of the Society,<br>
- management of the Committee,<br>
- management of the members,<br>
- ensure the presence of communication within the committee and between the committee and the members,<br>
- make contact with companies within the Industry and find sponsorship and other opportunities,<br>
- act as a liaison between the college and the Society,<br>
- be a member of the Societies Council and have an impact on the decision of the representatives of the student body.""",
"""Throughout my time as the Auditor of the Society, we have<br>
- achieved a significant increase in both interest in the society and the number of members,<br>
- established relationships with companies from the Industry,<br>
- received several sponsorships,<br>
- ensured the future activity of the Society."""]
at: true
}
{
id: "responsabilities_scisoc"
title: "PI:NAME:<NAME>END_PI"
description: "Senior-Committee"
subtext: "UCD Science Society"
date: "2011 - 2012"
details: ["I was elected to the position of webmaster of UCD Science Society. I have developed the society's website to help the committee to easily track and manage their important information.", " I was also involved in the running of the society, organising and managing events. These responsibilities helped me learn how to communicate and manage people on a large scale."]
at: true
}
]
}
@add "achievements", {
section: "achievements"
structure: [
{
id: "achievements_nwerc"
title: "Team member"
description: "Team BSD"
subtext: "North-Western European Regional Programming Competition 2012"
date: "November 2012"
details: ["Participated in the regional competition, held in the Netherlands, along with two other team members."]
}
{
id: "achievements_ucdsci"
title: "Winner"
description: ""
subtext: "UCD SCI Programming Competition"
date: "March 2012"
details: ["A day long programming competition where I competed using Ruby."]
}
]
}
@add "skills", {
section: "skills"
structure: [
{ name: "JavaScript", class: "big" }
{ name: "Swift", class: "big" }
{ name: "Java", class: "big" }
{ name: "Ruby", class: "medium" }
{ name: "CoffeeScript", class: "medium" }
{ name: "Objective-C", class: "medium" }
{ name: "C++", class: "medium" }
{ name: "Shell", class: "small" }
{ name: "iOS", class: "big" }
{ name: "Android", class: "big" }
{ name: "HTML", class: "medium" }
{ name: "CSS", class: "big" }
{ name: "Node.js", class: "big" }
{ name: "Arduino", class: "medium" }
{ name: "Software Development", class: "big" }
{ name: "Git", class: "big" }
{ name: "NoSQL", class: "medium" }
{ name: "SAP HANA", class: "big" }
{ name: "Object Oriented Design", class: "medium" }
{ name: "Linked data", class: "small" }
{ name: "jQuery", class: "medium" }
{ name: "SPARQL", class: "small" }
{ name: "Embedded Systems", class: "medium" }
{ name: "Web development", class: "big" }
{ name: "Agile development", class: "medium" }
{ name: "Scrum", class: "medium" }
{ name: "Test-driven development", class: "small" }
{ name: "Machine learning", class: "medium" }
]
}
module.exports = AboutModel
|
[
{
"context": "client-side module.\n#\n# :copyright: (c) 2012 by Zaur Nasibov.\n# :license: MIT, see LICENSE for more details",
"end": 144,
"score": 0.9998751282691956,
"start": 132,
"tag": "NAME",
"value": "Zaur Nasibov"
},
{
"context": " ->\n kl._app = {\n ## data\n name : name\n config : null\n mode : null # a",
"end": 2000,
"score": 0.5520386695861816,
"start": 1996,
"tag": "NAME",
"value": "name"
}
] | kaylee/client/kaylee.coffee | BasicWolf/archived-kaylee | 2 | ###
# kaylee.coffee
# ~~~~~~~~~~~~~
#
# This is the base file of Kaylee client-side module.
#
# :copyright: (c) 2012 by Zaur Nasibov.
# :license: MIT, see LICENSE for more details.
###
## Variables and interfaces defined in Kaylee namespace:
# kl.node_id : null
# kl._app :
# name : null # str
# config : null # {}
# worker : null # Worker object
# subscribed : false
# task : null # current task data
# CONSTANTS #
#-----------#
SESSION_DATA_ATTRIBUTE = '__kl_session_data__'
WORKER_SCRIPT_URL = ((scripts) ->
scripts = document.getElementsByTagName('script')
script = scripts[scripts.length - 1]
if not script.getAttribute.length?
path = script.src
# replace 'http://path/to/kaylee.js' with 'http://path/to/klworker.js'
path = script.getAttribute('src', -1)
return path[..path.lastIndexOf('/')] + 'klworker.js'
)()
kl._app = null
kl.api =
register : () ->
kl.get("/kaylee/register",
kl.node_registered.trigger,
kl.server_error.trigger)
return
subscribe : (name) ->
kl.post("/kaylee/apps/#{name}/subscribe/#{kl.node_id}",
null,
kl.node_subscribed.trigger,
kl.server_error.trigger)
return
get_action : () ->
kl.get("/kaylee/actions/#{kl.node_id}",
kl.action_received.trigger,
kl.server_error.trigger)
return
send_result : (result) ->
kl.post("/kaylee/actions/#{kl.node_id}", result,
((action_data) ->
kl.result_sent.trigger(result)
kl.action_received.trigger(action_data)
),
kl._preliminary_server_error_handler
)
return
kl.register = () ->
kl.instance.is_unique(
kl.api.register,
() -> kl.error("Another Kaylee instance is already running"))
return
kl.subscribe = (name) ->
kl._app = {
## data
name : name
config : null
mode : null # a shortcut to config.__kl_project_mode__
worker : null
subscribed : false
task : null # current task data
## functions
# assigned when project is being imported
process_task : () -> ;
}
kl.api.subscribe(name)
return
kl.get_action = () ->
if kl._app.subscribed == true
kl.api.get_action()
return
kl.send_result = (data) ->
if not data?
kl.error('Cannot send data: the value is empty.')
if typeof(data) != 'object'
kl.error('The returned result is not a JS object.')
# before sending the result, check whether app.task contains
# session data and attach it
if SESSION_DATA_ATTRIBUTE of kl._app.task
data[SESSION_DATA_ATTRIBUTE] = \
kl._app.task[SESSION_DATA_ATTRIBUTE]
kl.api.send_result(data)
kl._app.task = null
return
kl._message_to_worker = (msg, data = {}) ->
kl._app.worker.postMessage({'msg' : msg, 'data' : data})
return
kl._preliminary_server_error_handler = (err) ->
switch(err)
when 'INVALID_STATE_ERR'
@get_action() if kl._app.subscribed == true
kl.server_error.trigger(err)
return
# Primary event handlers
on_node_registered = (data) ->
for key, val of data.config
kl.config[key] = val
kl.node_id = data.node_id
return
on_node_subscribed = (config) ->
app = kl._app
app.config = config
app.mode = config.__kl_project_mode__
switch config.__kl_project_mode__
when kl.AUTO_PROJECT_MODE
app.worker.terminate() if app.worker?
worker = new Worker(WORKER_SCRIPT_URL)
app.worker = worker
worker.onmessage = (e) ->
worker_message_handler(e)
worker.onerror = (e) ->
msg = "Line #{e.lineno} in #{e.filename}: #{e.message}"
kl.error(msg)
kl._message_to_worker('import_project', {
'kl_config' : kl.config,
'app_config' : app.config,
})
when kl.MANUAL_PROJECT_MODE
include_urls = [config.__kl_project_script_url__]
if config.__kl_project_styles__
include_urls.push(config.__kl_project_styles__)
kl.include(include_urls,
() -> pj.init(app.config)
)
else
kl.error('Unknown Kaylee Project mode')
return
on_node_unsubscibed = (data) ->
kl._app.worker?.terminate()
kl._app = null
kl.pj = null
return
on_project_imported = () ->
kl._app.subscribed = true
switch kl._app.mode
when kl.AUTO_PROJECT_MODE
kl._app.process_task = (data) ->
kl._message_to_worker('process_task', data)
when kl.MANUAL_PROJECT_MODE
kl._app.process_task = pj.process_task
kl.get_action()
return
on_action_received = (action) ->
switch action.action
when 'task' then kl.task_received.trigger(action.data)
when 'unsubscribe' then kl.node_unsubscibed.trigger(action.data)
else kl.error("Unknown action: #{action.action}")
return
on_task_received = (task) ->
kl._app.task = task
kl._app.process_task(task)
return
on_task_completed = (result) ->
if kl._app? and kl._app.task? and kl._app.subscribed == true
kl.send_result(result)
return
# Kaylee worker event handlers
worker_message_handler = (event) ->
data = event.data
msg = data.msg
mdata = data.data
switch msg
when '__kl_log__' then kl.log(mdata)
when '__kl_error__' then kl.error(mdata)
when 'project_imported' then kl.project_imported.trigger()
when 'task_completed' then kl.task_completed.trigger(mdata)
return
kl.log = (msg) ->
console.log('Kaylee: ' + msg)
kl.message_logged.trigger(msg)
kl.error = (msg) ->
kl.log("ERROR: #{msg}")
throw new kl.KayleeError(msg)
# Kaylee events
kl.node_registered = new Event(on_node_registered)
kl.node_subscribed = new Event(on_node_subscribed)
kl.node_unsubscibed = new Event(on_node_unsubscibed)
kl.project_imported = new Event(on_project_imported)
kl.action_received = new Event(on_action_received)
kl.task_received = new Event(on_task_received)
kl.task_completed = new Event(on_task_completed)
kl.result_sent = new Event()
kl.message_logged = new Event()
kl.server_error = new Event() | 172788 | ###
# kaylee.coffee
# ~~~~~~~~~~~~~
#
# This is the base file of Kaylee client-side module.
#
# :copyright: (c) 2012 by <NAME>.
# :license: MIT, see LICENSE for more details.
###
## Variables and interfaces defined in Kaylee namespace:
# kl.node_id : null
# kl._app :
# name : null # str
# config : null # {}
# worker : null # Worker object
# subscribed : false
# task : null # current task data
# CONSTANTS #
#-----------#
SESSION_DATA_ATTRIBUTE = '__kl_session_data__'
WORKER_SCRIPT_URL = ((scripts) ->
scripts = document.getElementsByTagName('script')
script = scripts[scripts.length - 1]
if not script.getAttribute.length?
path = script.src
# replace 'http://path/to/kaylee.js' with 'http://path/to/klworker.js'
path = script.getAttribute('src', -1)
return path[..path.lastIndexOf('/')] + 'klworker.js'
)()
kl._app = null
kl.api =
register : () ->
kl.get("/kaylee/register",
kl.node_registered.trigger,
kl.server_error.trigger)
return
subscribe : (name) ->
kl.post("/kaylee/apps/#{name}/subscribe/#{kl.node_id}",
null,
kl.node_subscribed.trigger,
kl.server_error.trigger)
return
get_action : () ->
kl.get("/kaylee/actions/#{kl.node_id}",
kl.action_received.trigger,
kl.server_error.trigger)
return
send_result : (result) ->
kl.post("/kaylee/actions/#{kl.node_id}", result,
((action_data) ->
kl.result_sent.trigger(result)
kl.action_received.trigger(action_data)
),
kl._preliminary_server_error_handler
)
return
kl.register = () ->
kl.instance.is_unique(
kl.api.register,
() -> kl.error("Another Kaylee instance is already running"))
return
kl.subscribe = (name) ->
kl._app = {
## data
name : <NAME>
config : null
mode : null # a shortcut to config.__kl_project_mode__
worker : null
subscribed : false
task : null # current task data
## functions
# assigned when project is being imported
process_task : () -> ;
}
kl.api.subscribe(name)
return
kl.get_action = () ->
if kl._app.subscribed == true
kl.api.get_action()
return
kl.send_result = (data) ->
if not data?
kl.error('Cannot send data: the value is empty.')
if typeof(data) != 'object'
kl.error('The returned result is not a JS object.')
# before sending the result, check whether app.task contains
# session data and attach it
if SESSION_DATA_ATTRIBUTE of kl._app.task
data[SESSION_DATA_ATTRIBUTE] = \
kl._app.task[SESSION_DATA_ATTRIBUTE]
kl.api.send_result(data)
kl._app.task = null
return
kl._message_to_worker = (msg, data = {}) ->
kl._app.worker.postMessage({'msg' : msg, 'data' : data})
return
kl._preliminary_server_error_handler = (err) ->
switch(err)
when 'INVALID_STATE_ERR'
@get_action() if kl._app.subscribed == true
kl.server_error.trigger(err)
return
# Primary event handlers
on_node_registered = (data) ->
for key, val of data.config
kl.config[key] = val
kl.node_id = data.node_id
return
on_node_subscribed = (config) ->
app = kl._app
app.config = config
app.mode = config.__kl_project_mode__
switch config.__kl_project_mode__
when kl.AUTO_PROJECT_MODE
app.worker.terminate() if app.worker?
worker = new Worker(WORKER_SCRIPT_URL)
app.worker = worker
worker.onmessage = (e) ->
worker_message_handler(e)
worker.onerror = (e) ->
msg = "Line #{e.lineno} in #{e.filename}: #{e.message}"
kl.error(msg)
kl._message_to_worker('import_project', {
'kl_config' : kl.config,
'app_config' : app.config,
})
when kl.MANUAL_PROJECT_MODE
include_urls = [config.__kl_project_script_url__]
if config.__kl_project_styles__
include_urls.push(config.__kl_project_styles__)
kl.include(include_urls,
() -> pj.init(app.config)
)
else
kl.error('Unknown Kaylee Project mode')
return
on_node_unsubscibed = (data) ->
kl._app.worker?.terminate()
kl._app = null
kl.pj = null
return
on_project_imported = () ->
kl._app.subscribed = true
switch kl._app.mode
when kl.AUTO_PROJECT_MODE
kl._app.process_task = (data) ->
kl._message_to_worker('process_task', data)
when kl.MANUAL_PROJECT_MODE
kl._app.process_task = pj.process_task
kl.get_action()
return
on_action_received = (action) ->
switch action.action
when 'task' then kl.task_received.trigger(action.data)
when 'unsubscribe' then kl.node_unsubscibed.trigger(action.data)
else kl.error("Unknown action: #{action.action}")
return
on_task_received = (task) ->
kl._app.task = task
kl._app.process_task(task)
return
on_task_completed = (result) ->
if kl._app? and kl._app.task? and kl._app.subscribed == true
kl.send_result(result)
return
# Kaylee worker event handlers
worker_message_handler = (event) ->
data = event.data
msg = data.msg
mdata = data.data
switch msg
when '__kl_log__' then kl.log(mdata)
when '__kl_error__' then kl.error(mdata)
when 'project_imported' then kl.project_imported.trigger()
when 'task_completed' then kl.task_completed.trigger(mdata)
return
kl.log = (msg) ->
console.log('Kaylee: ' + msg)
kl.message_logged.trigger(msg)
kl.error = (msg) ->
kl.log("ERROR: #{msg}")
throw new kl.KayleeError(msg)
# Kaylee events
kl.node_registered = new Event(on_node_registered)
kl.node_subscribed = new Event(on_node_subscribed)
kl.node_unsubscibed = new Event(on_node_unsubscibed)
kl.project_imported = new Event(on_project_imported)
kl.action_received = new Event(on_action_received)
kl.task_received = new Event(on_task_received)
kl.task_completed = new Event(on_task_completed)
kl.result_sent = new Event()
kl.message_logged = new Event()
kl.server_error = new Event() | true | ###
# kaylee.coffee
# ~~~~~~~~~~~~~
#
# This is the base file of Kaylee client-side module.
#
# :copyright: (c) 2012 by PI:NAME:<NAME>END_PI.
# :license: MIT, see LICENSE for more details.
###
## Variables and interfaces defined in Kaylee namespace:
# kl.node_id : null
# kl._app :
# name : null # str
# config : null # {}
# worker : null # Worker object
# subscribed : false
# task : null # current task data
# CONSTANTS #
#-----------#
SESSION_DATA_ATTRIBUTE = '__kl_session_data__'
WORKER_SCRIPT_URL = ((scripts) ->
scripts = document.getElementsByTagName('script')
script = scripts[scripts.length - 1]
if not script.getAttribute.length?
path = script.src
# replace 'http://path/to/kaylee.js' with 'http://path/to/klworker.js'
path = script.getAttribute('src', -1)
return path[..path.lastIndexOf('/')] + 'klworker.js'
)()
kl._app = null
kl.api =
register : () ->
kl.get("/kaylee/register",
kl.node_registered.trigger,
kl.server_error.trigger)
return
subscribe : (name) ->
kl.post("/kaylee/apps/#{name}/subscribe/#{kl.node_id}",
null,
kl.node_subscribed.trigger,
kl.server_error.trigger)
return
get_action : () ->
kl.get("/kaylee/actions/#{kl.node_id}",
kl.action_received.trigger,
kl.server_error.trigger)
return
send_result : (result) ->
kl.post("/kaylee/actions/#{kl.node_id}", result,
((action_data) ->
kl.result_sent.trigger(result)
kl.action_received.trigger(action_data)
),
kl._preliminary_server_error_handler
)
return
kl.register = () ->
kl.instance.is_unique(
kl.api.register,
() -> kl.error("Another Kaylee instance is already running"))
return
kl.subscribe = (name) ->
kl._app = {
## data
name : PI:NAME:<NAME>END_PI
config : null
mode : null # a shortcut to config.__kl_project_mode__
worker : null
subscribed : false
task : null # current task data
## functions
# assigned when project is being imported
process_task : () -> ;
}
kl.api.subscribe(name)
return
kl.get_action = () ->
if kl._app.subscribed == true
kl.api.get_action()
return
kl.send_result = (data) ->
if not data?
kl.error('Cannot send data: the value is empty.')
if typeof(data) != 'object'
kl.error('The returned result is not a JS object.')
# before sending the result, check whether app.task contains
# session data and attach it
if SESSION_DATA_ATTRIBUTE of kl._app.task
data[SESSION_DATA_ATTRIBUTE] = \
kl._app.task[SESSION_DATA_ATTRIBUTE]
kl.api.send_result(data)
kl._app.task = null
return
kl._message_to_worker = (msg, data = {}) ->
kl._app.worker.postMessage({'msg' : msg, 'data' : data})
return
kl._preliminary_server_error_handler = (err) ->
switch(err)
when 'INVALID_STATE_ERR'
@get_action() if kl._app.subscribed == true
kl.server_error.trigger(err)
return
# Primary event handlers
on_node_registered = (data) ->
for key, val of data.config
kl.config[key] = val
kl.node_id = data.node_id
return
on_node_subscribed = (config) ->
app = kl._app
app.config = config
app.mode = config.__kl_project_mode__
switch config.__kl_project_mode__
when kl.AUTO_PROJECT_MODE
app.worker.terminate() if app.worker?
worker = new Worker(WORKER_SCRIPT_URL)
app.worker = worker
worker.onmessage = (e) ->
worker_message_handler(e)
worker.onerror = (e) ->
msg = "Line #{e.lineno} in #{e.filename}: #{e.message}"
kl.error(msg)
kl._message_to_worker('import_project', {
'kl_config' : kl.config,
'app_config' : app.config,
})
when kl.MANUAL_PROJECT_MODE
include_urls = [config.__kl_project_script_url__]
if config.__kl_project_styles__
include_urls.push(config.__kl_project_styles__)
kl.include(include_urls,
() -> pj.init(app.config)
)
else
kl.error('Unknown Kaylee Project mode')
return
on_node_unsubscibed = (data) ->
kl._app.worker?.terminate()
kl._app = null
kl.pj = null
return
on_project_imported = () ->
kl._app.subscribed = true
switch kl._app.mode
when kl.AUTO_PROJECT_MODE
kl._app.process_task = (data) ->
kl._message_to_worker('process_task', data)
when kl.MANUAL_PROJECT_MODE
kl._app.process_task = pj.process_task
kl.get_action()
return
on_action_received = (action) ->
switch action.action
when 'task' then kl.task_received.trigger(action.data)
when 'unsubscribe' then kl.node_unsubscibed.trigger(action.data)
else kl.error("Unknown action: #{action.action}")
return
on_task_received = (task) ->
kl._app.task = task
kl._app.process_task(task)
return
on_task_completed = (result) ->
if kl._app? and kl._app.task? and kl._app.subscribed == true
kl.send_result(result)
return
# Kaylee worker event handlers
worker_message_handler = (event) ->
data = event.data
msg = data.msg
mdata = data.data
switch msg
when '__kl_log__' then kl.log(mdata)
when '__kl_error__' then kl.error(mdata)
when 'project_imported' then kl.project_imported.trigger()
when 'task_completed' then kl.task_completed.trigger(mdata)
return
kl.log = (msg) ->
console.log('Kaylee: ' + msg)
kl.message_logged.trigger(msg)
kl.error = (msg) ->
kl.log("ERROR: #{msg}")
throw new kl.KayleeError(msg)
# Kaylee events
kl.node_registered = new Event(on_node_registered)
kl.node_subscribed = new Event(on_node_subscribed)
kl.node_unsubscibed = new Event(on_node_unsubscibed)
kl.project_imported = new Event(on_project_imported)
kl.action_received = new Event(on_action_received)
kl.task_received = new Event(on_task_received)
kl.task_completed = new Event(on_task_completed)
kl.result_sent = new Event()
kl.message_logged = new Event()
kl.server_error = new Event() |
[
{
"context": "bre\"\n contact: \"Contacto\"\n twitter_follow: \"Seguir\"\n\n forms:\n name: \"Nome\"\n email: \"E-mail\"\n ",
"end": 619,
"score": 0.9994664788246155,
"start": 613,
"tag": "USERNAME",
"value": "Seguir"
},
{
"context": "\"\n wizard_tab: \"Feiticeiro\"\n password_tab: \"Palavra-passe\"\n emails_tab: \"E-mails\"\n language_tab: \"Idi",
"end": 3810,
"score": 0.9987937808036804,
"start": 3797,
"tag": "PASSWORD",
"value": "Palavra-passe"
},
{
"context": "\"Cor das roupas do feiticeiro\"\n new_password: \"Nova palavra-passe\"\n new_password_verify: \"Verificar\"\n email_s",
"end": 4244,
"score": 0.999299168586731,
"start": 4226,
"tag": "PASSWORD",
"value": "Nova palavra-passe"
},
{
"context": "d: \"Nova palavra-passe\"\n new_password_verify: \"Verificar\"\n email_subscriptions: \"Subscrições de E-mail\"",
"end": 4281,
"score": 0.999324381351471,
"start": 4272,
"tag": "PASSWORD",
"value": "Verificar"
}
] | app/locale/pt-PT.coffee | cochee/codecombat | 1 | module.exports = nativeDescription: "Português europeu", englishDescription: "Portuguese (Portugal)", translation:
common:
loading: "A carregar..."
modal:
close: "Fechar"
okay: "Okay"
not_found:
page_not_found: "Página não encontrada"
nav:
# Header
sign_up: "Criar conta"
log_in: "Iniciar sessão"
log_out: "Terminar sessão"
play: "Jogar"
editor: "Editor"
blog: "Blog"
forum: "Fórum"
admin: "Administrador"
# Footer
home: "Início"
contribute: "Contribuir"
legal: "Legal"
about: "Sobre"
contact: "Contacto"
twitter_follow: "Seguir"
forms:
name: "Nome"
email: "E-mail"
message: "Mensagem"
cancel: "Cancelar"
login:
log_in: "Iniciar sessão"
sign_up: "criar nova conta"
or: ", ou "
recover: "recuperar conta"
signup:
description: "É grátis. Só precisamos de umas coisas e fica tudo pronto:"
email_announcements: "Receber anúncios por e-mail"
coppa: "13+ ou não-EUA "
coppa_why: "(Porquê?)"
creating: "A criar conta..."
sign_up: "Registar"
or: "ou "
log_in: "iniciar sessão com palavra-passe"
home:
slogan: "Aprende a Programar JavaScript ao Jogar um Jogo"
no_ie: "O CodeCombat não corre em Internet Explorer 9 ou anterior. Desculpa!"
no_mobile: "O CodeCombat não foi desenhado para dispositivos móveis e pode não funcionar!"
play: "Jogar"
play:
choose_your_level: "Escolhe o Teu Nível"
adventurer_prefix: "Podes saltar para um dos níveis abaixo, ou discutir os níveis "
adventurer_forum: "no fórum de Aventureiro"
adventurer_suffix: "."
campaign_beginner: "Campanha para Iniciantes"
campaign_beginner_description: "... onde aprendes a feitiçaria da programação."
campaign_dev: "Níveis mais Difíceis"
campaign_dev_description: "... onde aprendes a interface enquanto fazes coisas um bocadinho mais difíceis."
campaign_multiplayer: "Arenas Multijogador"
campaign_multiplayer_description: "... onde programas frente-a-frente contra outros jogadores."
campaign_player_created: "Criados por Jogadores"
campaign_player_created_description: "... onde combates contra a criatividade dos teus colegas <a href=\"/contribute#artisan\">Feiticeiros Artesãos</a>."
level_difficulty: "Dificuldade: "
contact:
contact_us: "Contactar o CodeCombat"
welcome: "É bom ter notícias tuas! Usa este formulário para nos enviares um e-mail."
contribute_prefix: "Se estás interessado em contribuir, dá uma olhadela à nossa "
contribute_page: "página de contribuição"
contribute_suffix: "!"
forum_prefix: "Para algo público, por favor, usa o "
forum_page: "nosso fórum"
forum_suffix: " como alternativa."
sending: "A enviar..."
send: "Enviar Feedback"
diplomat_suggestion:
title: "Ajuda a traduzir o CodeCombat!"
sub_heading: "Precisamos das tuas habilidades linguísticas."
pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores em todo o mundo. Muitos deles querem jogar em Português e não falam Inglês, por isso, se sabes falar ambas, por favor considera registares-te como Diplomata para ajudares a traduzir o website do CodeCombat e todos os níveis para Português."
missing_translations: "Enquanto não conseguimos traduzir tudo para Português, irás ver em Inglês o que não estiver disponível em Português."
learn_more: "Sabe mais sobre ser um Diplomata"
subscribe_as_diplomat: "Subscrever como Diplomata"
account_settings:
title: "Definições da Conta"
not_logged_in: "Inicia sessão ou cria uma conta para alterares as tuas definições."
autosave: "As alterações guardam-se automaticamente"
me_tab: "Eu"
picture_tab: "Fotografia"
wizard_tab: "Feiticeiro"
password_tab: "Palavra-passe"
emails_tab: "E-mails"
language_tab: "Idioma"
gravatar_select: "Seleciona qual fotografia Gravatar a usar"
gravatar_add_photos: "Adiciona miniaturas e fotografias a uma conta Gravatar com o teu email para escolheres uma imagem."
gravatar_add_more_photos: "Adiciona mais fotografias à tua conta Gravatar para as acederes aqui."
wizard_color: "Cor das roupas do feiticeiro"
new_password: "Nova palavra-passe"
new_password_verify: "Verificar"
email_subscriptions: "Subscrições de E-mail"
email_announcements: "Anúncios"
email_announcements_description: "Recebe e-mails sobre as últimas novidades e desenvolvimentos no CodeCombat."
contributor_emails: "E-mails para Contribuintes"
contribute_prefix: "Estamos à procura de pessoas para se juntarem a nós! Visita a "
contribute_page: "página de contribuição"
contribute_suffix: " para mais informação."
email_toggle: "Alternar todos"
language: "Idioma"
saving: "A guardar..."
error_saving: "Erro ao guardar"
saved: "Alterações guardadas"
password_mismatch: "As palavras-passe não coincidem."
account_profile:
edit_settings: "Editar Definições"
profile_for_prefix: "Perfil de "
profile_for_suffix: ""
profile: "Perfil"
user_not_found: "Nenhum utilizador encontrado. Verifica o URL?"
gravatar_not_found_mine: "Não conseguimos encontrar o teu perfil associado com:"
gravatar_signup_prefix: "Regista-te no "
gravatar_signup_suffix: " para começares!"
gravatar_not_found_other: "Infelizmente, não existe nenhum perfil associado ao endereço de e-mail desta pessoa."
gravatar_contact: "Contacto"
gravatar_websites: "Websites"
gravatar_accounts: "Como visto no"
gravatar_profile_link: "Perfil Gravatar completo"
play_level:
level_load_error: "O nível não pôde ser carregado."
done: "Concluir"
grid: "Grelha"
customize_wizard: "Personalizar Feiticeiro"
home: "Início"
guide: "Guia"
multiplayer: "Multijogador"
restart: "Reiniciar"
goals: "Objetivos"
action_timeline: "Linha do Tempo"
click_to_select: "Clica numa unidade para a selecionares."
reload_title: "Recarregar todo o código?"
reload_really: "Tens a certeza que queres recarregar este nível de volta ao início?"
reload_confirm: "Recarregar tudo"
victory_title_prefix: ""
victory_title_suffix: " Concluído"
# victory_sign_up: ""
# victory_sign_up_poke: ""
# victory_rate_the_level: ""
# victory_play_next_level: ""
# victory_go_home: ""
# victory_review: ""
# victory_hour_of_code_done: ""
# victory_hour_of_code_done_yes: ""
# multiplayer_title: ""
# multiplayer_link_description: ""
# multiplayer_hint_label: ""
# multiplayer_hint: ""
# multiplayer_coming_soon: ""
# guide_title: ""
# tome_minion_spells: ""
# tome_read_only_spells: ""
# tome_other_units: ""
# tome_cast_button_castable: ""
# tome_cast_button_casting: ""
# tome_cast_button_cast: ""
# tome_autocast_delay: ""
# tome_autocast_1: ""
# tome_autocast_3: ""
# tome_autocast_5: ""
# tome_autocast_manual: ""
# tome_select_spell: ""
# tome_select_a_thang: ""
# tome_available_spells: ""
# hud_continue: ""
| 116130 | module.exports = nativeDescription: "Português europeu", englishDescription: "Portuguese (Portugal)", translation:
common:
loading: "A carregar..."
modal:
close: "Fechar"
okay: "Okay"
not_found:
page_not_found: "Página não encontrada"
nav:
# Header
sign_up: "Criar conta"
log_in: "Iniciar sessão"
log_out: "Terminar sessão"
play: "Jogar"
editor: "Editor"
blog: "Blog"
forum: "Fórum"
admin: "Administrador"
# Footer
home: "Início"
contribute: "Contribuir"
legal: "Legal"
about: "Sobre"
contact: "Contacto"
twitter_follow: "Seguir"
forms:
name: "Nome"
email: "E-mail"
message: "Mensagem"
cancel: "Cancelar"
login:
log_in: "Iniciar sessão"
sign_up: "criar nova conta"
or: ", ou "
recover: "recuperar conta"
signup:
description: "É grátis. Só precisamos de umas coisas e fica tudo pronto:"
email_announcements: "Receber anúncios por e-mail"
coppa: "13+ ou não-EUA "
coppa_why: "(Porquê?)"
creating: "A criar conta..."
sign_up: "Registar"
or: "ou "
log_in: "iniciar sessão com palavra-passe"
home:
slogan: "Aprende a Programar JavaScript ao Jogar um Jogo"
no_ie: "O CodeCombat não corre em Internet Explorer 9 ou anterior. Desculpa!"
no_mobile: "O CodeCombat não foi desenhado para dispositivos móveis e pode não funcionar!"
play: "Jogar"
play:
choose_your_level: "Escolhe o Teu Nível"
adventurer_prefix: "Podes saltar para um dos níveis abaixo, ou discutir os níveis "
adventurer_forum: "no fórum de Aventureiro"
adventurer_suffix: "."
campaign_beginner: "Campanha para Iniciantes"
campaign_beginner_description: "... onde aprendes a feitiçaria da programação."
campaign_dev: "Níveis mais Difíceis"
campaign_dev_description: "... onde aprendes a interface enquanto fazes coisas um bocadinho mais difíceis."
campaign_multiplayer: "Arenas Multijogador"
campaign_multiplayer_description: "... onde programas frente-a-frente contra outros jogadores."
campaign_player_created: "Criados por Jogadores"
campaign_player_created_description: "... onde combates contra a criatividade dos teus colegas <a href=\"/contribute#artisan\">Feiticeiros Artesãos</a>."
level_difficulty: "Dificuldade: "
contact:
contact_us: "Contactar o CodeCombat"
welcome: "É bom ter notícias tuas! Usa este formulário para nos enviares um e-mail."
contribute_prefix: "Se estás interessado em contribuir, dá uma olhadela à nossa "
contribute_page: "página de contribuição"
contribute_suffix: "!"
forum_prefix: "Para algo público, por favor, usa o "
forum_page: "nosso fórum"
forum_suffix: " como alternativa."
sending: "A enviar..."
send: "Enviar Feedback"
diplomat_suggestion:
title: "Ajuda a traduzir o CodeCombat!"
sub_heading: "Precisamos das tuas habilidades linguísticas."
pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores em todo o mundo. Muitos deles querem jogar em Português e não falam Inglês, por isso, se sabes falar ambas, por favor considera registares-te como Diplomata para ajudares a traduzir o website do CodeCombat e todos os níveis para Português."
missing_translations: "Enquanto não conseguimos traduzir tudo para Português, irás ver em Inglês o que não estiver disponível em Português."
learn_more: "Sabe mais sobre ser um Diplomata"
subscribe_as_diplomat: "Subscrever como Diplomata"
account_settings:
title: "Definições da Conta"
not_logged_in: "Inicia sessão ou cria uma conta para alterares as tuas definições."
autosave: "As alterações guardam-se automaticamente"
me_tab: "Eu"
picture_tab: "Fotografia"
wizard_tab: "Feiticeiro"
password_tab: "<PASSWORD>"
emails_tab: "E-mails"
language_tab: "Idioma"
gravatar_select: "Seleciona qual fotografia Gravatar a usar"
gravatar_add_photos: "Adiciona miniaturas e fotografias a uma conta Gravatar com o teu email para escolheres uma imagem."
gravatar_add_more_photos: "Adiciona mais fotografias à tua conta Gravatar para as acederes aqui."
wizard_color: "Cor das roupas do feiticeiro"
new_password: "<PASSWORD>"
new_password_verify: "<PASSWORD>"
email_subscriptions: "Subscrições de E-mail"
email_announcements: "Anúncios"
email_announcements_description: "Recebe e-mails sobre as últimas novidades e desenvolvimentos no CodeCombat."
contributor_emails: "E-mails para Contribuintes"
contribute_prefix: "Estamos à procura de pessoas para se juntarem a nós! Visita a "
contribute_page: "página de contribuição"
contribute_suffix: " para mais informação."
email_toggle: "Alternar todos"
language: "Idioma"
saving: "A guardar..."
error_saving: "Erro ao guardar"
saved: "Alterações guardadas"
password_mismatch: "As palavras-passe não coincidem."
account_profile:
edit_settings: "Editar Definições"
profile_for_prefix: "Perfil de "
profile_for_suffix: ""
profile: "Perfil"
user_not_found: "Nenhum utilizador encontrado. Verifica o URL?"
gravatar_not_found_mine: "Não conseguimos encontrar o teu perfil associado com:"
gravatar_signup_prefix: "Regista-te no "
gravatar_signup_suffix: " para começares!"
gravatar_not_found_other: "Infelizmente, não existe nenhum perfil associado ao endereço de e-mail desta pessoa."
gravatar_contact: "Contacto"
gravatar_websites: "Websites"
gravatar_accounts: "Como visto no"
gravatar_profile_link: "Perfil Gravatar completo"
play_level:
level_load_error: "O nível não pôde ser carregado."
done: "Concluir"
grid: "Grelha"
customize_wizard: "Personalizar Feiticeiro"
home: "Início"
guide: "Guia"
multiplayer: "Multijogador"
restart: "Reiniciar"
goals: "Objetivos"
action_timeline: "Linha do Tempo"
click_to_select: "Clica numa unidade para a selecionares."
reload_title: "Recarregar todo o código?"
reload_really: "Tens a certeza que queres recarregar este nível de volta ao início?"
reload_confirm: "Recarregar tudo"
victory_title_prefix: ""
victory_title_suffix: " Concluído"
# victory_sign_up: ""
# victory_sign_up_poke: ""
# victory_rate_the_level: ""
# victory_play_next_level: ""
# victory_go_home: ""
# victory_review: ""
# victory_hour_of_code_done: ""
# victory_hour_of_code_done_yes: ""
# multiplayer_title: ""
# multiplayer_link_description: ""
# multiplayer_hint_label: ""
# multiplayer_hint: ""
# multiplayer_coming_soon: ""
# guide_title: ""
# tome_minion_spells: ""
# tome_read_only_spells: ""
# tome_other_units: ""
# tome_cast_button_castable: ""
# tome_cast_button_casting: ""
# tome_cast_button_cast: ""
# tome_autocast_delay: ""
# tome_autocast_1: ""
# tome_autocast_3: ""
# tome_autocast_5: ""
# tome_autocast_manual: ""
# tome_select_spell: ""
# tome_select_a_thang: ""
# tome_available_spells: ""
# hud_continue: ""
| true | module.exports = nativeDescription: "Português europeu", englishDescription: "Portuguese (Portugal)", translation:
common:
loading: "A carregar..."
modal:
close: "Fechar"
okay: "Okay"
not_found:
page_not_found: "Página não encontrada"
nav:
# Header
sign_up: "Criar conta"
log_in: "Iniciar sessão"
log_out: "Terminar sessão"
play: "Jogar"
editor: "Editor"
blog: "Blog"
forum: "Fórum"
admin: "Administrador"
# Footer
home: "Início"
contribute: "Contribuir"
legal: "Legal"
about: "Sobre"
contact: "Contacto"
twitter_follow: "Seguir"
forms:
name: "Nome"
email: "E-mail"
message: "Mensagem"
cancel: "Cancelar"
login:
log_in: "Iniciar sessão"
sign_up: "criar nova conta"
or: ", ou "
recover: "recuperar conta"
signup:
description: "É grátis. Só precisamos de umas coisas e fica tudo pronto:"
email_announcements: "Receber anúncios por e-mail"
coppa: "13+ ou não-EUA "
coppa_why: "(Porquê?)"
creating: "A criar conta..."
sign_up: "Registar"
or: "ou "
log_in: "iniciar sessão com palavra-passe"
home:
slogan: "Aprende a Programar JavaScript ao Jogar um Jogo"
no_ie: "O CodeCombat não corre em Internet Explorer 9 ou anterior. Desculpa!"
no_mobile: "O CodeCombat não foi desenhado para dispositivos móveis e pode não funcionar!"
play: "Jogar"
play:
choose_your_level: "Escolhe o Teu Nível"
adventurer_prefix: "Podes saltar para um dos níveis abaixo, ou discutir os níveis "
adventurer_forum: "no fórum de Aventureiro"
adventurer_suffix: "."
campaign_beginner: "Campanha para Iniciantes"
campaign_beginner_description: "... onde aprendes a feitiçaria da programação."
campaign_dev: "Níveis mais Difíceis"
campaign_dev_description: "... onde aprendes a interface enquanto fazes coisas um bocadinho mais difíceis."
campaign_multiplayer: "Arenas Multijogador"
campaign_multiplayer_description: "... onde programas frente-a-frente contra outros jogadores."
campaign_player_created: "Criados por Jogadores"
campaign_player_created_description: "... onde combates contra a criatividade dos teus colegas <a href=\"/contribute#artisan\">Feiticeiros Artesãos</a>."
level_difficulty: "Dificuldade: "
contact:
contact_us: "Contactar o CodeCombat"
welcome: "É bom ter notícias tuas! Usa este formulário para nos enviares um e-mail."
contribute_prefix: "Se estás interessado em contribuir, dá uma olhadela à nossa "
contribute_page: "página de contribuição"
contribute_suffix: "!"
forum_prefix: "Para algo público, por favor, usa o "
forum_page: "nosso fórum"
forum_suffix: " como alternativa."
sending: "A enviar..."
send: "Enviar Feedback"
diplomat_suggestion:
title: "Ajuda a traduzir o CodeCombat!"
sub_heading: "Precisamos das tuas habilidades linguísticas."
pitch_body: "Desenvolvemos o CodeCombat em Inglês, mas já temos jogadores em todo o mundo. Muitos deles querem jogar em Português e não falam Inglês, por isso, se sabes falar ambas, por favor considera registares-te como Diplomata para ajudares a traduzir o website do CodeCombat e todos os níveis para Português."
missing_translations: "Enquanto não conseguimos traduzir tudo para Português, irás ver em Inglês o que não estiver disponível em Português."
learn_more: "Sabe mais sobre ser um Diplomata"
subscribe_as_diplomat: "Subscrever como Diplomata"
account_settings:
title: "Definições da Conta"
not_logged_in: "Inicia sessão ou cria uma conta para alterares as tuas definições."
autosave: "As alterações guardam-se automaticamente"
me_tab: "Eu"
picture_tab: "Fotografia"
wizard_tab: "Feiticeiro"
password_tab: "PI:PASSWORD:<PASSWORD>END_PI"
emails_tab: "E-mails"
language_tab: "Idioma"
gravatar_select: "Seleciona qual fotografia Gravatar a usar"
gravatar_add_photos: "Adiciona miniaturas e fotografias a uma conta Gravatar com o teu email para escolheres uma imagem."
gravatar_add_more_photos: "Adiciona mais fotografias à tua conta Gravatar para as acederes aqui."
wizard_color: "Cor das roupas do feiticeiro"
new_password: "PI:PASSWORD:<PASSWORD>END_PI"
new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI"
email_subscriptions: "Subscrições de E-mail"
email_announcements: "Anúncios"
email_announcements_description: "Recebe e-mails sobre as últimas novidades e desenvolvimentos no CodeCombat."
contributor_emails: "E-mails para Contribuintes"
contribute_prefix: "Estamos à procura de pessoas para se juntarem a nós! Visita a "
contribute_page: "página de contribuição"
contribute_suffix: " para mais informação."
email_toggle: "Alternar todos"
language: "Idioma"
saving: "A guardar..."
error_saving: "Erro ao guardar"
saved: "Alterações guardadas"
password_mismatch: "As palavras-passe não coincidem."
account_profile:
edit_settings: "Editar Definições"
profile_for_prefix: "Perfil de "
profile_for_suffix: ""
profile: "Perfil"
user_not_found: "Nenhum utilizador encontrado. Verifica o URL?"
gravatar_not_found_mine: "Não conseguimos encontrar o teu perfil associado com:"
gravatar_signup_prefix: "Regista-te no "
gravatar_signup_suffix: " para começares!"
gravatar_not_found_other: "Infelizmente, não existe nenhum perfil associado ao endereço de e-mail desta pessoa."
gravatar_contact: "Contacto"
gravatar_websites: "Websites"
gravatar_accounts: "Como visto no"
gravatar_profile_link: "Perfil Gravatar completo"
play_level:
level_load_error: "O nível não pôde ser carregado."
done: "Concluir"
grid: "Grelha"
customize_wizard: "Personalizar Feiticeiro"
home: "Início"
guide: "Guia"
multiplayer: "Multijogador"
restart: "Reiniciar"
goals: "Objetivos"
action_timeline: "Linha do Tempo"
click_to_select: "Clica numa unidade para a selecionares."
reload_title: "Recarregar todo o código?"
reload_really: "Tens a certeza que queres recarregar este nível de volta ao início?"
reload_confirm: "Recarregar tudo"
victory_title_prefix: ""
victory_title_suffix: " Concluído"
# victory_sign_up: ""
# victory_sign_up_poke: ""
# victory_rate_the_level: ""
# victory_play_next_level: ""
# victory_go_home: ""
# victory_review: ""
# victory_hour_of_code_done: ""
# victory_hour_of_code_done_yes: ""
# multiplayer_title: ""
# multiplayer_link_description: ""
# multiplayer_hint_label: ""
# multiplayer_hint: ""
# multiplayer_coming_soon: ""
# guide_title: ""
# tome_minion_spells: ""
# tome_read_only_spells: ""
# tome_other_units: ""
# tome_cast_button_castable: ""
# tome_cast_button_casting: ""
# tome_cast_button_cast: ""
# tome_autocast_delay: ""
# tome_autocast_1: ""
# tome_autocast_3: ""
# tome_autocast_5: ""
# tome_autocast_manual: ""
# tome_select_spell: ""
# tome_select_a_thang: ""
# tome_available_spells: ""
# hud_continue: ""
|
[
{
"context": "#\n# Copyright 2011-2014 Carsten Klein\n#\n# Licensed under the Apache License, Version 2.",
"end": 37,
"score": 0.9998591542243958,
"start": 24,
"tag": "NAME",
"value": "Carsten Klein"
}
] | src/enum.coffee | vibejs/vibejs-enum | 0 | #
# Copyright 2011-2014 Carsten Klein
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# we always export globally
exports = window ? global
# guard preventing us from exporting twice
unless exports.enumerate?
# The class Enum models the root of a hierarchy of derived classes.
#
# @memberof vibejs.lang
class Enum
# Default constructor. Prevents instantiation of the class.
constructor : ->
throw new TypeError "enums cannot be instantiated and should not be inherited from."
# Returns the constant for either name or ordinal or null.
#
# @abstract
# @return enum constant or null
@valueOf : (value) ->
# Returns the enum constants as an array.
#
# @property
# @readonly
# @abstract
@values : null
# Recommendation only, logs a warning
ENUM_CLASS_NAME_RE = /^[$_]?E[A-Z][a-z]+(?:[A-Z][a-z]+)*[0-9]*$/
# Requirement.
ENUM_CONSTANT_NAME_RE = /^[A-Z_]+[A-Z_0-9]*$/
# counter used for creating unique enum names
anonymousEnumCount = 0
# The factory used for creating new enum classes.
#
# @param {} decl
# @option decl String name The name of the created enum class
# @option Object logger optional logger for debugging purposes (must have a debug() method)
# @option decl {} static static properties / methods of the created class
# @option decl {} constants
# @memberof vibejs.lang
exports.enumerate = (decl) ->
if not decl
throw new TypeError "required parameter decl is either missing or not an object."
# optional name
name = decl.name ? null
if name is null
name = "AnonEnum_#{anonymousEnumCount}"
anonymousEnumCount++
# set up optional debug logger
logger = decl.logger ? null
# dictionary used as ordinal/name to value mapping
dict = {}
values = []
class EnumImplBase extends Enum
constructor: (@name, @ordinal) ->
@valueOf : (value) ->
result = null
if value instanceof @
result = value
else if value of dict
result = dict[value]
result
Object.defineProperty @, 'values',
enumerable : true
configurable : false
value : ->
value for value in values
dynclass
name : name
base : EnumImplBase
freeze : true
ctor : ->
if Object.isFrozen @constructor
throw new TypeError "enums cannot be instantiated and must not be inherited from."
extend : (klass) ->
ord = 1
for key, spec of decl.extend
key = key.trim()
if null == ENUM_CONSTANT_NAME_RE.exec key
throw new Error "Constant literal must match production '#{ENUM_CONSTANT_NAME_RE}'."
newOrd = -1
if typeof spec is 'number'
newOrd = spec
else
throw new TypeError "Ordinal must be a number. (literal='#{key}', type='#{typeof spec}', value='#{spec}'"
ord = newOrd if newOrd > 0
if ord of dict
throw new TypeError "Duplicate ordinals. (ordinal='#{ord}', literal='#{dict[ord].name()}', duplicate='#{key}'.)"
instance = new klass key, ord
Object.freeze instance
dict[ord] = dict[key] = klass[key] = instance
values.push instance
ord += 1
if values.length == 0
throw new TypeError "Enums require at least one literal constant."
# @namespace vibejs.lang
namespace 'vibejs.lang',
configurable : false
extend :
Enum : Enum
enumerate : exports.enumerate
namespace 'vibejs.lang.constants',
configurable : false
extend :
ENUM_CLASS_NAME_RE : ENUM_CLASS_NAME_RE
ENUM_CONSTANT_NAME_RE : ENUM_CONSTANT_NAME_RE
| 207282 | #
# Copyright 2011-2014 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# we always export globally
exports = window ? global
# guard preventing us from exporting twice
unless exports.enumerate?
# The class Enum models the root of a hierarchy of derived classes.
#
# @memberof vibejs.lang
class Enum
# Default constructor. Prevents instantiation of the class.
constructor : ->
throw new TypeError "enums cannot be instantiated and should not be inherited from."
# Returns the constant for either name or ordinal or null.
#
# @abstract
# @return enum constant or null
@valueOf : (value) ->
# Returns the enum constants as an array.
#
# @property
# @readonly
# @abstract
@values : null
# Recommendation only, logs a warning
ENUM_CLASS_NAME_RE = /^[$_]?E[A-Z][a-z]+(?:[A-Z][a-z]+)*[0-9]*$/
# Requirement.
ENUM_CONSTANT_NAME_RE = /^[A-Z_]+[A-Z_0-9]*$/
# counter used for creating unique enum names
anonymousEnumCount = 0
# The factory used for creating new enum classes.
#
# @param {} decl
# @option decl String name The name of the created enum class
# @option Object logger optional logger for debugging purposes (must have a debug() method)
# @option decl {} static static properties / methods of the created class
# @option decl {} constants
# @memberof vibejs.lang
exports.enumerate = (decl) ->
if not decl
throw new TypeError "required parameter decl is either missing or not an object."
# optional name
name = decl.name ? null
if name is null
name = "AnonEnum_#{anonymousEnumCount}"
anonymousEnumCount++
# set up optional debug logger
logger = decl.logger ? null
# dictionary used as ordinal/name to value mapping
dict = {}
values = []
class EnumImplBase extends Enum
constructor: (@name, @ordinal) ->
@valueOf : (value) ->
result = null
if value instanceof @
result = value
else if value of dict
result = dict[value]
result
Object.defineProperty @, 'values',
enumerable : true
configurable : false
value : ->
value for value in values
dynclass
name : name
base : EnumImplBase
freeze : true
ctor : ->
if Object.isFrozen @constructor
throw new TypeError "enums cannot be instantiated and must not be inherited from."
extend : (klass) ->
ord = 1
for key, spec of decl.extend
key = key.trim()
if null == ENUM_CONSTANT_NAME_RE.exec key
throw new Error "Constant literal must match production '#{ENUM_CONSTANT_NAME_RE}'."
newOrd = -1
if typeof spec is 'number'
newOrd = spec
else
throw new TypeError "Ordinal must be a number. (literal='#{key}', type='#{typeof spec}', value='#{spec}'"
ord = newOrd if newOrd > 0
if ord of dict
throw new TypeError "Duplicate ordinals. (ordinal='#{ord}', literal='#{dict[ord].name()}', duplicate='#{key}'.)"
instance = new klass key, ord
Object.freeze instance
dict[ord] = dict[key] = klass[key] = instance
values.push instance
ord += 1
if values.length == 0
throw new TypeError "Enums require at least one literal constant."
# @namespace vibejs.lang
namespace 'vibejs.lang',
configurable : false
extend :
Enum : Enum
enumerate : exports.enumerate
namespace 'vibejs.lang.constants',
configurable : false
extend :
ENUM_CLASS_NAME_RE : ENUM_CLASS_NAME_RE
ENUM_CONSTANT_NAME_RE : ENUM_CONSTANT_NAME_RE
| true | #
# Copyright 2011-2014 PI:NAME:<NAME>END_PI
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# we always export globally
exports = window ? global
# guard preventing us from exporting twice
unless exports.enumerate?
# The class Enum models the root of a hierarchy of derived classes.
#
# @memberof vibejs.lang
class Enum
# Default constructor. Prevents instantiation of the class.
constructor : ->
throw new TypeError "enums cannot be instantiated and should not be inherited from."
# Returns the constant for either name or ordinal or null.
#
# @abstract
# @return enum constant or null
@valueOf : (value) ->
# Returns the enum constants as an array.
#
# @property
# @readonly
# @abstract
@values : null
# Recommendation only, logs a warning
ENUM_CLASS_NAME_RE = /^[$_]?E[A-Z][a-z]+(?:[A-Z][a-z]+)*[0-9]*$/
# Requirement.
ENUM_CONSTANT_NAME_RE = /^[A-Z_]+[A-Z_0-9]*$/
# counter used for creating unique enum names
anonymousEnumCount = 0
# The factory used for creating new enum classes.
#
# @param {} decl
# @option decl String name The name of the created enum class
# @option Object logger optional logger for debugging purposes (must have a debug() method)
# @option decl {} static static properties / methods of the created class
# @option decl {} constants
# @memberof vibejs.lang
exports.enumerate = (decl) ->
if not decl
throw new TypeError "required parameter decl is either missing or not an object."
# optional name
name = decl.name ? null
if name is null
name = "AnonEnum_#{anonymousEnumCount}"
anonymousEnumCount++
# set up optional debug logger
logger = decl.logger ? null
# dictionary used as ordinal/name to value mapping
dict = {}
values = []
class EnumImplBase extends Enum
constructor: (@name, @ordinal) ->
@valueOf : (value) ->
result = null
if value instanceof @
result = value
else if value of dict
result = dict[value]
result
Object.defineProperty @, 'values',
enumerable : true
configurable : false
value : ->
value for value in values
dynclass
name : name
base : EnumImplBase
freeze : true
ctor : ->
if Object.isFrozen @constructor
throw new TypeError "enums cannot be instantiated and must not be inherited from."
extend : (klass) ->
ord = 1
for key, spec of decl.extend
key = key.trim()
if null == ENUM_CONSTANT_NAME_RE.exec key
throw new Error "Constant literal must match production '#{ENUM_CONSTANT_NAME_RE}'."
newOrd = -1
if typeof spec is 'number'
newOrd = spec
else
throw new TypeError "Ordinal must be a number. (literal='#{key}', type='#{typeof spec}', value='#{spec}'"
ord = newOrd if newOrd > 0
if ord of dict
throw new TypeError "Duplicate ordinals. (ordinal='#{ord}', literal='#{dict[ord].name()}', duplicate='#{key}'.)"
instance = new klass key, ord
Object.freeze instance
dict[ord] = dict[key] = klass[key] = instance
values.push instance
ord += 1
if values.length == 0
throw new TypeError "Enums require at least one literal constant."
# @namespace vibejs.lang
namespace 'vibejs.lang',
configurable : false
extend :
Enum : Enum
enumerate : exports.enumerate
namespace 'vibejs.lang.constants',
configurable : false
extend :
ENUM_CLASS_NAME_RE : ENUM_CLASS_NAME_RE
ENUM_CONSTANT_NAME_RE : ENUM_CONSTANT_NAME_RE
|
[
{
"context": "{\n usernameField: 'email',\n passwordField: 'pass'\n}, (email, password, done) ->\n db.get 'SELECT",
"end": 1096,
"score": 0.9993141889572144,
"start": 1092,
"tag": "PASSWORD",
"value": "pass"
}
] | api/main.coffee | soulweaver91/gw2hub | 0 | express = require 'express'
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
expressSession = require 'express-session'
http = require 'http'
fs = require 'fs'
passport = require 'passport'
strategy = require('passport-local').Strategy
_ = require 'lodash'
settings = require('../configmanager').get()
security = require './tools/security'
gw2api = require './tools/gw2api'
sqlite = require 'sqlite3'
db = new sqlite.Database settings.database
db.exec "PRAGMA foreign_keys = ON;"
# Just initialize, don't care if it succeeded at this point - if it didn't, the key will be attempted later when it is
# truly needed. (unless the key was rejected, of course)
gw2api.init ->
app = express()
server = http.createServer app
# Add JSON, cookie, session and header layers to the server
app.use bodyParser.json()
app.use cookieParser()
app.use expressSession {
secret: settings.APISecret
saveUninitialized: true
resave: true
}
# Create the passport strategy to validate credentials
passport.use new strategy {
usernameField: 'email',
passwordField: 'pass'
}, (email, password, done) ->
db.get 'SELECT * FROM tUser WHERE email = ?', email, (err, row) ->
return done err if err?
return done null, false if !row?
security.compare password, row.pass, (err, res) ->
return done err if err?
return done null, false if !res
done null, _.omit row, ['pass']
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
db.get 'SELECT * FROM tUser WHERE id = ?', id, (err, row) ->
done err, _.omit row, ['pass']
# Add passport to the server
app.use passport.initialize()
app.use passport.session()
# Only allow connections from the defined UI server
app.use (req, res, next) ->
res.header "Access-Control-Allow-Origin", settings.siteAddress
res.header 'Access-Control-Allow-Credentials', true
next()
# Add all defined routes from the route directory
routes = fs.readdirSync './api/routes'
for file in routes
if file.match /.*\.coffee$/
route = require './routes/' + file
route app, db
exports = module.exports = server
exports.use = (args...) ->
app.use.apply app, args
| 47994 | express = require 'express'
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
expressSession = require 'express-session'
http = require 'http'
fs = require 'fs'
passport = require 'passport'
strategy = require('passport-local').Strategy
_ = require 'lodash'
settings = require('../configmanager').get()
security = require './tools/security'
gw2api = require './tools/gw2api'
sqlite = require 'sqlite3'
db = new sqlite.Database settings.database
db.exec "PRAGMA foreign_keys = ON;"
# Just initialize, don't care if it succeeded at this point - if it didn't, the key will be attempted later when it is
# truly needed. (unless the key was rejected, of course)
gw2api.init ->
app = express()
server = http.createServer app
# Add JSON, cookie, session and header layers to the server
app.use bodyParser.json()
app.use cookieParser()
app.use expressSession {
secret: settings.APISecret
saveUninitialized: true
resave: true
}
# Create the passport strategy to validate credentials
passport.use new strategy {
usernameField: 'email',
passwordField: '<PASSWORD>'
}, (email, password, done) ->
db.get 'SELECT * FROM tUser WHERE email = ?', email, (err, row) ->
return done err if err?
return done null, false if !row?
security.compare password, row.pass, (err, res) ->
return done err if err?
return done null, false if !res
done null, _.omit row, ['pass']
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
db.get 'SELECT * FROM tUser WHERE id = ?', id, (err, row) ->
done err, _.omit row, ['pass']
# Add passport to the server
app.use passport.initialize()
app.use passport.session()
# Only allow connections from the defined UI server
app.use (req, res, next) ->
res.header "Access-Control-Allow-Origin", settings.siteAddress
res.header 'Access-Control-Allow-Credentials', true
next()
# Add all defined routes from the route directory
routes = fs.readdirSync './api/routes'
for file in routes
if file.match /.*\.coffee$/
route = require './routes/' + file
route app, db
exports = module.exports = server
exports.use = (args...) ->
app.use.apply app, args
| true | express = require 'express'
bodyParser = require 'body-parser'
cookieParser = require 'cookie-parser'
expressSession = require 'express-session'
http = require 'http'
fs = require 'fs'
passport = require 'passport'
strategy = require('passport-local').Strategy
_ = require 'lodash'
settings = require('../configmanager').get()
security = require './tools/security'
gw2api = require './tools/gw2api'
sqlite = require 'sqlite3'
db = new sqlite.Database settings.database
db.exec "PRAGMA foreign_keys = ON;"
# Just initialize, don't care if it succeeded at this point - if it didn't, the key will be attempted later when it is
# truly needed. (unless the key was rejected, of course)
gw2api.init ->
app = express()
server = http.createServer app
# Add JSON, cookie, session and header layers to the server
app.use bodyParser.json()
app.use cookieParser()
app.use expressSession {
secret: settings.APISecret
saveUninitialized: true
resave: true
}
# Create the passport strategy to validate credentials
passport.use new strategy {
usernameField: 'email',
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
}, (email, password, done) ->
db.get 'SELECT * FROM tUser WHERE email = ?', email, (err, row) ->
return done err if err?
return done null, false if !row?
security.compare password, row.pass, (err, res) ->
return done err if err?
return done null, false if !res
done null, _.omit row, ['pass']
passport.serializeUser (user, done) ->
done null, user.id
passport.deserializeUser (id, done) ->
db.get 'SELECT * FROM tUser WHERE id = ?', id, (err, row) ->
done err, _.omit row, ['pass']
# Add passport to the server
app.use passport.initialize()
app.use passport.session()
# Only allow connections from the defined UI server
app.use (req, res, next) ->
res.header "Access-Control-Allow-Origin", settings.siteAddress
res.header 'Access-Control-Allow-Credentials', true
next()
# Add all defined routes from the route directory
routes = fs.readdirSync './api/routes'
for file in routes
if file.match /.*\.coffee$/
route = require './routes/' + file
route app, db
exports = module.exports = server
exports.use = (args...) ->
app.use.apply app, args
|
[
{
"context": "Length: 4\n \"exception-reporting\":\n userId: \"af06818b-2633-4d85-9366-6223a3f85e14\"\n github:\n remoteFetchProtocol: \"ssh\"\n \"hydr",
"end": 728,
"score": 0.6139845848083496,
"start": 694,
"tag": "PASSWORD",
"value": "06818b-2633-4d85-9366-6223a3f85e14"
}
] | atom/config.cson | jjssto/Config | 0 | "*":
Hydrogen:
autoScroll: false
kernelNotifications: true
outputAreaDock: true
showInspectorResultsInAutocomplete: true
wrapOutput: true
core:
disabledPackages: [
"markdown-preview"
"markdown-footnote"
]
telemetryConsent: "no"
themes: [
"atom-dark-ui"
"solarized-dark-syntax"
]
useTreeSitterParsers: false
warnOnLargeFileLimit: 5
editor:
autoIndentOnPaste: false
preferredLineLength: 79
scrollPastEnd: true
showIndentGuide: true
showInvisibles: true
softWrap: true
softWrapAtPreferredLineLength: true
softWrapHangingIndent: 4
tabLength: 4
"exception-reporting":
userId: "af06818b-2633-4d85-9366-6223a3f85e14"
github:
remoteFetchProtocol: "ssh"
"hydrogen-python": {}
kite:
showWelcomeNotificationOnStartup: false
"markdown-pdf":
ghStyle: false
"markdown-preview-plus":
renderer: "pandoc"
"markdown-writer":
fileExtension: ".md"
"spell-check":
addKnownWords: true
localePaths: [
"/usr/lib/"
]
locales: [
"de-DE"
]
"theme-switcher":
uiThemeOne: "atom-dark-ui"
uiThemeTwo: "atom-light-ui"
"tree-view":
hideVcsIgnoredFiles: true
typewriter: {}
"vim-mode-plus":
useClipboardAsDefaultRegister: true
welcome:
showOnStartup: false
"wrap-guide":
columns: [
72
]
enable: true
".coffee.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
79
]
".gfm.source":
editor:
preferredLineLength: 72
softWrapHangingIndent: 2
tabLength: 4
"wrap-guide":
columns: [
72
]
".i3.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
72
79
]
".md.pandoc.source":
editor:
preferredLineLength: 72
"wrap-guide":
enable: false
".md.pweave.source":
"wrap-guide":
columns: [
72
79
]
".plain.text":
editor:
preferredLineLength: 72
"wrap-guide":
enable: false
".python.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
72
79
]
".service.source":
"wrap-guide":
columns: [
72
]
| 99256 | "*":
Hydrogen:
autoScroll: false
kernelNotifications: true
outputAreaDock: true
showInspectorResultsInAutocomplete: true
wrapOutput: true
core:
disabledPackages: [
"markdown-preview"
"markdown-footnote"
]
telemetryConsent: "no"
themes: [
"atom-dark-ui"
"solarized-dark-syntax"
]
useTreeSitterParsers: false
warnOnLargeFileLimit: 5
editor:
autoIndentOnPaste: false
preferredLineLength: 79
scrollPastEnd: true
showIndentGuide: true
showInvisibles: true
softWrap: true
softWrapAtPreferredLineLength: true
softWrapHangingIndent: 4
tabLength: 4
"exception-reporting":
userId: "af<PASSWORD>"
github:
remoteFetchProtocol: "ssh"
"hydrogen-python": {}
kite:
showWelcomeNotificationOnStartup: false
"markdown-pdf":
ghStyle: false
"markdown-preview-plus":
renderer: "pandoc"
"markdown-writer":
fileExtension: ".md"
"spell-check":
addKnownWords: true
localePaths: [
"/usr/lib/"
]
locales: [
"de-DE"
]
"theme-switcher":
uiThemeOne: "atom-dark-ui"
uiThemeTwo: "atom-light-ui"
"tree-view":
hideVcsIgnoredFiles: true
typewriter: {}
"vim-mode-plus":
useClipboardAsDefaultRegister: true
welcome:
showOnStartup: false
"wrap-guide":
columns: [
72
]
enable: true
".coffee.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
79
]
".gfm.source":
editor:
preferredLineLength: 72
softWrapHangingIndent: 2
tabLength: 4
"wrap-guide":
columns: [
72
]
".i3.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
72
79
]
".md.pandoc.source":
editor:
preferredLineLength: 72
"wrap-guide":
enable: false
".md.pweave.source":
"wrap-guide":
columns: [
72
79
]
".plain.text":
editor:
preferredLineLength: 72
"wrap-guide":
enable: false
".python.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
72
79
]
".service.source":
"wrap-guide":
columns: [
72
]
| true | "*":
Hydrogen:
autoScroll: false
kernelNotifications: true
outputAreaDock: true
showInspectorResultsInAutocomplete: true
wrapOutput: true
core:
disabledPackages: [
"markdown-preview"
"markdown-footnote"
]
telemetryConsent: "no"
themes: [
"atom-dark-ui"
"solarized-dark-syntax"
]
useTreeSitterParsers: false
warnOnLargeFileLimit: 5
editor:
autoIndentOnPaste: false
preferredLineLength: 79
scrollPastEnd: true
showIndentGuide: true
showInvisibles: true
softWrap: true
softWrapAtPreferredLineLength: true
softWrapHangingIndent: 4
tabLength: 4
"exception-reporting":
userId: "afPI:PASSWORD:<PASSWORD>END_PI"
github:
remoteFetchProtocol: "ssh"
"hydrogen-python": {}
kite:
showWelcomeNotificationOnStartup: false
"markdown-pdf":
ghStyle: false
"markdown-preview-plus":
renderer: "pandoc"
"markdown-writer":
fileExtension: ".md"
"spell-check":
addKnownWords: true
localePaths: [
"/usr/lib/"
]
locales: [
"de-DE"
]
"theme-switcher":
uiThemeOne: "atom-dark-ui"
uiThemeTwo: "atom-light-ui"
"tree-view":
hideVcsIgnoredFiles: true
typewriter: {}
"vim-mode-plus":
useClipboardAsDefaultRegister: true
welcome:
showOnStartup: false
"wrap-guide":
columns: [
72
]
enable: true
".coffee.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
79
]
".gfm.source":
editor:
preferredLineLength: 72
softWrapHangingIndent: 2
tabLength: 4
"wrap-guide":
columns: [
72
]
".i3.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
72
79
]
".md.pandoc.source":
editor:
preferredLineLength: 72
"wrap-guide":
enable: false
".md.pweave.source":
"wrap-guide":
columns: [
72
79
]
".plain.text":
editor:
preferredLineLength: 72
"wrap-guide":
enable: false
".python.source":
editor:
preferredLineLength: 79
"wrap-guide":
columns: [
72
79
]
".service.source":
"wrap-guide":
columns: [
72
]
|
[
{
"context": ",'E','F','F#','G','G#','A','A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n",
"end": 2239,
"score": 0.9285996556282043,
"start": 2238,
"tag": "KEY",
"value": "C"
},
{
"context": ",'F','F#','G','G#','A','A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constru",
"end": 2248,
"score": 0.7760915756225586,
"start": 2242,
"tag": "KEY",
"value": "F','Bb"
},
{
"context": ",'G','G#','A','A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constructor:",
"end": 2253,
"score": 0.7688828706741333,
"start": 2251,
"tag": "KEY",
"value": "Eb"
},
{
"context": "'G#','A','A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constructor: (val",
"end": 2258,
"score": 0.5001735091209412,
"start": 2256,
"tag": "KEY",
"value": "Ab"
},
{
"context": "'A','A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constructor: (val, tem",
"end": 2263,
"score": 0.49498143792152405,
"start": 2261,
"tag": "KEY",
"value": "Db"
},
{
"context": "A#','B']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constructor: (val, temp) ->",
"end": 2268,
"score": 0.6521354913711548,
"start": 2266,
"tag": "KEY",
"value": "Gb"
},
{
"context": "']\nflatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']\n\nclass Note\n constructor: (val, temp) ->\n i",
"end": 2274,
"score": 0.5390825867652893,
"start": 2272,
"tag": "KEY",
"value": "Cb"
},
{
"context": " utils.type(val) is 'array'\n\n @frequencies = [@tonic.frequency]\n @names = [@tonic.name]\n @midiNo",
"end": 8051,
"score": 0.8841482400894165,
"start": 8046,
"tag": "USERNAME",
"value": "tonic"
},
{
"context": " @frequencies = [@tonic.frequency]\n @names = [@tonic.name]\n @midiNotes = [@tonic.midiNote]\n for note ",
"end": 8088,
"score": 0.9906665086746216,
"start": 8076,
"tag": "USERNAME",
"value": "[@tonic.name"
},
{
"context": "cy]\n @names = [@tonic.name]\n @midiNotes = [@tonic.midiNote]\n for note in @notes\n @frequenci",
"end": 8114,
"score": 0.8138277530670166,
"start": 8109,
"tag": "USERNAME",
"value": "tonic"
},
{
"context": ".85,696.58,788.76,889.74,1005.22,1082.89,1200]\n 'Werckmeister III':[0,90.22,192.18,294.14,390.23,498.05,588.27,",
"end": 11813,
"score": 0.890296459197998,
"start": 11801,
"tag": "NAME",
"value": "Werckmeister"
},
{
"context": "8.27,696.09,792.18,888.27,996.09,1092.18,1200]\n 'Kirnberger': [0,91,192,296,387,498,591,696,792,890,996,1092,",
"end": 11918,
"score": 0.9830171465873718,
"start": 11908,
"tag": "NAME",
"value": "Kirnberger"
},
{
"context": "192,296,387,498,591,696,792,890,996,1092,1200]\n 'Kirnberger III': [0,90.18,193.16,294.13,386.31,498.04,590.22,696",
"end": 11991,
"score": 0.9584181308746338,
"start": 11977,
"tag": "NAME",
"value": "Kirnberger III"
},
{
"context": " Meantone'] = temperaments['Equal']\ntemperaments['Salinas'] = temperaments['1/3 comma Meantone']\ntemperamen",
"end": 12260,
"score": 0.9168742895126343,
"start": 12253,
"tag": "NAME",
"value": "Salinas"
},
{
"context": " temperaments['1/3 comma Meantone']\ntemperaments['Aaron'] = temperaments['1/4 comma Meantone']\ntemperamen",
"end": 12319,
"score": 0.9980860948562622,
"start": 12314,
"tag": "NAME",
"value": "Aaron"
},
{
"context": " temperaments['1/4 comma Meantone']\ntemperaments['Silbermann'] = temperaments['1/5 comma Meantone']\n\nclass Tem",
"end": 12383,
"score": 0.9988827705383301,
"start": 12373,
"tag": "NAME",
"value": "Silbermann"
}
] | temper.src.coffee | jeffreypierce/temper | 2 | utils =
type: (obj) ->
if obj == undefined or obj == null
return false
classType = {
'[object Number]': 'number'
'[object String]': 'string'
'[object Array]': 'array',
'[object Object]': 'object'
}
classType[toString.call(obj)]
list: (val, arr) ->
if val and this[val]
this[val]
else
if arr
for name in this
name
else
for key of this
key
normalize: (num, precision = 3) ->
multiplier = Math.pow 10, precision
Math.round(num * multiplier) / multiplier
centOffset: (freq1, freq2) ->
Math.round 1200 * Math.log(freq1 / freq2) / Math.log 2
decimalFromCents: (cents) ->
Math.pow 2, (cents / 100 / 12)
ratioFromCents: (cents) ->
utils.ratioFromNumber utils.decimalFromCents(cents)
ratioFromNumber: (number, delineator) ->
delin = delineator or ':'
ratio = '0'
numerator = undefined
denominator = undefined
getFractionArray = (num) ->
hasWhole = false
interationLimit = 1000
accuracy = 0.001
fractionArray = []
if num >= 1
hasWhole = true
fractionArray.push Math.floor(num)
if num - Math.floor(num) == 0
return fractionArray
if hasWhole
num = num - Math.floor(num)
decimal = num - parseInt(num, 10)
q = decimal
i = 0
while Math.abs(q - Math.round(q)) > accuracy
if i == interationLimit
return false
i++
q = i / decimal
fractionArray.push Math.round(q * num)
fractionArray.push Math.round(q)
fractionArray
if number or number != Infinity
fractionArray = getFractionArray(number)
switch fractionArray.length
when 1
numerator = number
denominator = 1
when 2
numerator = fractionArray[0]
denominator = fractionArray[1]
when 3
numerator = fractionArray[0] * fractionArray[2] + fractionArray[1]
denominator = fractionArray[2]
ratio = numerator + delin + denominator
ratio
notesFlat = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
notesSharp = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flatKeys = ['C','F','Bb','Eb','Ab','Db','Gb', 'Cb']
class Note
constructor: (val, temp) ->
if window?
@_play = temp.play
@_pluck = temp.pluck
@rootFrequency = temp.rootFrequency()
@temperament = temp._temperament
referenceFrequency = =>
@rootFrequency * Math.pow 2, @octave
noteFromName = (noteName) =>
getFrequencyFromNoteLetter = =>
noteArray = @getNoteArray @letter
position = noteArray.indexOf @letter
ratio = utils.ratioFromCents temperaments[@temperament][position]
utils.normalize ratio * referenceFrequency()
parsed = /// ([A-Ga-g]) # match letter
([b#]?) # match accidental
(\d+) # match octave
///.exec noteName
if parsed?
@octave = parseInt parsed[3], 10
@accidental = parsed[2]
@letter = parsed[1].toUpperCase()
@letter += @accidental if @accidental?
@frequency = utils.normalize getFrequencyFromNoteLetter()
@name = val
@centOffset = 0
else
throw new TypeError "Note name #{noteName} is not a valid argument"
noteFromFreq = (freq) =>
getNoteLetterFromFrequency = =>
baseFreq = Math.log @frequency / referenceFrequency()
# equal temperament naming
noteNumber = Math.round baseFreq / Math.log Math.pow(2, 1 / 12)
@octave += 1 if noteNumber is 12
noteArray = @getNoteArray()
noteArray[noteNumber % 12]
if 20000 > freq > 0
@octave = Math.floor Math.log(freq / @rootFrequency) / Math.log 2
@frequency = utils.normalize freq
@letter = getNoteLetterFromFrequency()
@name = @letter + @octave.toString()
accidental = @name.match /[b#]/
@accidental = if accidental? then accidental else ""
trueFreq = temper @name
@centOffset = utils.centOffset @frequency, trueFreq.tonic.frequency,
else
throw new RangeError "Frequency #{freq} is not valid"
noteFromName val if utils.type(val) is "string"
noteFromFreq val if utils.type(val) is "number"
@midiNote = Math.round 12 * Math.log(@frequency / 440) / Math.log(2) + 69
getNoteArray: (letter) ->
if flatKeys.indexOf(letter) > -1 then notesFlat else notesSharp
if window?
Note::play = (length) ->
@_play.call this, length
Note::pluck= (length) ->
@_pluck.call this, length
U = 'U'
m2 = 'm2'
M2 = 'M2'
m3 = 'm3'
M3 = 'M3'
P4 = 'P4'
d5 = 'd5'
P5 = 'P5'
m6 = 'm6'
M6 = 'M6'
m7 = 'm7'
M7 = 'M7'
O = 'O'
A4 = 'd5'
intervals = [U, m2, M2, m3, M3, P4, d5, P5, m6, M6, m7, M7, O ]
class Interval extends Note
constructor: (val, temp, @direction = "up", octaveOffset = "0") ->
@tonic = temp.tonic
noteFromInterval = (val, octaveOffset) =>
@intervalName = val
position = intervals.indexOf val
noteArray = @tonic.getNoteArray()
intervalOctave = @tonic.octave
if @direction is 'up'
intervalOctave += parseInt octaveOffset, 10
intervalNumber = noteArray.indexOf(@tonic.letter) + position
intervalOctave += 1 if intervalNumber >= 12
else if @direction is 'down'
intervalOctave -= parseInt octaveOffset, 10
intervalNumber = noteArray.indexOf(@tonic.letter) - position
if intervalNumber < 0
intervalNumber += 12
intervalOctave -= 1
intervalNote = noteArray[intervalNumber % 12] + intervalOctave.toString()
intervalNamefromNoteName = =>
tonicNoteArray = @getNoteArray.call @tonic
noteArray = @getNoteArray()
rootPosition = tonicNoteArray.indexOf @tonic.letter
offsetPosition = noteArray.indexOf @letter
@direction = 'down'
position = (12 - offsetPosition + rootPosition) % 12
if @tonic.octave < @octave or
(@tonic.octave is @octave and offsetPosition > rootPosition)
offsetPosition += 12 if offsetPosition < rootPosition
position = offsetPosition - rootPosition
@direction = 'up'
intervals[position]
if intervals.indexOf(val) > -1
val = noteFromInterval val, octaveOffset
super val, temp
@intervalName = intervalNamefromNoteName() if !utils.type(@intervalName)
if @tonic.name is @name
@direction = '-'
@frequencies = [@tonic.frequency, @frequency]
@names = [@tonic.name, @name]
@midiNotes = [@tonic.midiNote, @midiNote]
if window?
Interval::play = (length) ->
@play.call this, length, 2
@play.call @tonic, length, 2
Interval::pluck= (length) ->
@pluck.call this, length, 2
@pluck.call @tonic, length, 2
class Collection
constructor: (val, temp, collection) ->
@tonic = temp.tonic
@notes = []
@name = 'unknown'
if window?
@_play = temp.play
@_pluck = temp.pluck
collectionFromName = (val) =>
if collection[val]
@name = val
for interval in collection[val]
@notes.push new Interval(interval, temp)
else
throw new TypeError "Name #{val} is not a valid argument"
collectionFromArray = (val) =>
positions = []
for note, i in val
if note.indexOf(',') > -1
complexInterval = note.split ','
note = complexInterval[0].trim()
direction = complexInterval[1].trim()
octave = complexInterval[2].trim()
interval = new Interval note, temp, direction, octave
else
interval = new Interval note, temp
positions.push interval.intervalName
@notes.push interval
for key, value of collection
if JSON.stringify(value) is JSON.stringify(positions)
@name = key
break
collectionFromName val if utils.type(val) is 'string'
collectionFromArray val if utils.type(val) is 'array'
@frequencies = [@tonic.frequency]
@names = [@tonic.name]
@midiNotes = [@tonic.midiNote]
for note in @notes
@frequencies.push note.frequency
@names.push note.name
@midiNotes.push note.midiNote
this
chords =
'maj': [M3, P5]
'maj6': [M3, P5, M6]
'maj7': [M3, P5, M7]
'majb6': [M3, P5, m6]
'majb7': [M3, P5, m7]
'min6': [m3, P5, m6]
'min7': [m3, P5, m7]
'minM7': [m3, P5, M7]
'min': [m3, P5]
'aug': [M3, m6]
'aug7': [M3, m6, M7]
'dim': [m3, d5]
'dim7': [m3, d5, M6]
'sus4': [P4, P5]
'sus2': [M2, P5]
'dream': [P4,d5,P5]
class Chord extends Collection
constructor: (chord, temp) ->
super chord, temp, chords
if window?
Chord::play = (length) ->
@_play.call @tonic, length, @notes.length + 1
for note in @notes then do (note) =>
@_play.call note, length, @notes.length + 1
this
Chord::pluck = (length) ->
@_pluck.call @tonic, length, @notes.length + 1
for note in @notes then do (note) =>
@_pluck.call note, length, @notes.length + 1
this
scales =
'Major': [M2, M3, P4, P5, M6, M7, O]
'Melodic Minor': [M2, m3, P4, P5, m6, m7, O]
'Harmonic Minor': [M2, m3, P4, P5, m6, M7, O]
'Chromatic': [m2, M2, m3, M3, P4, d5, P5, m6, M6, m7, M7, O]
'Ionian': [M2, M3, P4, P5, M6, M7, O]
'Dorian': [M2, m3, P4, P5, M6, m7, O]
'Phrygian': [m2, m3, P4, P5, m6, m7, O]
'Lydian': [M2, M3, A4, P5, M6, M7, O]
'Mixolydian': [M2, M3, P4, P5, M6, m7, O]
'Aeolian': [M2, m3, P4, P5, m6, m7, O]
'Locrian': [m2, m3, P4, d5, m6, m7, O]
'Whole Tone': [M2, M3, d5, m6, m7, O]
'Acoustic': [M2, M3, d5, P5, M6, m7, O]
'Enigmatic': [m2, M3, d5, m6, m7, M7, O]
'Enigmatic Minor': [m2, m3, d5, P5, m7, M7, O]
'Neapolitan': [m2, m3, P4, P4, P5, m6, M7, O]
'Prometheus':[M2, M3, d5, M6, m7, O]
'In Sen': [m2, P4, P5, m7, O]
'In': [m2, P4, P5, m6, O]
'Hirajoshi': [m2, P4, P5, m6, O]
'Yo': [M2, P4, P5, M6, O]
'Iwato': [m2, P4, d5, m7, O]
'Pentatonic': [M2, M3, P5, M6, O]
'Octatonic I': [M2, m3, P4, d5, m6, M6, M7, O]
'Octatonic II': [m2, m3, M3, d5, P5, M6, m7, O]
'Tritone': [m2, M3, d5, P5, m7, O]
'Hungarian': [M2, m3, d5, P5, m6, M7, O]
class Scale extends Collection
constructor: (scale, temp) ->
super scale, temp, scales
if window?
Scale::play = (length = 1) ->
@_play.call @tonic, length, 3
for note, i in @notes then do (note) =>
setTimeout ( =>
@_play.call note, length, 3
), length * 1000 / 2 * (i + 1)
this
Scale::pluck = (length = 1) ->
@_pluck.call @tonic, length, 3
for note, i in @notes then do (note) =>
setTimeout ( =>
@_pluck.call note, length, 3
), length * 1000 / 2 * (i + 1)
this
temperaments =
'Equal': [0,100,200,300,400,500,600,700,800,900,1000,1100,1200]
'Pythagorean': [0,113.69,203.91,294.13,407.82,498.04,611.73,701.95,815.64,905.87,996.09,1109.78,120]
'Natural': [0,111.74,203.91,315.64,386.31,498.05,603,702,813.69,884.36,1017.6,1088.27,1200]
'1/3 comma Meantone': [0,63.50,189.57,315.64,379.14,505.21,568.72,694.79,758.29,884.36,1010.43,1073.93,1200]
'2/7 comma Meantone': [0,70.67,191.62,312.57,383.24,504.19,574.86,695.81,766.48,887.43,1008.38,1079.05,1200]
'1/4 comma Meantone': [0,76.05,193.16,310.26,386.31,503.42,579.47,696.58,772.63,889.74,1006.84,1082.89,1200]
'1/5 comma Meantone': [0,83.58,195.31,307.04,390.61,502.35,585.92,697.65,781.23,892.96,1004.69,1088.27,1200]
'1/6 comma Meantone': [0,88.59,196.74,304.89,393.48,501.63,590.22,698.37,786.96,895.11,1003.26,1091.85,1200]
'1/8 comma Meantone': [0,94.87,198.53,302.20,397.07,500.73,595.60,699.27,794.13,897.80,1001.47,1096.33,1200]
'Ordinaire': [0,86.81,193.16,296.09,386.31,503.42,584.85,696.58,788.76,889.74,1005.22,1082.89,1200]
'Werckmeister III':[0,90.22,192.18,294.14,390.23,498.05,588.27,696.09,792.18,888.27,996.09,1092.18,1200]
'Kirnberger': [0,91,192,296,387,498,591,696,792,890,996,1092,1200]
'Kirnberger III': [0,90.18,193.16,294.13,386.31,498.04,590.22,696.58,792.18,889.74,996.09,1088.27,1200]
'Young': [0,93.69,195.91,298.13,391.82,502.04,591.73,697.96,796.18,893.87,1000.09,1089.78,1200]
temperaments['1/11 comma Meantone'] = temperaments['Equal']
temperaments['Salinas'] = temperaments['1/3 comma Meantone']
temperaments['Aaron'] = temperaments['1/4 comma Meantone']
temperaments['Silbermann'] = temperaments['1/5 comma Meantone']
class Temper
constructor: (val, @_temperament = 'Equal', @tuningFrequency = 440) ->
if val?
@tonic = new Note val, this
@tonic
rootFrequency: ->
ratio = utils.decimalFromCents temperaments[@_temperament][9]
@tuningFrequency / Math.pow(2, 4) / ratio
note: (noteName) ->
if noteName?
@tonic = new Note noteName, this
@interval @_interval.name if @_interval?
@scale @_scale.names if @_scale?
@chord @_chord.name if @_chord?
else
@tonic
temperament: (temperament) ->
if temperament?
if temperaments[temperament]
@_temperament = temperament
@tonic = @note @tonic.name
@interval @_interval.name if @_interval?
@scale @_scale.names if @_scale?
@chord @_chord.name if @_chord?
this
else
@_temperament
interval: (interval, direction, octaveOffset) ->
if interval?
@_interval = new Interval interval, this, direction, octaveOffset
else
@_interval
scale: (scale) ->
if scale?
@_scale = new Scale scale, this
else
@_scale
chord: (chord) ->
if chord?
@_chord = new Chord chord, this
else
@_chord
temper = (val, temperament, tuningFrequency) ->
new Temper val, temperament, tuningFrequency
temper.chords = (val) ->
utils.list.call chords, val
temper.scales = (val) ->
utils.list.call scales, val
temper.intervals = (val) ->
utils.list.call intervals, val, true
temper.temperaments = (val) ->
utils.list.call temperaments, val
temper.centOffset = utils.centOffset
temper.ratioFromCents = utils.ratioFromCents
# node or browser
root = this
if typeof exports isnt "undefined"
module.exports = temper
else
root["temper"] = temper
if window?
window.AudioContext = window.AudioContext || window.webkitAudioContext
context = new AudioContext()
Temper::play = (length = 2, numOfNotes = 1) ->
volume = 0.9 / numOfNotes
begin = context.currentTime
end = begin + length
osc = context.createOscillator()
osc.type = 'sine'
osc.frequency.value = if @frequency then @frequency else @tonic.frequency
vol = context.createGain()
vol.gain.setValueAtTime(0, begin)
vol.gain.linearRampToValueAtTime(volume, end - (length * 0.5))
vol.gain.linearRampToValueAtTime(0, end)
osc.connect vol
vol.connect context.destination
osc.start begin
osc.stop end
Temper::pluck = (length = 2, numOfNotes = 1) ->
volume = 0.9 / numOfNotes
begin = context.currentTime
end = begin + length
_karplusStrong = (freq) ->
noise = []
samples = new Float32Array(context.sampleRate)
# generate noise
period = Math.floor(context.sampleRate / freq)
i = 0
while i < period
noise[i] = 2 * Math.random() - 1
i++
prevIndex = 0
_generateSample = ->
index = noise.shift()
sample = (index + prevIndex) / 2
prevIndex = sample
noise.push sample
sample
# generate decay
amp = (Math.random() * 0.5) + 0.4
j = 0
while j < context.sampleRate
samples[j] = _generateSample()
decay = amp - (j / context.sampleRate) * amp
samples[j] = samples[j] * decay
j++
samples
vol = context.createGain()
pluck = context.createBufferSource()
frequency = if @frequency then @frequency else @tonic.frequency
samples = _karplusStrong frequency
audioBuffer = context.createBuffer(1, samples.length, context.sampleRate)
audioBuffer.getChannelData(0).set samples
pluck.buffer = audioBuffer
pluck.connect vol
vol.connect context.destination
vol.gain.value = volume
pluck.start begin
pluck.stop end
| 63714 | utils =
type: (obj) ->
if obj == undefined or obj == null
return false
classType = {
'[object Number]': 'number'
'[object String]': 'string'
'[object Array]': 'array',
'[object Object]': 'object'
}
classType[toString.call(obj)]
list: (val, arr) ->
if val and this[val]
this[val]
else
if arr
for name in this
name
else
for key of this
key
normalize: (num, precision = 3) ->
multiplier = Math.pow 10, precision
Math.round(num * multiplier) / multiplier
centOffset: (freq1, freq2) ->
Math.round 1200 * Math.log(freq1 / freq2) / Math.log 2
decimalFromCents: (cents) ->
Math.pow 2, (cents / 100 / 12)
ratioFromCents: (cents) ->
utils.ratioFromNumber utils.decimalFromCents(cents)
ratioFromNumber: (number, delineator) ->
delin = delineator or ':'
ratio = '0'
numerator = undefined
denominator = undefined
getFractionArray = (num) ->
hasWhole = false
interationLimit = 1000
accuracy = 0.001
fractionArray = []
if num >= 1
hasWhole = true
fractionArray.push Math.floor(num)
if num - Math.floor(num) == 0
return fractionArray
if hasWhole
num = num - Math.floor(num)
decimal = num - parseInt(num, 10)
q = decimal
i = 0
while Math.abs(q - Math.round(q)) > accuracy
if i == interationLimit
return false
i++
q = i / decimal
fractionArray.push Math.round(q * num)
fractionArray.push Math.round(q)
fractionArray
if number or number != Infinity
fractionArray = getFractionArray(number)
switch fractionArray.length
when 1
numerator = number
denominator = 1
when 2
numerator = fractionArray[0]
denominator = fractionArray[1]
when 3
numerator = fractionArray[0] * fractionArray[2] + fractionArray[1]
denominator = fractionArray[2]
ratio = numerator + delin + denominator
ratio
notesFlat = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
notesSharp = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flatKeys = ['<KEY>','<KEY>','<KEY>','<KEY>','<KEY>','<KEY>', '<KEY>']
class Note
constructor: (val, temp) ->
if window?
@_play = temp.play
@_pluck = temp.pluck
@rootFrequency = temp.rootFrequency()
@temperament = temp._temperament
referenceFrequency = =>
@rootFrequency * Math.pow 2, @octave
noteFromName = (noteName) =>
getFrequencyFromNoteLetter = =>
noteArray = @getNoteArray @letter
position = noteArray.indexOf @letter
ratio = utils.ratioFromCents temperaments[@temperament][position]
utils.normalize ratio * referenceFrequency()
parsed = /// ([A-Ga-g]) # match letter
([b#]?) # match accidental
(\d+) # match octave
///.exec noteName
if parsed?
@octave = parseInt parsed[3], 10
@accidental = parsed[2]
@letter = parsed[1].toUpperCase()
@letter += @accidental if @accidental?
@frequency = utils.normalize getFrequencyFromNoteLetter()
@name = val
@centOffset = 0
else
throw new TypeError "Note name #{noteName} is not a valid argument"
noteFromFreq = (freq) =>
getNoteLetterFromFrequency = =>
baseFreq = Math.log @frequency / referenceFrequency()
# equal temperament naming
noteNumber = Math.round baseFreq / Math.log Math.pow(2, 1 / 12)
@octave += 1 if noteNumber is 12
noteArray = @getNoteArray()
noteArray[noteNumber % 12]
if 20000 > freq > 0
@octave = Math.floor Math.log(freq / @rootFrequency) / Math.log 2
@frequency = utils.normalize freq
@letter = getNoteLetterFromFrequency()
@name = @letter + @octave.toString()
accidental = @name.match /[b#]/
@accidental = if accidental? then accidental else ""
trueFreq = temper @name
@centOffset = utils.centOffset @frequency, trueFreq.tonic.frequency,
else
throw new RangeError "Frequency #{freq} is not valid"
noteFromName val if utils.type(val) is "string"
noteFromFreq val if utils.type(val) is "number"
@midiNote = Math.round 12 * Math.log(@frequency / 440) / Math.log(2) + 69
getNoteArray: (letter) ->
if flatKeys.indexOf(letter) > -1 then notesFlat else notesSharp
if window?
Note::play = (length) ->
@_play.call this, length
Note::pluck= (length) ->
@_pluck.call this, length
U = 'U'
m2 = 'm2'
M2 = 'M2'
m3 = 'm3'
M3 = 'M3'
P4 = 'P4'
d5 = 'd5'
P5 = 'P5'
m6 = 'm6'
M6 = 'M6'
m7 = 'm7'
M7 = 'M7'
O = 'O'
A4 = 'd5'
intervals = [U, m2, M2, m3, M3, P4, d5, P5, m6, M6, m7, M7, O ]
class Interval extends Note
constructor: (val, temp, @direction = "up", octaveOffset = "0") ->
@tonic = temp.tonic
noteFromInterval = (val, octaveOffset) =>
@intervalName = val
position = intervals.indexOf val
noteArray = @tonic.getNoteArray()
intervalOctave = @tonic.octave
if @direction is 'up'
intervalOctave += parseInt octaveOffset, 10
intervalNumber = noteArray.indexOf(@tonic.letter) + position
intervalOctave += 1 if intervalNumber >= 12
else if @direction is 'down'
intervalOctave -= parseInt octaveOffset, 10
intervalNumber = noteArray.indexOf(@tonic.letter) - position
if intervalNumber < 0
intervalNumber += 12
intervalOctave -= 1
intervalNote = noteArray[intervalNumber % 12] + intervalOctave.toString()
intervalNamefromNoteName = =>
tonicNoteArray = @getNoteArray.call @tonic
noteArray = @getNoteArray()
rootPosition = tonicNoteArray.indexOf @tonic.letter
offsetPosition = noteArray.indexOf @letter
@direction = 'down'
position = (12 - offsetPosition + rootPosition) % 12
if @tonic.octave < @octave or
(@tonic.octave is @octave and offsetPosition > rootPosition)
offsetPosition += 12 if offsetPosition < rootPosition
position = offsetPosition - rootPosition
@direction = 'up'
intervals[position]
if intervals.indexOf(val) > -1
val = noteFromInterval val, octaveOffset
super val, temp
@intervalName = intervalNamefromNoteName() if !utils.type(@intervalName)
if @tonic.name is @name
@direction = '-'
@frequencies = [@tonic.frequency, @frequency]
@names = [@tonic.name, @name]
@midiNotes = [@tonic.midiNote, @midiNote]
if window?
Interval::play = (length) ->
@play.call this, length, 2
@play.call @tonic, length, 2
Interval::pluck= (length) ->
@pluck.call this, length, 2
@pluck.call @tonic, length, 2
class Collection
constructor: (val, temp, collection) ->
@tonic = temp.tonic
@notes = []
@name = 'unknown'
if window?
@_play = temp.play
@_pluck = temp.pluck
collectionFromName = (val) =>
if collection[val]
@name = val
for interval in collection[val]
@notes.push new Interval(interval, temp)
else
throw new TypeError "Name #{val} is not a valid argument"
collectionFromArray = (val) =>
positions = []
for note, i in val
if note.indexOf(',') > -1
complexInterval = note.split ','
note = complexInterval[0].trim()
direction = complexInterval[1].trim()
octave = complexInterval[2].trim()
interval = new Interval note, temp, direction, octave
else
interval = new Interval note, temp
positions.push interval.intervalName
@notes.push interval
for key, value of collection
if JSON.stringify(value) is JSON.stringify(positions)
@name = key
break
collectionFromName val if utils.type(val) is 'string'
collectionFromArray val if utils.type(val) is 'array'
@frequencies = [@tonic.frequency]
@names = [@tonic.name]
@midiNotes = [@tonic.midiNote]
for note in @notes
@frequencies.push note.frequency
@names.push note.name
@midiNotes.push note.midiNote
this
chords =
'maj': [M3, P5]
'maj6': [M3, P5, M6]
'maj7': [M3, P5, M7]
'majb6': [M3, P5, m6]
'majb7': [M3, P5, m7]
'min6': [m3, P5, m6]
'min7': [m3, P5, m7]
'minM7': [m3, P5, M7]
'min': [m3, P5]
'aug': [M3, m6]
'aug7': [M3, m6, M7]
'dim': [m3, d5]
'dim7': [m3, d5, M6]
'sus4': [P4, P5]
'sus2': [M2, P5]
'dream': [P4,d5,P5]
class Chord extends Collection
constructor: (chord, temp) ->
super chord, temp, chords
if window?
Chord::play = (length) ->
@_play.call @tonic, length, @notes.length + 1
for note in @notes then do (note) =>
@_play.call note, length, @notes.length + 1
this
Chord::pluck = (length) ->
@_pluck.call @tonic, length, @notes.length + 1
for note in @notes then do (note) =>
@_pluck.call note, length, @notes.length + 1
this
scales =
'Major': [M2, M3, P4, P5, M6, M7, O]
'Melodic Minor': [M2, m3, P4, P5, m6, m7, O]
'Harmonic Minor': [M2, m3, P4, P5, m6, M7, O]
'Chromatic': [m2, M2, m3, M3, P4, d5, P5, m6, M6, m7, M7, O]
'Ionian': [M2, M3, P4, P5, M6, M7, O]
'Dorian': [M2, m3, P4, P5, M6, m7, O]
'Phrygian': [m2, m3, P4, P5, m6, m7, O]
'Lydian': [M2, M3, A4, P5, M6, M7, O]
'Mixolydian': [M2, M3, P4, P5, M6, m7, O]
'Aeolian': [M2, m3, P4, P5, m6, m7, O]
'Locrian': [m2, m3, P4, d5, m6, m7, O]
'Whole Tone': [M2, M3, d5, m6, m7, O]
'Acoustic': [M2, M3, d5, P5, M6, m7, O]
'Enigmatic': [m2, M3, d5, m6, m7, M7, O]
'Enigmatic Minor': [m2, m3, d5, P5, m7, M7, O]
'Neapolitan': [m2, m3, P4, P4, P5, m6, M7, O]
'Prometheus':[M2, M3, d5, M6, m7, O]
'In Sen': [m2, P4, P5, m7, O]
'In': [m2, P4, P5, m6, O]
'Hirajoshi': [m2, P4, P5, m6, O]
'Yo': [M2, P4, P5, M6, O]
'Iwato': [m2, P4, d5, m7, O]
'Pentatonic': [M2, M3, P5, M6, O]
'Octatonic I': [M2, m3, P4, d5, m6, M6, M7, O]
'Octatonic II': [m2, m3, M3, d5, P5, M6, m7, O]
'Tritone': [m2, M3, d5, P5, m7, O]
'Hungarian': [M2, m3, d5, P5, m6, M7, O]
class Scale extends Collection
constructor: (scale, temp) ->
super scale, temp, scales
if window?
Scale::play = (length = 1) ->
@_play.call @tonic, length, 3
for note, i in @notes then do (note) =>
setTimeout ( =>
@_play.call note, length, 3
), length * 1000 / 2 * (i + 1)
this
Scale::pluck = (length = 1) ->
@_pluck.call @tonic, length, 3
for note, i in @notes then do (note) =>
setTimeout ( =>
@_pluck.call note, length, 3
), length * 1000 / 2 * (i + 1)
this
temperaments =
'Equal': [0,100,200,300,400,500,600,700,800,900,1000,1100,1200]
'Pythagorean': [0,113.69,203.91,294.13,407.82,498.04,611.73,701.95,815.64,905.87,996.09,1109.78,120]
'Natural': [0,111.74,203.91,315.64,386.31,498.05,603,702,813.69,884.36,1017.6,1088.27,1200]
'1/3 comma Meantone': [0,63.50,189.57,315.64,379.14,505.21,568.72,694.79,758.29,884.36,1010.43,1073.93,1200]
'2/7 comma Meantone': [0,70.67,191.62,312.57,383.24,504.19,574.86,695.81,766.48,887.43,1008.38,1079.05,1200]
'1/4 comma Meantone': [0,76.05,193.16,310.26,386.31,503.42,579.47,696.58,772.63,889.74,1006.84,1082.89,1200]
'1/5 comma Meantone': [0,83.58,195.31,307.04,390.61,502.35,585.92,697.65,781.23,892.96,1004.69,1088.27,1200]
'1/6 comma Meantone': [0,88.59,196.74,304.89,393.48,501.63,590.22,698.37,786.96,895.11,1003.26,1091.85,1200]
'1/8 comma Meantone': [0,94.87,198.53,302.20,397.07,500.73,595.60,699.27,794.13,897.80,1001.47,1096.33,1200]
'Ordinaire': [0,86.81,193.16,296.09,386.31,503.42,584.85,696.58,788.76,889.74,1005.22,1082.89,1200]
'<NAME> III':[0,90.22,192.18,294.14,390.23,498.05,588.27,696.09,792.18,888.27,996.09,1092.18,1200]
'<NAME>': [0,91,192,296,387,498,591,696,792,890,996,1092,1200]
'<NAME>': [0,90.18,193.16,294.13,386.31,498.04,590.22,696.58,792.18,889.74,996.09,1088.27,1200]
'Young': [0,93.69,195.91,298.13,391.82,502.04,591.73,697.96,796.18,893.87,1000.09,1089.78,1200]
temperaments['1/11 comma Meantone'] = temperaments['Equal']
temperaments['<NAME>'] = temperaments['1/3 comma Meantone']
temperaments['<NAME>'] = temperaments['1/4 comma Meantone']
temperaments['<NAME>'] = temperaments['1/5 comma Meantone']
class Temper
constructor: (val, @_temperament = 'Equal', @tuningFrequency = 440) ->
if val?
@tonic = new Note val, this
@tonic
rootFrequency: ->
ratio = utils.decimalFromCents temperaments[@_temperament][9]
@tuningFrequency / Math.pow(2, 4) / ratio
note: (noteName) ->
if noteName?
@tonic = new Note noteName, this
@interval @_interval.name if @_interval?
@scale @_scale.names if @_scale?
@chord @_chord.name if @_chord?
else
@tonic
temperament: (temperament) ->
if temperament?
if temperaments[temperament]
@_temperament = temperament
@tonic = @note @tonic.name
@interval @_interval.name if @_interval?
@scale @_scale.names if @_scale?
@chord @_chord.name if @_chord?
this
else
@_temperament
interval: (interval, direction, octaveOffset) ->
if interval?
@_interval = new Interval interval, this, direction, octaveOffset
else
@_interval
scale: (scale) ->
if scale?
@_scale = new Scale scale, this
else
@_scale
chord: (chord) ->
if chord?
@_chord = new Chord chord, this
else
@_chord
temper = (val, temperament, tuningFrequency) ->
new Temper val, temperament, tuningFrequency
temper.chords = (val) ->
utils.list.call chords, val
temper.scales = (val) ->
utils.list.call scales, val
temper.intervals = (val) ->
utils.list.call intervals, val, true
temper.temperaments = (val) ->
utils.list.call temperaments, val
temper.centOffset = utils.centOffset
temper.ratioFromCents = utils.ratioFromCents
# node or browser
root = this
if typeof exports isnt "undefined"
module.exports = temper
else
root["temper"] = temper
if window?
window.AudioContext = window.AudioContext || window.webkitAudioContext
context = new AudioContext()
Temper::play = (length = 2, numOfNotes = 1) ->
volume = 0.9 / numOfNotes
begin = context.currentTime
end = begin + length
osc = context.createOscillator()
osc.type = 'sine'
osc.frequency.value = if @frequency then @frequency else @tonic.frequency
vol = context.createGain()
vol.gain.setValueAtTime(0, begin)
vol.gain.linearRampToValueAtTime(volume, end - (length * 0.5))
vol.gain.linearRampToValueAtTime(0, end)
osc.connect vol
vol.connect context.destination
osc.start begin
osc.stop end
Temper::pluck = (length = 2, numOfNotes = 1) ->
volume = 0.9 / numOfNotes
begin = context.currentTime
end = begin + length
_karplusStrong = (freq) ->
noise = []
samples = new Float32Array(context.sampleRate)
# generate noise
period = Math.floor(context.sampleRate / freq)
i = 0
while i < period
noise[i] = 2 * Math.random() - 1
i++
prevIndex = 0
_generateSample = ->
index = noise.shift()
sample = (index + prevIndex) / 2
prevIndex = sample
noise.push sample
sample
# generate decay
amp = (Math.random() * 0.5) + 0.4
j = 0
while j < context.sampleRate
samples[j] = _generateSample()
decay = amp - (j / context.sampleRate) * amp
samples[j] = samples[j] * decay
j++
samples
vol = context.createGain()
pluck = context.createBufferSource()
frequency = if @frequency then @frequency else @tonic.frequency
samples = _karplusStrong frequency
audioBuffer = context.createBuffer(1, samples.length, context.sampleRate)
audioBuffer.getChannelData(0).set samples
pluck.buffer = audioBuffer
pluck.connect vol
vol.connect context.destination
vol.gain.value = volume
pluck.start begin
pluck.stop end
| true | utils =
type: (obj) ->
if obj == undefined or obj == null
return false
classType = {
'[object Number]': 'number'
'[object String]': 'string'
'[object Array]': 'array',
'[object Object]': 'object'
}
classType[toString.call(obj)]
list: (val, arr) ->
if val and this[val]
this[val]
else
if arr
for name in this
name
else
for key of this
key
normalize: (num, precision = 3) ->
multiplier = Math.pow 10, precision
Math.round(num * multiplier) / multiplier
centOffset: (freq1, freq2) ->
Math.round 1200 * Math.log(freq1 / freq2) / Math.log 2
decimalFromCents: (cents) ->
Math.pow 2, (cents / 100 / 12)
ratioFromCents: (cents) ->
utils.ratioFromNumber utils.decimalFromCents(cents)
ratioFromNumber: (number, delineator) ->
delin = delineator or ':'
ratio = '0'
numerator = undefined
denominator = undefined
getFractionArray = (num) ->
hasWhole = false
interationLimit = 1000
accuracy = 0.001
fractionArray = []
if num >= 1
hasWhole = true
fractionArray.push Math.floor(num)
if num - Math.floor(num) == 0
return fractionArray
if hasWhole
num = num - Math.floor(num)
decimal = num - parseInt(num, 10)
q = decimal
i = 0
while Math.abs(q - Math.round(q)) > accuracy
if i == interationLimit
return false
i++
q = i / decimal
fractionArray.push Math.round(q * num)
fractionArray.push Math.round(q)
fractionArray
if number or number != Infinity
fractionArray = getFractionArray(number)
switch fractionArray.length
when 1
numerator = number
denominator = 1
when 2
numerator = fractionArray[0]
denominator = fractionArray[1]
when 3
numerator = fractionArray[0] * fractionArray[2] + fractionArray[1]
denominator = fractionArray[2]
ratio = numerator + delin + denominator
ratio
notesFlat = ['C','Db','D','Eb','E','F','Gb','G','Ab','A','Bb','B']
notesSharp = ['C','C#','D','D#','E','F','F#','G','G#','A','A#','B']
flatKeys = ['PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI','PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
class Note
constructor: (val, temp) ->
if window?
@_play = temp.play
@_pluck = temp.pluck
@rootFrequency = temp.rootFrequency()
@temperament = temp._temperament
referenceFrequency = =>
@rootFrequency * Math.pow 2, @octave
noteFromName = (noteName) =>
getFrequencyFromNoteLetter = =>
noteArray = @getNoteArray @letter
position = noteArray.indexOf @letter
ratio = utils.ratioFromCents temperaments[@temperament][position]
utils.normalize ratio * referenceFrequency()
parsed = /// ([A-Ga-g]) # match letter
([b#]?) # match accidental
(\d+) # match octave
///.exec noteName
if parsed?
@octave = parseInt parsed[3], 10
@accidental = parsed[2]
@letter = parsed[1].toUpperCase()
@letter += @accidental if @accidental?
@frequency = utils.normalize getFrequencyFromNoteLetter()
@name = val
@centOffset = 0
else
throw new TypeError "Note name #{noteName} is not a valid argument"
noteFromFreq = (freq) =>
getNoteLetterFromFrequency = =>
baseFreq = Math.log @frequency / referenceFrequency()
# equal temperament naming
noteNumber = Math.round baseFreq / Math.log Math.pow(2, 1 / 12)
@octave += 1 if noteNumber is 12
noteArray = @getNoteArray()
noteArray[noteNumber % 12]
if 20000 > freq > 0
@octave = Math.floor Math.log(freq / @rootFrequency) / Math.log 2
@frequency = utils.normalize freq
@letter = getNoteLetterFromFrequency()
@name = @letter + @octave.toString()
accidental = @name.match /[b#]/
@accidental = if accidental? then accidental else ""
trueFreq = temper @name
@centOffset = utils.centOffset @frequency, trueFreq.tonic.frequency,
else
throw new RangeError "Frequency #{freq} is not valid"
noteFromName val if utils.type(val) is "string"
noteFromFreq val if utils.type(val) is "number"
@midiNote = Math.round 12 * Math.log(@frequency / 440) / Math.log(2) + 69
getNoteArray: (letter) ->
if flatKeys.indexOf(letter) > -1 then notesFlat else notesSharp
if window?
Note::play = (length) ->
@_play.call this, length
Note::pluck= (length) ->
@_pluck.call this, length
U = 'U'
m2 = 'm2'
M2 = 'M2'
m3 = 'm3'
M3 = 'M3'
P4 = 'P4'
d5 = 'd5'
P5 = 'P5'
m6 = 'm6'
M6 = 'M6'
m7 = 'm7'
M7 = 'M7'
O = 'O'
A4 = 'd5'
intervals = [U, m2, M2, m3, M3, P4, d5, P5, m6, M6, m7, M7, O ]
class Interval extends Note
constructor: (val, temp, @direction = "up", octaveOffset = "0") ->
@tonic = temp.tonic
noteFromInterval = (val, octaveOffset) =>
@intervalName = val
position = intervals.indexOf val
noteArray = @tonic.getNoteArray()
intervalOctave = @tonic.octave
if @direction is 'up'
intervalOctave += parseInt octaveOffset, 10
intervalNumber = noteArray.indexOf(@tonic.letter) + position
intervalOctave += 1 if intervalNumber >= 12
else if @direction is 'down'
intervalOctave -= parseInt octaveOffset, 10
intervalNumber = noteArray.indexOf(@tonic.letter) - position
if intervalNumber < 0
intervalNumber += 12
intervalOctave -= 1
intervalNote = noteArray[intervalNumber % 12] + intervalOctave.toString()
intervalNamefromNoteName = =>
tonicNoteArray = @getNoteArray.call @tonic
noteArray = @getNoteArray()
rootPosition = tonicNoteArray.indexOf @tonic.letter
offsetPosition = noteArray.indexOf @letter
@direction = 'down'
position = (12 - offsetPosition + rootPosition) % 12
if @tonic.octave < @octave or
(@tonic.octave is @octave and offsetPosition > rootPosition)
offsetPosition += 12 if offsetPosition < rootPosition
position = offsetPosition - rootPosition
@direction = 'up'
intervals[position]
if intervals.indexOf(val) > -1
val = noteFromInterval val, octaveOffset
super val, temp
@intervalName = intervalNamefromNoteName() if !utils.type(@intervalName)
if @tonic.name is @name
@direction = '-'
@frequencies = [@tonic.frequency, @frequency]
@names = [@tonic.name, @name]
@midiNotes = [@tonic.midiNote, @midiNote]
if window?
Interval::play = (length) ->
@play.call this, length, 2
@play.call @tonic, length, 2
Interval::pluck= (length) ->
@pluck.call this, length, 2
@pluck.call @tonic, length, 2
class Collection
constructor: (val, temp, collection) ->
@tonic = temp.tonic
@notes = []
@name = 'unknown'
if window?
@_play = temp.play
@_pluck = temp.pluck
collectionFromName = (val) =>
if collection[val]
@name = val
for interval in collection[val]
@notes.push new Interval(interval, temp)
else
throw new TypeError "Name #{val} is not a valid argument"
collectionFromArray = (val) =>
positions = []
for note, i in val
if note.indexOf(',') > -1
complexInterval = note.split ','
note = complexInterval[0].trim()
direction = complexInterval[1].trim()
octave = complexInterval[2].trim()
interval = new Interval note, temp, direction, octave
else
interval = new Interval note, temp
positions.push interval.intervalName
@notes.push interval
for key, value of collection
if JSON.stringify(value) is JSON.stringify(positions)
@name = key
break
collectionFromName val if utils.type(val) is 'string'
collectionFromArray val if utils.type(val) is 'array'
@frequencies = [@tonic.frequency]
@names = [@tonic.name]
@midiNotes = [@tonic.midiNote]
for note in @notes
@frequencies.push note.frequency
@names.push note.name
@midiNotes.push note.midiNote
this
chords =
'maj': [M3, P5]
'maj6': [M3, P5, M6]
'maj7': [M3, P5, M7]
'majb6': [M3, P5, m6]
'majb7': [M3, P5, m7]
'min6': [m3, P5, m6]
'min7': [m3, P5, m7]
'minM7': [m3, P5, M7]
'min': [m3, P5]
'aug': [M3, m6]
'aug7': [M3, m6, M7]
'dim': [m3, d5]
'dim7': [m3, d5, M6]
'sus4': [P4, P5]
'sus2': [M2, P5]
'dream': [P4,d5,P5]
class Chord extends Collection
constructor: (chord, temp) ->
super chord, temp, chords
if window?
Chord::play = (length) ->
@_play.call @tonic, length, @notes.length + 1
for note in @notes then do (note) =>
@_play.call note, length, @notes.length + 1
this
Chord::pluck = (length) ->
@_pluck.call @tonic, length, @notes.length + 1
for note in @notes then do (note) =>
@_pluck.call note, length, @notes.length + 1
this
scales =
'Major': [M2, M3, P4, P5, M6, M7, O]
'Melodic Minor': [M2, m3, P4, P5, m6, m7, O]
'Harmonic Minor': [M2, m3, P4, P5, m6, M7, O]
'Chromatic': [m2, M2, m3, M3, P4, d5, P5, m6, M6, m7, M7, O]
'Ionian': [M2, M3, P4, P5, M6, M7, O]
'Dorian': [M2, m3, P4, P5, M6, m7, O]
'Phrygian': [m2, m3, P4, P5, m6, m7, O]
'Lydian': [M2, M3, A4, P5, M6, M7, O]
'Mixolydian': [M2, M3, P4, P5, M6, m7, O]
'Aeolian': [M2, m3, P4, P5, m6, m7, O]
'Locrian': [m2, m3, P4, d5, m6, m7, O]
'Whole Tone': [M2, M3, d5, m6, m7, O]
'Acoustic': [M2, M3, d5, P5, M6, m7, O]
'Enigmatic': [m2, M3, d5, m6, m7, M7, O]
'Enigmatic Minor': [m2, m3, d5, P5, m7, M7, O]
'Neapolitan': [m2, m3, P4, P4, P5, m6, M7, O]
'Prometheus':[M2, M3, d5, M6, m7, O]
'In Sen': [m2, P4, P5, m7, O]
'In': [m2, P4, P5, m6, O]
'Hirajoshi': [m2, P4, P5, m6, O]
'Yo': [M2, P4, P5, M6, O]
'Iwato': [m2, P4, d5, m7, O]
'Pentatonic': [M2, M3, P5, M6, O]
'Octatonic I': [M2, m3, P4, d5, m6, M6, M7, O]
'Octatonic II': [m2, m3, M3, d5, P5, M6, m7, O]
'Tritone': [m2, M3, d5, P5, m7, O]
'Hungarian': [M2, m3, d5, P5, m6, M7, O]
class Scale extends Collection
constructor: (scale, temp) ->
super scale, temp, scales
if window?
Scale::play = (length = 1) ->
@_play.call @tonic, length, 3
for note, i in @notes then do (note) =>
setTimeout ( =>
@_play.call note, length, 3
), length * 1000 / 2 * (i + 1)
this
Scale::pluck = (length = 1) ->
@_pluck.call @tonic, length, 3
for note, i in @notes then do (note) =>
setTimeout ( =>
@_pluck.call note, length, 3
), length * 1000 / 2 * (i + 1)
this
temperaments =
'Equal': [0,100,200,300,400,500,600,700,800,900,1000,1100,1200]
'Pythagorean': [0,113.69,203.91,294.13,407.82,498.04,611.73,701.95,815.64,905.87,996.09,1109.78,120]
'Natural': [0,111.74,203.91,315.64,386.31,498.05,603,702,813.69,884.36,1017.6,1088.27,1200]
'1/3 comma Meantone': [0,63.50,189.57,315.64,379.14,505.21,568.72,694.79,758.29,884.36,1010.43,1073.93,1200]
'2/7 comma Meantone': [0,70.67,191.62,312.57,383.24,504.19,574.86,695.81,766.48,887.43,1008.38,1079.05,1200]
'1/4 comma Meantone': [0,76.05,193.16,310.26,386.31,503.42,579.47,696.58,772.63,889.74,1006.84,1082.89,1200]
'1/5 comma Meantone': [0,83.58,195.31,307.04,390.61,502.35,585.92,697.65,781.23,892.96,1004.69,1088.27,1200]
'1/6 comma Meantone': [0,88.59,196.74,304.89,393.48,501.63,590.22,698.37,786.96,895.11,1003.26,1091.85,1200]
'1/8 comma Meantone': [0,94.87,198.53,302.20,397.07,500.73,595.60,699.27,794.13,897.80,1001.47,1096.33,1200]
'Ordinaire': [0,86.81,193.16,296.09,386.31,503.42,584.85,696.58,788.76,889.74,1005.22,1082.89,1200]
'PI:NAME:<NAME>END_PI III':[0,90.22,192.18,294.14,390.23,498.05,588.27,696.09,792.18,888.27,996.09,1092.18,1200]
'PI:NAME:<NAME>END_PI': [0,91,192,296,387,498,591,696,792,890,996,1092,1200]
'PI:NAME:<NAME>END_PI': [0,90.18,193.16,294.13,386.31,498.04,590.22,696.58,792.18,889.74,996.09,1088.27,1200]
'Young': [0,93.69,195.91,298.13,391.82,502.04,591.73,697.96,796.18,893.87,1000.09,1089.78,1200]
temperaments['1/11 comma Meantone'] = temperaments['Equal']
temperaments['PI:NAME:<NAME>END_PI'] = temperaments['1/3 comma Meantone']
temperaments['PI:NAME:<NAME>END_PI'] = temperaments['1/4 comma Meantone']
temperaments['PI:NAME:<NAME>END_PI'] = temperaments['1/5 comma Meantone']
class Temper
constructor: (val, @_temperament = 'Equal', @tuningFrequency = 440) ->
if val?
@tonic = new Note val, this
@tonic
rootFrequency: ->
ratio = utils.decimalFromCents temperaments[@_temperament][9]
@tuningFrequency / Math.pow(2, 4) / ratio
note: (noteName) ->
if noteName?
@tonic = new Note noteName, this
@interval @_interval.name if @_interval?
@scale @_scale.names if @_scale?
@chord @_chord.name if @_chord?
else
@tonic
temperament: (temperament) ->
if temperament?
if temperaments[temperament]
@_temperament = temperament
@tonic = @note @tonic.name
@interval @_interval.name if @_interval?
@scale @_scale.names if @_scale?
@chord @_chord.name if @_chord?
this
else
@_temperament
interval: (interval, direction, octaveOffset) ->
if interval?
@_interval = new Interval interval, this, direction, octaveOffset
else
@_interval
scale: (scale) ->
if scale?
@_scale = new Scale scale, this
else
@_scale
chord: (chord) ->
if chord?
@_chord = new Chord chord, this
else
@_chord
temper = (val, temperament, tuningFrequency) ->
new Temper val, temperament, tuningFrequency
temper.chords = (val) ->
utils.list.call chords, val
temper.scales = (val) ->
utils.list.call scales, val
temper.intervals = (val) ->
utils.list.call intervals, val, true
temper.temperaments = (val) ->
utils.list.call temperaments, val
temper.centOffset = utils.centOffset
temper.ratioFromCents = utils.ratioFromCents
# node or browser
root = this
if typeof exports isnt "undefined"
module.exports = temper
else
root["temper"] = temper
if window?
window.AudioContext = window.AudioContext || window.webkitAudioContext
context = new AudioContext()
Temper::play = (length = 2, numOfNotes = 1) ->
volume = 0.9 / numOfNotes
begin = context.currentTime
end = begin + length
osc = context.createOscillator()
osc.type = 'sine'
osc.frequency.value = if @frequency then @frequency else @tonic.frequency
vol = context.createGain()
vol.gain.setValueAtTime(0, begin)
vol.gain.linearRampToValueAtTime(volume, end - (length * 0.5))
vol.gain.linearRampToValueAtTime(0, end)
osc.connect vol
vol.connect context.destination
osc.start begin
osc.stop end
Temper::pluck = (length = 2, numOfNotes = 1) ->
volume = 0.9 / numOfNotes
begin = context.currentTime
end = begin + length
_karplusStrong = (freq) ->
noise = []
samples = new Float32Array(context.sampleRate)
# generate noise
period = Math.floor(context.sampleRate / freq)
i = 0
while i < period
noise[i] = 2 * Math.random() - 1
i++
prevIndex = 0
_generateSample = ->
index = noise.shift()
sample = (index + prevIndex) / 2
prevIndex = sample
noise.push sample
sample
# generate decay
amp = (Math.random() * 0.5) + 0.4
j = 0
while j < context.sampleRate
samples[j] = _generateSample()
decay = amp - (j / context.sampleRate) * amp
samples[j] = samples[j] * decay
j++
samples
vol = context.createGain()
pluck = context.createBufferSource()
frequency = if @frequency then @frequency else @tonic.frequency
samples = _karplusStrong frequency
audioBuffer = context.createBuffer(1, samples.length, context.sampleRate)
audioBuffer.getChannelData(0).set samples
pluck.buffer = audioBuffer
pluck.connect vol
vol.connect context.destination
vol.gain.value = volume
pluck.start begin
pluck.stop end
|
[
{
"context": "w Promise (resolve) -> \n\n ## 変数展開\n\n name = 'Recipe'\n hello = \"Hello #{name}!\"\n logger.debug he",
"end": 306,
"score": 0.8004554510116577,
"start": 300,
"tag": "NAME",
"value": "Recipe"
}
] | node-coffee/src/cookbook/recipe_base.coffee | ykchat/recipe-code | 0 | #!/usr/bin/env coffee
moment = require 'moment-timezone'
path = require 'path'
logging = require './util/logging'
logger = logging.LoggerFactory.getLogger path.basename __filename
title = ->
logger.debug '# Base'
return
cook = -> new Promise (resolve) ->
## 変数展開
name = 'Recipe'
hello = "Hello #{name}!"
logger.debug hello
## 現在時刻
now = moment().utc()
logger.debug now.format()
now = moment().tz 'Asia/Tokyo'
logger.debug now.format()
resolve()
return
module.exports =
title: title
cook: cook
| 188680 | #!/usr/bin/env coffee
moment = require 'moment-timezone'
path = require 'path'
logging = require './util/logging'
logger = logging.LoggerFactory.getLogger path.basename __filename
title = ->
logger.debug '# Base'
return
cook = -> new Promise (resolve) ->
## 変数展開
name = '<NAME>'
hello = "Hello #{name}!"
logger.debug hello
## 現在時刻
now = moment().utc()
logger.debug now.format()
now = moment().tz 'Asia/Tokyo'
logger.debug now.format()
resolve()
return
module.exports =
title: title
cook: cook
| true | #!/usr/bin/env coffee
moment = require 'moment-timezone'
path = require 'path'
logging = require './util/logging'
logger = logging.LoggerFactory.getLogger path.basename __filename
title = ->
logger.debug '# Base'
return
cook = -> new Promise (resolve) ->
## 変数展開
name = 'PI:NAME:<NAME>END_PI'
hello = "Hello #{name}!"
logger.debug hello
## 現在時刻
now = moment().utc()
logger.debug now.format()
now = moment().tz 'Asia/Tokyo'
logger.debug now.format()
resolve()
return
module.exports =
title: title
cook: cook
|
[
{
"context": " category: \"人相关的\"\n example: \"example@qq.com\"\n defaultValue: \"\"\n g",
"end": 948,
"score": 0.9999162554740906,
"start": 934,
"tag": "EMAIL",
"value": "example@qq.com"
},
{
"context": "MENT=1;\n\nINSERT INTO `myTable` (`name`) VALUES (\\\"Len\\\"),(\\\"Brendan\\\"),(\\\"Allistair\\\"),(\\\"Talon\\\"),(\\\"K",
"end": 5833,
"score": 0.9997299909591675,
"start": 5830,
"tag": "NAME",
"value": "Len"
},
{
"context": "NSERT INTO `myTable` (`name`) VALUES (\\\"Len\\\"),(\\\"Brendan\\\"),(\\\"Allistair\\\"),(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hil",
"end": 5847,
"score": 0.9995427131652832,
"start": 5840,
"tag": "NAME",
"value": "Brendan"
},
{
"context": "Table` (`name`) VALUES (\\\"Len\\\"),(\\\"Brendan\\\"),(\\\"Allistair\\\"),(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\")",
"end": 5863,
"score": 0.9995209574699402,
"start": 5854,
"tag": "NAME",
"value": "Allistair"
},
{
"context": "VALUES (\\\"Len\\\"),(\\\"Brendan\\\"),(\\\"Allistair\\\"),(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"",
"end": 5875,
"score": 0.9991706013679504,
"start": 5870,
"tag": "NAME",
"value": "Talon"
},
{
"context": "n\\\"),(\\\"Brendan\\\"),(\\\"Allistair\\\"),(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"),(\\\"Talon\\\"",
"end": 5887,
"score": 0.9991787075996399,
"start": 5882,
"tag": "NAME",
"value": "Keefe"
},
{
"context": "dan\\\"),(\\\"Allistair\\\"),(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"),(\\\"Talon\\\"),(\\\"Ezra\\\")",
"end": 5899,
"score": 0.9994773864746094,
"start": 5894,
"tag": "NAME",
"value": "Hilel"
},
{
"context": "listair\\\"),(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"),(\\\"Talon\\\"),(\\\"Ezra\\\");\nINSERT IN",
"end": 5910,
"score": 0.999091386795044,
"start": 5906,
"tag": "NAME",
"value": "Ezra"
},
{
"context": "(\\\"Talon\\\"),(\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"),(\\\"Talon\\\"),(\\\"Ezra\\\");\nINSERT INTO `myTable` ",
"end": 5923,
"score": 0.9991052746772766,
"start": 5917,
"tag": "NAME",
"value": "Duncan"
},
{
"context": "\\\"Keefe\\\"),(\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"),(\\\"Talon\\\"),(\\\"Ezra\\\");\nINSERT INTO `myTable` (`name`) VAL",
"end": 5935,
"score": 0.9967518448829651,
"start": 5930,
"tag": "NAME",
"value": "Talon"
},
{
"context": "\\\"Hilel\\\"),(\\\"Ezra\\\"),(\\\"Duncan\\\"),(\\\"Talon\\\"),(\\\"Ezra\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Tyro",
"end": 5946,
"score": 0.9964982867240906,
"start": 5942,
"tag": "NAME",
"value": "Ezra"
},
{
"context": "Ezra\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Tyrone\\\"),(\\\"Caleb\\\"),(\\\"Gregory\\\"),(\\\"Lucas\\\"),(\\\"Brend",
"end": 5998,
"score": 0.9995668530464172,
"start": 5992,
"tag": "NAME",
"value": "Tyrone"
},
{
"context": "RT INTO `myTable` (`name`) VALUES (\\\"Tyrone\\\"),(\\\"Caleb\\\"),(\\\"Gregory\\\"),(\\\"Lucas\\\"),(\\\"Brenden\\\"),(\\\"Den",
"end": 6010,
"score": 0.9994415640830994,
"start": 6005,
"tag": "NAME",
"value": "Caleb"
},
{
"context": "able` (`name`) VALUES (\\\"Tyrone\\\"),(\\\"Caleb\\\"),(\\\"Gregory\\\"),(\\\"Lucas\\\"),(\\\"Brenden\\\"),(\\\"Dennis\\\"),(\\\"Bren",
"end": 6024,
"score": 0.9994780421257019,
"start": 6017,
"tag": "NAME",
"value": "Gregory"
},
{
"context": " VALUES (\\\"Tyrone\\\"),(\\\"Caleb\\\"),(\\\"Gregory\\\"),(\\\"Lucas\\\"),(\\\"Brenden\\\"),(\\\"Dennis\\\"),(\\\"Brendan\\\"),(\\\"Ar",
"end": 6036,
"score": 0.9993445873260498,
"start": 6031,
"tag": "NAME",
"value": "Lucas"
},
{
"context": "yrone\\\"),(\\\"Caleb\\\"),(\\\"Gregory\\\"),(\\\"Lucas\\\"),(\\\"Brenden\\\"),(\\\"Dennis\\\"),(\\\"Brendan\\\"),(\\\"Armand\\\"),(\\\"Eze",
"end": 6050,
"score": 0.9994813799858093,
"start": 6043,
"tag": "NAME",
"value": "Brenden"
},
{
"context": "leb\\\"),(\\\"Gregory\\\"),(\\\"Lucas\\\"),(\\\"Brenden\\\"),(\\\"Dennis\\\"),(\\\"Brendan\\\"),(\\\"Armand\\\"),(\\\"Ezekiel\\\"),(\\\"St",
"end": 6063,
"score": 0.9993389248847961,
"start": 6057,
"tag": "NAME",
"value": "Dennis"
},
{
"context": "gory\\\"),(\\\"Lucas\\\"),(\\\"Brenden\\\"),(\\\"Dennis\\\"),(\\\"Brendan\\\"),(\\\"Armand\\\"),(\\\"Ezekiel\\\"),(\\\"Stephen\\\");\nINSE",
"end": 6077,
"score": 0.9993128776550293,
"start": 6070,
"tag": "NAME",
"value": "Brendan"
},
{
"context": "as\\\"),(\\\"Brenden\\\"),(\\\"Dennis\\\"),(\\\"Brendan\\\"),(\\\"Armand\\\"),(\\\"Ezekiel\\\"),(\\\"Stephen\\\");\nINSERT INTO `myTa",
"end": 6090,
"score": 0.999480664730072,
"start": 6084,
"tag": "NAME",
"value": "Armand"
},
{
"context": "den\\\"),(\\\"Dennis\\\"),(\\\"Brendan\\\"),(\\\"Armand\\\"),(\\\"Ezekiel\\\"),(\\\"Stephen\\\");\nINSERT INTO `myTable` (`name`) ",
"end": 6104,
"score": 0.9992908239364624,
"start": 6097,
"tag": "NAME",
"value": "Ezekiel"
},
{
"context": "is\\\"),(\\\"Brendan\\\"),(\\\"Armand\\\"),(\\\"Ezekiel\\\"),(\\\"Stephen\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Jose",
"end": 6118,
"score": 0.9993656873703003,
"start": 6111,
"tag": "NAME",
"value": "Stephen"
},
{
"context": "phen\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Joseph\\\"),(\\\"Duncan\\\"),(\\\"Tyrone\\\"),(\\\"Alden\\\"),(\\\"Vaugh",
"end": 6170,
"score": 0.9994306564331055,
"start": 6164,
"tag": "NAME",
"value": "Joseph"
},
{
"context": "RT INTO `myTable` (`name`) VALUES (\\\"Joseph\\\"),(\\\"Duncan\\\"),(\\\"Tyrone\\\"),(\\\"Alden\\\"),(\\\"Vaughan\\\"),(\\\"Maca",
"end": 6183,
"score": 0.9993560910224915,
"start": 6177,
"tag": "NAME",
"value": "Duncan"
},
{
"context": "ble` (`name`) VALUES (\\\"Joseph\\\"),(\\\"Duncan\\\"),(\\\"Tyrone\\\"),(\\\"Alden\\\"),(\\\"Vaughan\\\"),(\\\"Macaulay\\\"),(\\\"Ab",
"end": 6196,
"score": 0.999370813369751,
"start": 6190,
"tag": "NAME",
"value": "Tyrone"
},
{
"context": " VALUES (\\\"Joseph\\\"),(\\\"Duncan\\\"),(\\\"Tyrone\\\"),(\\\"Alden\\\"),(\\\"Vaughan\\\"),(\\\"Macaulay\\\"),(\\\"Abraham\\\"),(\\\"",
"end": 6208,
"score": 0.9993227124214172,
"start": 6203,
"tag": "NAME",
"value": "Alden"
},
{
"context": "oseph\\\"),(\\\"Duncan\\\"),(\\\"Tyrone\\\"),(\\\"Alden\\\"),(\\\"Vaughan\\\"),(\\\"Macaulay\\\"),(\\\"Abraham\\\"),(\\\"Thaddeus\\\"),(\\",
"end": 6222,
"score": 0.9991186261177063,
"start": 6215,
"tag": "NAME",
"value": "Vaughan"
},
{
"context": "ncan\\\"),(\\\"Tyrone\\\"),(\\\"Alden\\\"),(\\\"Vaughan\\\"),(\\\"Macaulay\\\"),(\\\"Abraham\\\"),(\\\"Thaddeus\\\"),(\\\"Brandon\\\"),(\\\"",
"end": 6237,
"score": 0.9976338148117065,
"start": 6229,
"tag": "NAME",
"value": "Macaulay"
},
{
"context": "ne\\\"),(\\\"Alden\\\"),(\\\"Vaughan\\\"),(\\\"Macaulay\\\"),(\\\"Abraham\\\"),(\\\"Thaddeus\\\"),(\\\"Brandon\\\"),(\\\"Brent\\\");\nINSE",
"end": 6251,
"score": 0.9979279637336731,
"start": 6244,
"tag": "NAME",
"value": "Abraham"
},
{
"context": "\\\"),(\\\"Vaughan\\\"),(\\\"Macaulay\\\"),(\\\"Abraham\\\"),(\\\"Thaddeus\\\"),(\\\"Brandon\\\"),(\\\"Brent\\\");\nINSERT INTO `myTabl",
"end": 6266,
"score": 0.9991392493247986,
"start": 6258,
"tag": "NAME",
"value": "Thaddeus"
},
{
"context": "\"),(\\\"Macaulay\\\"),(\\\"Abraham\\\"),(\\\"Thaddeus\\\"),(\\\"Brandon\\\"),(\\\"Brent\\\");\nINSERT INTO `myTable` (`name`) VA",
"end": 6280,
"score": 0.9993481636047363,
"start": 6273,
"tag": "NAME",
"value": "Brandon"
},
{
"context": "\\\"),(\\\"Abraham\\\"),(\\\"Thaddeus\\\"),(\\\"Brandon\\\"),(\\\"Brent\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Orso",
"end": 6292,
"score": 0.9988869428634644,
"start": 6287,
"tag": "NAME",
"value": "Brent"
},
{
"context": "rent\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Orson\\\"),(\\\"Chase\\\"),(\\\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander",
"end": 6343,
"score": 0.9992615580558777,
"start": 6338,
"tag": "NAME",
"value": "Orson"
},
{
"context": "ERT INTO `myTable` (`name`) VALUES (\\\"Orson\\\"),(\\\"Chase\\\"),(\\\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\",
"end": 6355,
"score": 0.9992609620094299,
"start": 6350,
"tag": "NAME",
"value": "Chase"
},
{
"context": "Table` (`name`) VALUES (\\\"Orson\\\"),(\\\"Chase\\\"),(\\\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\",
"end": 6367,
"score": 0.9992571473121643,
"start": 6362,
"tag": "NAME",
"value": "Brady"
},
{
"context": "e`) VALUES (\\\"Orson\\\"),(\\\"Chase\\\"),(\\\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan",
"end": 6380,
"score": 0.998796284198761,
"start": 6374,
"tag": "NAME",
"value": "Graham"
},
{
"context": "\"Orson\\\"),(\\\"Chase\\\"),(\\\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan\\\"),(\\\"Ahmed\\",
"end": 6393,
"score": 0.9984278082847595,
"start": 6387,
"tag": "NAME",
"value": "Xander"
},
{
"context": "Chase\\\"),(\\\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan\\\"),(\\\"Ahmed\\\"),(\\\"Zeph\\",
"end": 6404,
"score": 0.9987615346908569,
"start": 6400,
"tag": "NAME",
"value": "Neil"
},
{
"context": "\"Brady\\\"),(\\\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan\\\"),(\\\"Ahmed\\\"),(\\\"Zeph\\\");\nINSERT I",
"end": 6416,
"score": 0.9992210268974304,
"start": 6411,
"tag": "NAME",
"value": "Brady"
},
{
"context": "\"Graham\\\"),(\\\"Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan\\\"),(\\\"Ahmed\\\"),(\\\"Zeph\\\");\nINSERT INTO `myTable` ",
"end": 6430,
"score": 0.9992594122886658,
"start": 6423,
"tag": "NAME",
"value": "Donovan"
},
{
"context": "Xander\\\"),(\\\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan\\\"),(\\\"Ahmed\\\"),(\\\"Zeph\\\");\nINSERT INTO `myTable` (`name`) VAL",
"end": 6442,
"score": 0.9991551637649536,
"start": 6437,
"tag": "NAME",
"value": "Ahmed"
},
{
"context": "\"Neil\\\"),(\\\"Brady\\\"),(\\\"Donovan\\\"),(\\\"Ahmed\\\"),(\\\"Zeph\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Rudy",
"end": 6453,
"score": 0.9987665414810181,
"start": 6449,
"tag": "NAME",
"value": "Zeph"
},
{
"context": "Zeph\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Rudyard\\\"),(\\\"Quinlan\\\"),(\\\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Philli",
"end": 6506,
"score": 0.9994351863861084,
"start": 6499,
"tag": "NAME",
"value": "Rudyard"
},
{
"context": "T INTO `myTable` (`name`) VALUES (\\\"Rudyard\\\"),(\\\"Quinlan\\\"),(\\\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\",
"end": 6520,
"score": 0.9992024302482605,
"start": 6513,
"tag": "NAME",
"value": "Quinlan"
},
{
"context": "e` (`name`) VALUES (\\\"Rudyard\\\"),(\\\"Quinlan\\\"),(\\\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\\"),(\\\"Quama",
"end": 6531,
"score": 0.9993963241577148,
"start": 6527,
"tag": "NAME",
"value": "Neil"
},
{
"context": " VALUES (\\\"Rudyard\\\"),(\\\"Quinlan\\\"),(\\\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dust",
"end": 6543,
"score": 0.999374508857727,
"start": 6538,
"tag": "NAME",
"value": "Rigel"
},
{
"context": "udyard\\\"),(\\\"Quinlan\\\"),(\\\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dustin\\\"),(\\\"Devin",
"end": 6557,
"score": 0.999544620513916,
"start": 6550,
"tag": "NAME",
"value": "Phillip"
},
{
"context": "uinlan\\\"),(\\\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dustin\\\"),(\\\"Devin\\\"),(\\\"Julia",
"end": 6569,
"score": 0.9993235468864441,
"start": 6564,
"tag": "NAME",
"value": "Lucas"
},
{
"context": "\"Neil\\\"),(\\\"Rigel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dustin\\\"),(\\\"Devin\\\"),(\\\"Julian\\\");\nINSERT ",
"end": 6582,
"score": 0.999362051486969,
"start": 6576,
"tag": "NAME",
"value": "Quamar"
},
{
"context": "igel\\\"),(\\\"Phillip\\\"),(\\\"Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dustin\\\"),(\\\"Devin\\\"),(\\\"Julian\\\");\nINSERT INTO `myTable",
"end": 6595,
"score": 0.9992421865463257,
"start": 6589,
"tag": "NAME",
"value": "Dustin"
},
{
"context": "illip\\\"),(\\\"Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dustin\\\"),(\\\"Devin\\\"),(\\\"Julian\\\");\nINSERT INTO `myTable` (`name`) V",
"end": 6607,
"score": 0.9995013475418091,
"start": 6602,
"tag": "NAME",
"value": "Devin"
},
{
"context": "Lucas\\\"),(\\\"Quamar\\\"),(\\\"Dustin\\\"),(\\\"Devin\\\"),(\\\"Julian\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Clar",
"end": 6620,
"score": 0.9995100498199463,
"start": 6614,
"tag": "NAME",
"value": "Julian"
},
{
"context": "lian\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Clarke\\\"),(\\\"Ethan\\\"),(\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\")",
"end": 6672,
"score": 0.9994150996208191,
"start": 6666,
"tag": "NAME",
"value": "Clarke"
},
{
"context": "RT INTO `myTable` (`name`) VALUES (\\\"Clarke\\\"),(\\\"Ethan\\\"),(\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"",
"end": 6684,
"score": 0.9994240999221802,
"start": 6679,
"tag": "NAME",
"value": "Ethan"
},
{
"context": "able` (`name`) VALUES (\\\"Clarke\\\"),(\\\"Ethan\\\"),(\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"),(\\\"Basil\\",
"end": 6695,
"score": 0.9996125102043152,
"start": 6691,
"tag": "NAME",
"value": "Adam"
},
{
"context": "e`) VALUES (\\\"Clarke\\\"),(\\\"Ethan\\\"),(\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"),(\\\"Basil\\\"),(\\\"Ignatiu",
"end": 6708,
"score": 0.9996557235717773,
"start": 6702,
"tag": "NAME",
"value": "Armand"
},
{
"context": "\"Clarke\\\"),(\\\"Ethan\\\"),(\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"),(\\\"Basil\\\"),(\\\"Ignatius\\\"),(\\\"Nor",
"end": 6719,
"score": 0.9993579983711243,
"start": 6715,
"tag": "NAME",
"value": "Drew"
},
{
"context": "(\\\"Ethan\\\"),(\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"),(\\\"Basil\\\"),(\\\"Ignatius\\\"),(\\\"Norman\\\"),(\\\"Dex",
"end": 6732,
"score": 0.9995135068893433,
"start": 6726,
"tag": "NAME",
"value": "George"
},
{
"context": "\\\"Adam\\\"),(\\\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"),(\\\"Basil\\\"),(\\\"Ignatius\\\"),(\\\"Norman\\\"),(\\\"Dexter\\\");\nINSE",
"end": 6744,
"score": 0.9983503818511963,
"start": 6739,
"tag": "NAME",
"value": "Basil"
},
{
"context": "\"Armand\\\"),(\\\"Drew\\\"),(\\\"George\\\"),(\\\"Basil\\\"),(\\\"Ignatius\\\"),(\\\"Norman\\\"),(\\\"Dexter\\\");\nINSERT INTO `myTabl",
"end": 6759,
"score": 0.9994420409202576,
"start": 6751,
"tag": "NAME",
"value": "Ignatius"
},
{
"context": "rew\\\"),(\\\"George\\\"),(\\\"Basil\\\"),(\\\"Ignatius\\\"),(\\\"Norman\\\"),(\\\"Dexter\\\");\nINSERT INTO `myTable` (`name`) V",
"end": 6772,
"score": 0.999265193939209,
"start": 6766,
"tag": "NAME",
"value": "Norman"
},
{
"context": "rge\\\"),(\\\"Basil\\\"),(\\\"Ignatius\\\"),(\\\"Norman\\\"),(\\\"Dexter\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Ian\\",
"end": 6785,
"score": 0.9970873594284058,
"start": 6779,
"tag": "NAME",
"value": "Dexter"
},
{
"context": "xter\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Ian\\\"),(\\\"Herrod\\\"),(\\\"Ashton\\\"),(\\\"August\\\"),(\\\"Josi",
"end": 6834,
"score": 0.9995729923248291,
"start": 6831,
"tag": "NAME",
"value": "Ian"
},
{
"context": "NSERT INTO `myTable` (`name`) VALUES (\\\"Ian\\\"),(\\\"Herrod\\\"),(\\\"Ashton\\\"),(\\\"August\\\"),(\\\"Josiah\\\"),(\\\"Jame",
"end": 6847,
"score": 0.9995152950286865,
"start": 6841,
"tag": "NAME",
"value": "Herrod"
},
{
"context": "yTable` (`name`) VALUES (\\\"Ian\\\"),(\\\"Herrod\\\"),(\\\"Ashton\\\"),(\\\"August\\\"),(\\\"Josiah\\\"),(\\\"James\\\"),(\\\"Patri",
"end": 6860,
"score": 0.999563992023468,
"start": 6854,
"tag": "NAME",
"value": "Ashton"
},
{
"context": "e`) VALUES (\\\"Ian\\\"),(\\\"Herrod\\\"),(\\\"Ashton\\\"),(\\\"August\\\"),(\\\"Josiah\\\"),(\\\"James\\\"),(\\\"Patrick\\\"),(\\\"Timo",
"end": 6873,
"score": 0.9974014759063721,
"start": 6867,
"tag": "NAME",
"value": "August"
},
{
"context": "\"Ian\\\"),(\\\"Herrod\\\"),(\\\"Ashton\\\"),(\\\"August\\\"),(\\\"Josiah\\\"),(\\\"James\\\"),(\\\"Patrick\\\"),(\\\"Timothy\\\"),(\\\"Phe",
"end": 6886,
"score": 0.9993658065795898,
"start": 6880,
"tag": "NAME",
"value": "Josiah"
},
{
"context": "rrod\\\"),(\\\"Ashton\\\"),(\\\"August\\\"),(\\\"Josiah\\\"),(\\\"James\\\"),(\\\"Patrick\\\"),(\\\"Timothy\\\"),(\\\"Phelan\\\"),(\\\"Ba",
"end": 6898,
"score": 0.999535322189331,
"start": 6893,
"tag": "NAME",
"value": "James"
},
{
"context": "shton\\\"),(\\\"August\\\"),(\\\"Josiah\\\"),(\\\"James\\\"),(\\\"Patrick\\\"),(\\\"Timothy\\\"),(\\\"Phelan\\\"),(\\\"Baker\\\");\nINSERT",
"end": 6912,
"score": 0.9994784593582153,
"start": 6905,
"tag": "NAME",
"value": "Patrick"
},
{
"context": "gust\\\"),(\\\"Josiah\\\"),(\\\"James\\\"),(\\\"Patrick\\\"),(\\\"Timothy\\\"),(\\\"Phelan\\\"),(\\\"Baker\\\");\nINSERT INTO `myTable",
"end": 6926,
"score": 0.9995629191398621,
"start": 6919,
"tag": "NAME",
"value": "Timothy"
},
{
"context": "iah\\\"),(\\\"James\\\"),(\\\"Patrick\\\"),(\\\"Timothy\\\"),(\\\"Phelan\\\"),(\\\"Baker\\\");\nINSERT INTO `myTable` (`name`) VA",
"end": 6939,
"score": 0.9995803236961365,
"start": 6933,
"tag": "NAME",
"value": "Phelan"
},
{
"context": "es\\\"),(\\\"Patrick\\\"),(\\\"Timothy\\\"),(\\\"Phelan\\\"),(\\\"Baker\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Luci",
"end": 6951,
"score": 0.9971921443939209,
"start": 6946,
"tag": "NAME",
"value": "Baker"
},
{
"context": "aker\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Lucius\\\"),(\\\"Jameson\\\"),(\\\"Nissim\\\"),(\\\"Donovan\\\"),(\\\"Ea",
"end": 7003,
"score": 0.9994632005691528,
"start": 6997,
"tag": "NAME",
"value": "Lucius"
},
{
"context": "RT INTO `myTable` (`name`) VALUES (\\\"Lucius\\\"),(\\\"Jameson\\\"),(\\\"Nissim\\\"),(\\\"Donovan\\\"),(\\\"Eagan\\\"),(\\\"Cald",
"end": 7017,
"score": 0.9994050860404968,
"start": 7010,
"tag": "NAME",
"value": "Jameson"
},
{
"context": "le` (`name`) VALUES (\\\"Lucius\\\"),(\\\"Jameson\\\"),(\\\"Nissim\\\"),(\\\"Donovan\\\"),(\\\"Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Re",
"end": 7030,
"score": 0.9994459748268127,
"start": 7024,
"tag": "NAME",
"value": "Nissim"
},
{
"context": "VALUES (\\\"Lucius\\\"),(\\\"Jameson\\\"),(\\\"Nissim\\\"),(\\\"Donovan\\\"),(\\\"Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Reed\\\"),(\\\"Uriel",
"end": 7044,
"score": 0.9994958639144897,
"start": 7037,
"tag": "NAME",
"value": "Donovan"
},
{
"context": "us\\\"),(\\\"Jameson\\\"),(\\\"Nissim\\\"),(\\\"Donovan\\\"),(\\\"Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Reed\\\"),(\\\"Uriel\\\"),(\\\"Griff",
"end": 7056,
"score": 0.9994152188301086,
"start": 7051,
"tag": "NAME",
"value": "Eagan"
},
{
"context": "eson\\\"),(\\\"Nissim\\\"),(\\\"Donovan\\\"),(\\\"Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Reed\\\"),(\\\"Uriel\\\"),(\\\"Griffith\\\"),(\\\"Keato",
"end": 7071,
"score": 0.9991887211799622,
"start": 7063,
"tag": "NAME",
"value": "Caldwell"
},
{
"context": "im\\\"),(\\\"Donovan\\\"),(\\\"Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Reed\\\"),(\\\"Uriel\\\"),(\\\"Griffith\\\"),(\\\"Keaton\\\");\nINSER",
"end": 7082,
"score": 0.9994574189186096,
"start": 7078,
"tag": "NAME",
"value": "Reed"
},
{
"context": "novan\\\"),(\\\"Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Reed\\\"),(\\\"Uriel\\\"),(\\\"Griffith\\\"),(\\\"Keaton\\\");\nINSERT INTO `myTa",
"end": 7094,
"score": 0.9994624853134155,
"start": 7089,
"tag": "NAME",
"value": "Uriel"
},
{
"context": "Eagan\\\"),(\\\"Caldwell\\\"),(\\\"Reed\\\"),(\\\"Uriel\\\"),(\\\"Griffith\\\"),(\\\"Keaton\\\");\nINSERT INTO `myTable` (`name`) V",
"end": 7109,
"score": 0.9994814991950989,
"start": 7101,
"tag": "NAME",
"value": "Griffith"
},
{
"context": "dwell\\\"),(\\\"Reed\\\"),(\\\"Uriel\\\"),(\\\"Griffith\\\"),(\\\"Keaton\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Avra",
"end": 7122,
"score": 0.9988234639167786,
"start": 7116,
"tag": "NAME",
"value": "Keaton"
},
{
"context": "aton\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Avram\\\"),(\\\"Maxwell\\\"),(\\\"Giacomo\\\"),(\\\"Aristotle\\\"),(\\",
"end": 7173,
"score": 0.9995073676109314,
"start": 7168,
"tag": "NAME",
"value": "Avram"
},
{
"context": "ERT INTO `myTable` (`name`) VALUES (\\\"Avram\\\"),(\\\"Maxwell\\\"),(\\\"Giacomo\\\"),(\\\"Aristotle\\\"),(\\\"Ivor\\\"),(\\\"Cl",
"end": 7187,
"score": 0.999507486820221,
"start": 7180,
"tag": "NAME",
"value": "Maxwell"
},
{
"context": "ble` (`name`) VALUES (\\\"Avram\\\"),(\\\"Maxwell\\\"),(\\\"Giacomo\\\"),(\\\"Aristotle\\\"),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joe",
"end": 7201,
"score": 0.9994933009147644,
"start": 7194,
"tag": "NAME",
"value": "Giacomo"
},
{
"context": "VALUES (\\\"Avram\\\"),(\\\"Maxwell\\\"),(\\\"Giacomo\\\"),(\\\"Aristotle\\\"),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(",
"end": 7217,
"score": 0.9995453953742981,
"start": 7208,
"tag": "NAME",
"value": "Aristotle"
},
{
"context": "\"),(\\\"Maxwell\\\"),(\\\"Giacomo\\\"),(\\\"Aristotle\\\"),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(\\\"Dexter\\\")",
"end": 7228,
"score": 0.9990270733833313,
"start": 7224,
"tag": "NAME",
"value": "Ivor"
},
{
"context": "ll\\\"),(\\\"Giacomo\\\"),(\\\"Aristotle\\\"),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(\\\"Dexter\\\"),(\\\"Xenos\\\");",
"end": 7241,
"score": 0.9993200302124023,
"start": 7235,
"tag": "NAME",
"value": "Clarke"
},
{
"context": "omo\\\"),(\\\"Aristotle\\\"),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(\\\"Dexter\\\"),(\\\"Xenos\\\");\nINSERT INT",
"end": 7252,
"score": 0.9992414712905884,
"start": 7248,
"tag": "NAME",
"value": "Joel"
},
{
"context": "ristotle\\\"),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(\\\"Dexter\\\"),(\\\"Xenos\\\");\nINSERT INTO `myTable",
"end": 7262,
"score": 0.9993310570716858,
"start": 7259,
"tag": "NAME",
"value": "Ali"
},
{
"context": "),(\\\"Ivor\\\"),(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(\\\"Dexter\\\"),(\\\"Xenos\\\");\nINSERT INTO `myTable` (`name`) VA",
"end": 7275,
"score": 0.9963618516921997,
"start": 7269,
"tag": "NAME",
"value": "Dexter"
},
{
"context": "(\\\"Clarke\\\"),(\\\"Joel\\\"),(\\\"Ali\\\"),(\\\"Dexter\\\"),(\\\"Xenos\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Plat",
"end": 7287,
"score": 0.9028623104095459,
"start": 7282,
"tag": "NAME",
"value": "Xenos"
},
{
"context": "enos\\\");\nINSERT INTO `myTable` (`name`) VALUES (\\\"Plato\\\"),(\\\"Colby\\\"),(\\\"Rafael\\\"),(\\\"Vance\\\"),(\\\"Samuel",
"end": 7338,
"score": 0.9991555213928223,
"start": 7333,
"tag": "NAME",
"value": "Plato"
},
{
"context": "ERT INTO `myTable` (`name`) VALUES (\\\"Plato\\\"),(\\\"Colby\\\"),(\\\"Rafael\\\"),(\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daqua",
"end": 7350,
"score": 0.9994689226150513,
"start": 7345,
"tag": "NAME",
"value": "Colby"
},
{
"context": "Table` (`name`) VALUES (\\\"Plato\\\"),(\\\"Colby\\\"),(\\\"Rafael\\\"),(\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"",
"end": 7363,
"score": 0.9994670748710632,
"start": 7357,
"tag": "NAME",
"value": "Rafael"
},
{
"context": "`) VALUES (\\\"Plato\\\"),(\\\"Colby\\\"),(\\\"Rafael\\\"),(\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\",
"end": 7375,
"score": 0.9989145994186401,
"start": 7370,
"tag": "NAME",
"value": "Vance"
},
{
"context": "\"Plato\\\"),(\\\"Colby\\\"),(\\\"Rafael\\\"),(\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\\"),(\\\"Wayne\\\"",
"end": 7388,
"score": 0.9993904829025269,
"start": 7382,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "Colby\\\"),(\\\"Rafael\\\"),(\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\\"),(\\\"Wayne\\\"),(\\\"David\\\")",
"end": 7401,
"score": 0.9991288185119629,
"start": 7395,
"tag": "NAME",
"value": "Daquan"
},
{
"context": "afael\\\"),(\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\\"),(\\\"Wayne\\\"),(\\\"David\\\");\n\n\")\n ",
"end": 7411,
"score": 0.9984700083732605,
"start": 7408,
"tag": "NAME",
"value": "Tad"
},
{
"context": "\\\"Vance\\\"),(\\\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\\"),(\\\"Wayne\\\"),(\\\"David\\\");\n\n\")\n .a",
"end": 7424,
"score": 0.9993603229522705,
"start": 7418,
"tag": "NAME",
"value": "Isaiah"
},
{
"context": "\"Samuel\\\"),(\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\\"),(\\\"Wayne\\\"),(\\\"David\\\");\n\n\")\n .ariaLabel(\"结果",
"end": 7436,
"score": 0.9989989995956421,
"start": 7431,
"tag": "NAME",
"value": "Wayne"
},
{
"context": "\\\"Daquan\\\"),(\\\"Tad\\\"),(\\\"Isaiah\\\"),(\\\"Wayne\\\"),(\\\"David\\\");\n\n\")\n .ariaLabel(\"结果\")\n ",
"end": 7448,
"score": 0.9967833757400513,
"start": 7443,
"tag": "NAME",
"value": "David"
}
] | src/coffee/controller/dataMakerController.coffee | shenshen/dataMaker | 0 | define [], ()->
_ = require("underscore/underscore")
textData = require("../data/textData")
angular.module "dataMaker", ["ngMaterial"]
.controller "AppCtrl", [
"$scope", "$mdDialog", ($scope, $mdDialog)->
tempId = 1
$scope.types =
'array':
name: "数组"
category: "数值类型"
_hasChildren: ()->
true
opt:
valuein: ""
getter: (opt)->
return {
run: ->
}
'object':
name: "对象"
category: "数值类型"
_hasChildren: ()->
return true
getter: ()->
return {
run: ->
{}
}
'email':
name: "Email"
category: "人相关的"
example: "example@qq.com"
defaultValue: ""
getter: (opt)->
debugger
'string':
name: "字符串"
category: "数值类型"
opt:
max: 10 #最大长度
min: 0 #最小长度
valuein: ""
textType: 1 #1=chineseText 2=englishSingle 3=englishText
getter: (opt)->
if opt.valuein
result = opt.valuein.split "|"
else
text = textData[opt.textType]
return {
run: ()->
if opt.valuein
return result[parseInt(Math.random() * result.length)]
else
result = ""
while result.length <= opt.min
max = opt.max - result.length
min = opt.min - result.length
strIndex = parseInt(Math.random() * (max - min + 1) + min)
result += text.substring 0, strIndex
return result
}
'date':
name: "日期"
disabled: true
'phone':
name: "手机号"
disabled: true
'country':
name: "国家"
disabled: true
$scope.struct =
root:
type: "object"
name: "root"
level: 0
opt: {}
_child: $scope.types['object']._hasChildren
_childItem: {}
$scope.addStruct = (node)->
node._childItem = node._childItem || {}
node._childItem["data#{tempId}"] = {
level: node.level + 1
name: "data#{tempId++}"
}
$scope.delStruct = (parent, key, value)->
delete parent._childItem[key]
$scope.changeType = (node)->
node._child = $scope.types[node.type]._hasChildren
node._childItem = {}
node.opt = {}
if node.type == 'array'
node.opt.childType = 0
if node.type == "string"
node.opt.textType = "chineseText"
itemGetter = null
$scope.doCreate = ()->
result = ""
renderArray = (obj)->
a = []
count = obj.opt.childLength
while count-- > 0
_.each obj._childItem, (value)->
if value.type is "object"
a.push renderObject(value)
else if value.type is "array"
a.push renderArray(value)
else
a.push $scope.types[value.type].getter(value.opt).run()
return a
renderObject = (obj)->
a = {}
_.each obj._childItem, (value)->
if value.type is "object"
a[value.name] = renderObject(value)
else if value.type is "array"
a[value.name] = renderArray(value)
else
a[value.name] = $scope.types[value.type].getter(value.opt).run()
return a
if $scope.struct.root.type is "array"
result = renderArray $scope.struct.root
else if $scope.struct.root.type is "object"
result = renderObject $scope.struct.root
else result = $scope.types[$scope.struct.root.type].getter($scope.struct.root.opt).run()
return result
$scope.doCreateJson = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content(JSON.stringify result)
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.doCreateJs = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content("var data = #{JSON.stringify(result)}")
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.doCreateMySql = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content("
DROP TABLE `myTable`;
CREATE TABLE `myTable` (
`id` mediumint(8) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;
INSERT INTO `myTable` (`name`) VALUES (\"Len\"),(\"Brendan\"),(\"Allistair\"),(\"Talon\"),(\"Keefe\"),(\"Hilel\"),(\"Ezra\"),(\"Duncan\"),(\"Talon\"),(\"Ezra\");
INSERT INTO `myTable` (`name`) VALUES (\"Tyrone\"),(\"Caleb\"),(\"Gregory\"),(\"Lucas\"),(\"Brenden\"),(\"Dennis\"),(\"Brendan\"),(\"Armand\"),(\"Ezekiel\"),(\"Stephen\");
INSERT INTO `myTable` (`name`) VALUES (\"Joseph\"),(\"Duncan\"),(\"Tyrone\"),(\"Alden\"),(\"Vaughan\"),(\"Macaulay\"),(\"Abraham\"),(\"Thaddeus\"),(\"Brandon\"),(\"Brent\");
INSERT INTO `myTable` (`name`) VALUES (\"Orson\"),(\"Chase\"),(\"Brady\"),(\"Graham\"),(\"Xander\"),(\"Neil\"),(\"Brady\"),(\"Donovan\"),(\"Ahmed\"),(\"Zeph\");
INSERT INTO `myTable` (`name`) VALUES (\"Rudyard\"),(\"Quinlan\"),(\"Neil\"),(\"Rigel\"),(\"Phillip\"),(\"Lucas\"),(\"Quamar\"),(\"Dustin\"),(\"Devin\"),(\"Julian\");
INSERT INTO `myTable` (`name`) VALUES (\"Clarke\"),(\"Ethan\"),(\"Adam\"),(\"Armand\"),(\"Drew\"),(\"George\"),(\"Basil\"),(\"Ignatius\"),(\"Norman\"),(\"Dexter\");
INSERT INTO `myTable` (`name`) VALUES (\"Ian\"),(\"Herrod\"),(\"Ashton\"),(\"August\"),(\"Josiah\"),(\"James\"),(\"Patrick\"),(\"Timothy\"),(\"Phelan\"),(\"Baker\");
INSERT INTO `myTable` (`name`) VALUES (\"Lucius\"),(\"Jameson\"),(\"Nissim\"),(\"Donovan\"),(\"Eagan\"),(\"Caldwell\"),(\"Reed\"),(\"Uriel\"),(\"Griffith\"),(\"Keaton\");
INSERT INTO `myTable` (`name`) VALUES (\"Avram\"),(\"Maxwell\"),(\"Giacomo\"),(\"Aristotle\"),(\"Ivor\"),(\"Clarke\"),(\"Joel\"),(\"Ali\"),(\"Dexter\"),(\"Xenos\");
INSERT INTO `myTable` (`name`) VALUES (\"Plato\"),(\"Colby\"),(\"Rafael\"),(\"Vance\"),(\"Samuel\"),(\"Daquan\"),(\"Tad\"),(\"Isaiah\"),(\"Wayne\"),(\"David\");
")
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.changeArrayType = (node)->
node._childItem = {}
return this
] | 56232 | define [], ()->
_ = require("underscore/underscore")
textData = require("../data/textData")
angular.module "dataMaker", ["ngMaterial"]
.controller "AppCtrl", [
"$scope", "$mdDialog", ($scope, $mdDialog)->
tempId = 1
$scope.types =
'array':
name: "数组"
category: "数值类型"
_hasChildren: ()->
true
opt:
valuein: ""
getter: (opt)->
return {
run: ->
}
'object':
name: "对象"
category: "数值类型"
_hasChildren: ()->
return true
getter: ()->
return {
run: ->
{}
}
'email':
name: "Email"
category: "人相关的"
example: "<EMAIL>"
defaultValue: ""
getter: (opt)->
debugger
'string':
name: "字符串"
category: "数值类型"
opt:
max: 10 #最大长度
min: 0 #最小长度
valuein: ""
textType: 1 #1=chineseText 2=englishSingle 3=englishText
getter: (opt)->
if opt.valuein
result = opt.valuein.split "|"
else
text = textData[opt.textType]
return {
run: ()->
if opt.valuein
return result[parseInt(Math.random() * result.length)]
else
result = ""
while result.length <= opt.min
max = opt.max - result.length
min = opt.min - result.length
strIndex = parseInt(Math.random() * (max - min + 1) + min)
result += text.substring 0, strIndex
return result
}
'date':
name: "日期"
disabled: true
'phone':
name: "手机号"
disabled: true
'country':
name: "国家"
disabled: true
$scope.struct =
root:
type: "object"
name: "root"
level: 0
opt: {}
_child: $scope.types['object']._hasChildren
_childItem: {}
$scope.addStruct = (node)->
node._childItem = node._childItem || {}
node._childItem["data#{tempId}"] = {
level: node.level + 1
name: "data#{tempId++}"
}
$scope.delStruct = (parent, key, value)->
delete parent._childItem[key]
$scope.changeType = (node)->
node._child = $scope.types[node.type]._hasChildren
node._childItem = {}
node.opt = {}
if node.type == 'array'
node.opt.childType = 0
if node.type == "string"
node.opt.textType = "chineseText"
itemGetter = null
$scope.doCreate = ()->
result = ""
renderArray = (obj)->
a = []
count = obj.opt.childLength
while count-- > 0
_.each obj._childItem, (value)->
if value.type is "object"
a.push renderObject(value)
else if value.type is "array"
a.push renderArray(value)
else
a.push $scope.types[value.type].getter(value.opt).run()
return a
renderObject = (obj)->
a = {}
_.each obj._childItem, (value)->
if value.type is "object"
a[value.name] = renderObject(value)
else if value.type is "array"
a[value.name] = renderArray(value)
else
a[value.name] = $scope.types[value.type].getter(value.opt).run()
return a
if $scope.struct.root.type is "array"
result = renderArray $scope.struct.root
else if $scope.struct.root.type is "object"
result = renderObject $scope.struct.root
else result = $scope.types[$scope.struct.root.type].getter($scope.struct.root.opt).run()
return result
$scope.doCreateJson = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content(JSON.stringify result)
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.doCreateJs = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content("var data = #{JSON.stringify(result)}")
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.doCreateMySql = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content("
DROP TABLE `myTable`;
CREATE TABLE `myTable` (
`id` mediumint(8) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
INSERT INTO `myTable` (`name`) VALUES (\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\"),(\"<NAME>\");
")
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.changeArrayType = (node)->
node._childItem = {}
return this
] | true | define [], ()->
_ = require("underscore/underscore")
textData = require("../data/textData")
angular.module "dataMaker", ["ngMaterial"]
.controller "AppCtrl", [
"$scope", "$mdDialog", ($scope, $mdDialog)->
tempId = 1
$scope.types =
'array':
name: "数组"
category: "数值类型"
_hasChildren: ()->
true
opt:
valuein: ""
getter: (opt)->
return {
run: ->
}
'object':
name: "对象"
category: "数值类型"
_hasChildren: ()->
return true
getter: ()->
return {
run: ->
{}
}
'email':
name: "Email"
category: "人相关的"
example: "PI:EMAIL:<EMAIL>END_PI"
defaultValue: ""
getter: (opt)->
debugger
'string':
name: "字符串"
category: "数值类型"
opt:
max: 10 #最大长度
min: 0 #最小长度
valuein: ""
textType: 1 #1=chineseText 2=englishSingle 3=englishText
getter: (opt)->
if opt.valuein
result = opt.valuein.split "|"
else
text = textData[opt.textType]
return {
run: ()->
if opt.valuein
return result[parseInt(Math.random() * result.length)]
else
result = ""
while result.length <= opt.min
max = opt.max - result.length
min = opt.min - result.length
strIndex = parseInt(Math.random() * (max - min + 1) + min)
result += text.substring 0, strIndex
return result
}
'date':
name: "日期"
disabled: true
'phone':
name: "手机号"
disabled: true
'country':
name: "国家"
disabled: true
$scope.struct =
root:
type: "object"
name: "root"
level: 0
opt: {}
_child: $scope.types['object']._hasChildren
_childItem: {}
$scope.addStruct = (node)->
node._childItem = node._childItem || {}
node._childItem["data#{tempId}"] = {
level: node.level + 1
name: "data#{tempId++}"
}
$scope.delStruct = (parent, key, value)->
delete parent._childItem[key]
$scope.changeType = (node)->
node._child = $scope.types[node.type]._hasChildren
node._childItem = {}
node.opt = {}
if node.type == 'array'
node.opt.childType = 0
if node.type == "string"
node.opt.textType = "chineseText"
itemGetter = null
$scope.doCreate = ()->
result = ""
renderArray = (obj)->
a = []
count = obj.opt.childLength
while count-- > 0
_.each obj._childItem, (value)->
if value.type is "object"
a.push renderObject(value)
else if value.type is "array"
a.push renderArray(value)
else
a.push $scope.types[value.type].getter(value.opt).run()
return a
renderObject = (obj)->
a = {}
_.each obj._childItem, (value)->
if value.type is "object"
a[value.name] = renderObject(value)
else if value.type is "array"
a[value.name] = renderArray(value)
else
a[value.name] = $scope.types[value.type].getter(value.opt).run()
return a
if $scope.struct.root.type is "array"
result = renderArray $scope.struct.root
else if $scope.struct.root.type is "object"
result = renderObject $scope.struct.root
else result = $scope.types[$scope.struct.root.type].getter($scope.struct.root.opt).run()
return result
$scope.doCreateJson = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content(JSON.stringify result)
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.doCreateJs = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content("var data = #{JSON.stringify(result)}")
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.doCreateMySql = (ev)->
result = $scope.doCreate()
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.body))
.title("结果")
.content("
DROP TABLE `myTable`;
CREATE TABLE `myTable` (
`id` mediumint(8) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
PRIMARY KEY (`id`)
) AUTO_INCREMENT=1;
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
INSERT INTO `myTable` (`name`) VALUES (\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\"),(\"PI:NAME:<NAME>END_PI\");
")
.ariaLabel("结果")
.ok("确定")
.targetEvent(ev)
)
$scope.changeArrayType = (node)->
node._childItem = {}
return this
] |
[
{
"context": "le guide please refer to\n * https://github.com/MBV-Media/CoffeeScript-Style-Guide\n *\n * @since 1.0.0\n *",
"end": 242,
"score": 0.6905002593994141,
"start": 235,
"tag": "USERNAME",
"value": "V-Media"
},
{
"context": "cript-Style-Guide\n *\n * @since 1.0.0\n * @author R4c00n <marcel.kempf93@gmail.com>\n * @license MIT\n###\n'",
"end": 307,
"score": 0.999671459197998,
"start": 301,
"tag": "USERNAME",
"value": "R4c00n"
},
{
"context": "le-Guide\n *\n * @since 1.0.0\n * @author R4c00n <marcel.kempf93@gmail.com>\n * @license MIT\n###\n'use strict'\n\njQuery ($) ->",
"end": 333,
"score": 0.9999309182167053,
"start": 309,
"tag": "EMAIL",
"value": "marcel.kempf93@gmail.com"
}
] | src/js/main.coffee | JeffPlo/skGruendau | 0 | ###*
* Your JS/CoffeeScript goes here
* Components like custom classes are in components/
* Third party libraries are in vendor/ or /bower_components/
*
* For CoffeeScript style guide please refer to
* https://github.com/MBV-Media/CoffeeScript-Style-Guide
*
* @since 1.0.0
* @author R4c00n <marcel.kempf93@gmail.com>
* @license MIT
###
'use strict'
jQuery ($) ->
###*
* Initialize modules/plugins/etc.
*
* @since 1.0.0
* @return {void}
###
init = ->
$(document).foundation()
initEvents()
###*
* Initialize global events.
*
* @since 1.0.0
* @return {void}
###
initEvents = ->
$(window).load onReady
$(document).on 'click', '.gp-tabs .not-loaded', getPostContent
$(document).on 'click', '.table-tabs .not-loaded', getTableContent
###*
* Log "Everything loaded".
*
* @since 1.0.0
* @return {void}
###
onReady = ->
$('.gp-tabs').tabs()
$('.table-tabs').tabs()
getTableContent = ->
element = $(this)
if(element.hasClass('not-loaded'))
leagueId = element.data('league-id')
teamId = element.data('team-id')
type = element.data('type')
targetElement = $('#tabs-' + teamId)
data = {
action: 'get_data'
leagueId: leagueId
type: type
function: 'getTableContent'
nonce: adminAjax.nonce
}
$.ajax
url: adminAjax.ajaxurl
type: 'post'
dataType: 'html'
data: data
error: (jqXHR, textStatus, errorThrown) ->
console.log(textStatus, errorThrown)
success: (response) ->
targetElement.html(response)
element.removeClass('not-loaded')
getPostContent = ->
element = $(this)
if(element.hasClass('not-loaded'))
postId = element.data('post-id')
targetElement = $('#tabs-' + postId)
data = {
action: 'get_data'
postId: postId
function: 'getPostContent'
nonce: adminAjax.nonce
}
$.ajax
url: adminAjax.ajaxurl
type: 'post'
dataType: 'html'
data: data
error: (jqXHR, textStatus, errorThrown) ->
console.log(textStatus, errorThrown)
success: (response) ->
targetElement.html(response)
element.removeClass('not-loaded')
init() | 14694 | ###*
* Your JS/CoffeeScript goes here
* Components like custom classes are in components/
* Third party libraries are in vendor/ or /bower_components/
*
* For CoffeeScript style guide please refer to
* https://github.com/MBV-Media/CoffeeScript-Style-Guide
*
* @since 1.0.0
* @author R4c00n <<EMAIL>>
* @license MIT
###
'use strict'
jQuery ($) ->
###*
* Initialize modules/plugins/etc.
*
* @since 1.0.0
* @return {void}
###
init = ->
$(document).foundation()
initEvents()
###*
* Initialize global events.
*
* @since 1.0.0
* @return {void}
###
initEvents = ->
$(window).load onReady
$(document).on 'click', '.gp-tabs .not-loaded', getPostContent
$(document).on 'click', '.table-tabs .not-loaded', getTableContent
###*
* Log "Everything loaded".
*
* @since 1.0.0
* @return {void}
###
onReady = ->
$('.gp-tabs').tabs()
$('.table-tabs').tabs()
getTableContent = ->
element = $(this)
if(element.hasClass('not-loaded'))
leagueId = element.data('league-id')
teamId = element.data('team-id')
type = element.data('type')
targetElement = $('#tabs-' + teamId)
data = {
action: 'get_data'
leagueId: leagueId
type: type
function: 'getTableContent'
nonce: adminAjax.nonce
}
$.ajax
url: adminAjax.ajaxurl
type: 'post'
dataType: 'html'
data: data
error: (jqXHR, textStatus, errorThrown) ->
console.log(textStatus, errorThrown)
success: (response) ->
targetElement.html(response)
element.removeClass('not-loaded')
getPostContent = ->
element = $(this)
if(element.hasClass('not-loaded'))
postId = element.data('post-id')
targetElement = $('#tabs-' + postId)
data = {
action: 'get_data'
postId: postId
function: 'getPostContent'
nonce: adminAjax.nonce
}
$.ajax
url: adminAjax.ajaxurl
type: 'post'
dataType: 'html'
data: data
error: (jqXHR, textStatus, errorThrown) ->
console.log(textStatus, errorThrown)
success: (response) ->
targetElement.html(response)
element.removeClass('not-loaded')
init() | true | ###*
* Your JS/CoffeeScript goes here
* Components like custom classes are in components/
* Third party libraries are in vendor/ or /bower_components/
*
* For CoffeeScript style guide please refer to
* https://github.com/MBV-Media/CoffeeScript-Style-Guide
*
* @since 1.0.0
* @author R4c00n <PI:EMAIL:<EMAIL>END_PI>
* @license MIT
###
'use strict'
jQuery ($) ->
###*
* Initialize modules/plugins/etc.
*
* @since 1.0.0
* @return {void}
###
init = ->
$(document).foundation()
initEvents()
###*
* Initialize global events.
*
* @since 1.0.0
* @return {void}
###
initEvents = ->
$(window).load onReady
$(document).on 'click', '.gp-tabs .not-loaded', getPostContent
$(document).on 'click', '.table-tabs .not-loaded', getTableContent
###*
* Log "Everything loaded".
*
* @since 1.0.0
* @return {void}
###
onReady = ->
$('.gp-tabs').tabs()
$('.table-tabs').tabs()
getTableContent = ->
element = $(this)
if(element.hasClass('not-loaded'))
leagueId = element.data('league-id')
teamId = element.data('team-id')
type = element.data('type')
targetElement = $('#tabs-' + teamId)
data = {
action: 'get_data'
leagueId: leagueId
type: type
function: 'getTableContent'
nonce: adminAjax.nonce
}
$.ajax
url: adminAjax.ajaxurl
type: 'post'
dataType: 'html'
data: data
error: (jqXHR, textStatus, errorThrown) ->
console.log(textStatus, errorThrown)
success: (response) ->
targetElement.html(response)
element.removeClass('not-loaded')
getPostContent = ->
element = $(this)
if(element.hasClass('not-loaded'))
postId = element.data('post-id')
targetElement = $('#tabs-' + postId)
data = {
action: 'get_data'
postId: postId
function: 'getPostContent'
nonce: adminAjax.nonce
}
$.ajax
url: adminAjax.ajaxurl
type: 'post'
dataType: 'html'
data: data
error: (jqXHR, textStatus, errorThrown) ->
console.log(textStatus, errorThrown)
success: (response) ->
targetElement.html(response)
element.removeClass('not-loaded')
init() |
[
{
"context": "@Config =\n\tname: 'My App'\n\ttitle: ->\n\t\t\tTAPi18n.__ 'configTitle'\n\tsubt",
"end": 20,
"score": 0.49717894196510315,
"start": 18,
"tag": "NAME",
"value": "My"
},
{
"context": ": 'http://benjaminpeterjones.com'\n\tabout: 'http://benjaminpeterjones.com'\n\tusername: false\n\thomeRoute: ",
"end": 319,
"score": 0.5133510231971741,
"start": 316,
"tag": "USERNAME",
"value": "ben"
},
{
"context": "board'\n\tsocialMedia:\n\t\t[\n\t\t\t['http://facebook.com/benjaminpeterjones','facebook']\n\t\t\t['http://twitter.com/BenPeterJone",
"end": 443,
"score": 0.9996790289878845,
"start": 425,
"tag": "USERNAME",
"value": "benjaminpeterjones"
},
{
"context": "inpeterjones','facebook']\n\t\t\t['http://twitter.com/BenPeterJones','twitter']\n\t\t\t['http://github.com/yogiben','gith",
"end": 494,
"score": 0.9996636509895325,
"start": 481,
"tag": "USERNAME",
"value": "BenPeterJones"
},
{
"context": "/BenPeterJones','twitter']\n\t\t\t['http://github.com/yogiben','github']\n\t\t]\n\nAvatar.options =\n\tcustomImageProp",
"end": 537,
"score": 0.9997062087059021,
"start": 530,
"tag": "USERNAME",
"value": "yogiben"
}
] | both/config/_config.coffee | stephenpfaff/ua-suite | 0 | @Config =
name: 'My App'
title: ->
TAPi18n.__ 'configTitle'
subtitle: ->
TAPi18n.__ 'configSubtitle'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
emails:
from: 'noreply@' + Meteor.absoluteUrl()
blog: 'http://benjaminpeterjones.com'
about: 'http://benjaminpeterjones.com'
username: false
homeRoute: '/dashboard'
socialMedia:
[
['http://facebook.com/benjaminpeterjones','facebook']
['http://twitter.com/BenPeterJones','twitter']
['http://github.com/yogiben','github']
]
Avatar.options =
customImageProperty: 'profile.picture'
Meteor.startup ->
if Meteor.isClient
TAPi18n.setLanguage('en')
| 194579 | @Config =
name: '<NAME> App'
title: ->
TAPi18n.__ 'configTitle'
subtitle: ->
TAPi18n.__ 'configSubtitle'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
emails:
from: 'noreply@' + Meteor.absoluteUrl()
blog: 'http://benjaminpeterjones.com'
about: 'http://benjaminpeterjones.com'
username: false
homeRoute: '/dashboard'
socialMedia:
[
['http://facebook.com/benjaminpeterjones','facebook']
['http://twitter.com/BenPeterJones','twitter']
['http://github.com/yogiben','github']
]
Avatar.options =
customImageProperty: 'profile.picture'
Meteor.startup ->
if Meteor.isClient
TAPi18n.setLanguage('en')
| true | @Config =
name: 'PI:NAME:<NAME>END_PI App'
title: ->
TAPi18n.__ 'configTitle'
subtitle: ->
TAPi18n.__ 'configSubtitle'
logo: ->
'<b>' + @name + '</b>'
footer: ->
@name + ' - Copyright ' + new Date().getFullYear()
emails:
from: 'noreply@' + Meteor.absoluteUrl()
blog: 'http://benjaminpeterjones.com'
about: 'http://benjaminpeterjones.com'
username: false
homeRoute: '/dashboard'
socialMedia:
[
['http://facebook.com/benjaminpeterjones','facebook']
['http://twitter.com/BenPeterJones','twitter']
['http://github.com/yogiben','github']
]
Avatar.options =
customImageProperty: 'profile.picture'
Meteor.startup ->
if Meteor.isClient
TAPi18n.setLanguage('en')
|
[
{
"context": " - Show/change current k8s context\n#\n# Author:\n# canthefason\nmodule.exports = (robot) ->\n\n getContext = (res)",
"end": 368,
"score": 0.9996257424354553,
"start": 357,
"tag": "USERNAME",
"value": "canthefason"
},
{
"context": " (res) ->\n user = res.message.user.id\n key = \"#{user}.context\"\n\n return robot.brain.get(key) or defaultCtx\n\n",
"end": 479,
"score": 0.985037088394165,
"start": 463,
"tag": "KEY",
"value": "\"#{user}.context"
},
{
"context": "ntext) ->\n user = res.message.user.id\n key = \"#{user}.context\"\n\n return robot.brain.set(key, context or defa",
"end": 619,
"score": 0.9935901165008545,
"start": 603,
"tag": "KEY",
"value": "\"#{user}.context"
},
{
"context": "e\n requestOptions['auth'] =\n user: user\n pass: @tokenMap[user]\n\n request.get ",
"end": 4460,
"score": 0.7170737385749817,
"start": 4456,
"tag": "USERNAME",
"value": "user"
},
{
"context": "s['auth'] =\n user: user\n pass: @tokenMap[user]\n\n request.get requestOptions, (err, resp",
"end": 4486,
"score": 0.7370601892471313,
"start": 4478,
"tag": "PASSWORD",
"value": "tokenMap"
}
] | src/kubernetes.coffee | sbueringer/hubot-kubernetes | 1 | # Description:
# Hubot Kubernetes REST API helper commands.
#
# Dependencies:
# None
#
# Configuration:
# KUBE_HOST
# KUBE_VERSION
# KUBE_CONTEXT
# KUBE_CA
# KUBE_TOKENS
#
# Commands:
# hubot k8s [po|rc|svc] (labels) - List all k8s resources under given context
# hubot k8s context <name> - Show/change current k8s context
#
# Author:
# canthefason
module.exports = (robot) ->
getContext = (res) ->
user = res.message.user.id
key = "#{user}.context"
return robot.brain.get(key) or defaultCtx
setContext = (res, context) ->
user = res.message.user.id
key = "#{user}.context"
return robot.brain.set(key, context or defaultCtx)
defaultCtx = "default" or process.env.KUBE_CONTEXT
kubeapi = new Request()
aliasMap =
"svc": "services"
"rc": "replicationcontrollers"
"po": "pods"
decorateFnMap =
'replicationcontrollers': (response) ->
reply = ''
for rc in response.items
image = rc.spec.template.spec.containers[0].image
{metadata: {name, creationTimestamp}, spec: {replicas}} = rc
reply += ">*#{name}*: \n"+
">Replicas: #{replicas}\n>Age: #{timeSince(creationTimestamp)}\n"+
">Image: #{image}\n"
return reply
'services': (response) ->
reply = ''
for service in response.items
{metadata: {creationTimestamp}, spec: {clusterIP, ports}} = service
ps = ""
for p in ports
{protocol, port} = p
ps += "#{port}/#{protocol} "
reply += ">*#{service.metadata.name}*:\n" +
">Cluster ip: #{clusterIP}\n>Ports: #{ps}\n>Age: #{timeSince(creationTimestamp)}\n"
return reply
'pods': (response) ->
reply = ''
for pod in response.items
{metadata: {name}, status: {phase, startTime, containerStatuses}} = pod
reply += ">*#{name}*: \n>Status: #{phase} for: #{timeSince(startTime)} \n"
for cs in containerStatuses
{name, restartCount, image} = cs
reply += ">Name: #{name} \n>Restarts: #{restartCount}\n>Image: #{image}\n"
return reply
robot.respond /k8s\s*(services|pods|replicationcontrollers|svc|po|rc)\s*(.+)?/i, (res) ->
namespace = getContext(res)
type = res.match[1]
if alias = aliasMap[type] then type = alias
url = "namespaces/#{namespace}/#{type}"
if res.match[2] and res.match[2] != ""
url += "?labelSelector=#{res.match[2].trim()}"
roles = ["admin"]
if (robot.hasOwnProperty("auth"))
roles = robot.auth.userRoles res.envelope.user
kubeapi.get {path: url, roles}, (err, response) ->
if err
robot.logger.error err
return res.send "Could not fetch #{type} on *#{namespace}*"
return res.reply 'Requested resource is not found' unless response.items and response.items.length
reply = "\n"
decorateFn = decorateFnMap[type] or ->
reply = "Here is the list of #{type} running on *#{namespace}*\n"
reply += decorateFn response
res.reply reply
# update/fetch kubernetes context
robot.respond /k8s\s*context\s*(.+)?/i, (res) ->
context = res.match[1]
if not context or context is ""
return res.reply "Your current context is: `#{getContext(res)}`"
setContext res, context
res.reply "Your current context is changed to `#{context}`"
class Request
request = require 'request'
constructor: ->
caFile = process.env.KUBE_CA
if caFile and caFile != ""
fs = require('fs')
path = require('path')
@ca = fs.readFileSync(caFile)
@tokenMap = generateTokens()
host = process.env.KUBE_HOST or 'https://localhost'
version = process.env.KUBE_VERSION or 'v1'
@domain = host + '/api/' + version + '/'
getKubeUser: (roles) ->
# if there is only one token, then return it right away
if @tokenMap.length is 1
for role, token of @tokenMap
return role
for role in roles
if @tokenMap[role]
return role
if @tokenMap["bearer_"+role]
return "bearer_"+role
return ""
get: ({path, roles}, callback) ->
requestOptions =
url : @domain + path
if @ca
requestOptions.agentOptions =
ca: @ca
authOptions = {}
user = @getKubeUser roles
if user and user isnt ""
if user.search 'bearer_' == 0
requestOptions['auth'] =
bearer: @tokenMap[user]
else
requestOptions['auth'] =
user: user
pass: @tokenMap[user]
request.get requestOptions, (err, response, data) ->
return callback(err) if err
if response.statusCode != 200
return callback new Error("Status code is not OK: #{response.statusCode}")
callback null, JSON.parse(data)
generateTokens = ->
tokens = {}
tokensVar = process.env.KUBE_TOKENS
if tokensVar
tokenArr = tokensVar.split(',')
for token in tokenArr
keyPair = token.split(":")
unless keyPair.length is 2
continue
tokens[keyPair[0]] = keyPair[1]
tokensVarBearer = process.env.KUBE_TOKENS_BEARER
if tokensVarBearer
tokenBearerArr = tokensVarBearer.split(',')
for token in tokenBearerArr
keyPair = token.split(":")
unless keyPair.length is 2
continue
tokens["bearer_" + keyPair[0]] = keyPair[1]
return tokens
timeSince = (date) ->
d = new Date(date).getTime()
seconds = Math.floor((new Date() - d) / 1000)
return "#{Math.floor(seconds)}s" if seconds < 60
return "#{Math.floor(seconds/60)}m" if seconds < 3600
return "#{Math.floor(seconds/3600)}h" if seconds < 86400
return "#{Math.floor(seconds/86400)}d" if seconds < 2592000
return "#{Math.floor(seconds/2592000)}mo" if seconds < 31536000
return "#{Math.floor(seconds/31536000)}y"
| 117699 | # Description:
# Hubot Kubernetes REST API helper commands.
#
# Dependencies:
# None
#
# Configuration:
# KUBE_HOST
# KUBE_VERSION
# KUBE_CONTEXT
# KUBE_CA
# KUBE_TOKENS
#
# Commands:
# hubot k8s [po|rc|svc] (labels) - List all k8s resources under given context
# hubot k8s context <name> - Show/change current k8s context
#
# Author:
# canthefason
module.exports = (robot) ->
getContext = (res) ->
user = res.message.user.id
key = <KEY>"
return robot.brain.get(key) or defaultCtx
setContext = (res, context) ->
user = res.message.user.id
key = <KEY>"
return robot.brain.set(key, context or defaultCtx)
defaultCtx = "default" or process.env.KUBE_CONTEXT
kubeapi = new Request()
aliasMap =
"svc": "services"
"rc": "replicationcontrollers"
"po": "pods"
decorateFnMap =
'replicationcontrollers': (response) ->
reply = ''
for rc in response.items
image = rc.spec.template.spec.containers[0].image
{metadata: {name, creationTimestamp}, spec: {replicas}} = rc
reply += ">*#{name}*: \n"+
">Replicas: #{replicas}\n>Age: #{timeSince(creationTimestamp)}\n"+
">Image: #{image}\n"
return reply
'services': (response) ->
reply = ''
for service in response.items
{metadata: {creationTimestamp}, spec: {clusterIP, ports}} = service
ps = ""
for p in ports
{protocol, port} = p
ps += "#{port}/#{protocol} "
reply += ">*#{service.metadata.name}*:\n" +
">Cluster ip: #{clusterIP}\n>Ports: #{ps}\n>Age: #{timeSince(creationTimestamp)}\n"
return reply
'pods': (response) ->
reply = ''
for pod in response.items
{metadata: {name}, status: {phase, startTime, containerStatuses}} = pod
reply += ">*#{name}*: \n>Status: #{phase} for: #{timeSince(startTime)} \n"
for cs in containerStatuses
{name, restartCount, image} = cs
reply += ">Name: #{name} \n>Restarts: #{restartCount}\n>Image: #{image}\n"
return reply
robot.respond /k8s\s*(services|pods|replicationcontrollers|svc|po|rc)\s*(.+)?/i, (res) ->
namespace = getContext(res)
type = res.match[1]
if alias = aliasMap[type] then type = alias
url = "namespaces/#{namespace}/#{type}"
if res.match[2] and res.match[2] != ""
url += "?labelSelector=#{res.match[2].trim()}"
roles = ["admin"]
if (robot.hasOwnProperty("auth"))
roles = robot.auth.userRoles res.envelope.user
kubeapi.get {path: url, roles}, (err, response) ->
if err
robot.logger.error err
return res.send "Could not fetch #{type} on *#{namespace}*"
return res.reply 'Requested resource is not found' unless response.items and response.items.length
reply = "\n"
decorateFn = decorateFnMap[type] or ->
reply = "Here is the list of #{type} running on *#{namespace}*\n"
reply += decorateFn response
res.reply reply
# update/fetch kubernetes context
robot.respond /k8s\s*context\s*(.+)?/i, (res) ->
context = res.match[1]
if not context or context is ""
return res.reply "Your current context is: `#{getContext(res)}`"
setContext res, context
res.reply "Your current context is changed to `#{context}`"
class Request
request = require 'request'
constructor: ->
caFile = process.env.KUBE_CA
if caFile and caFile != ""
fs = require('fs')
path = require('path')
@ca = fs.readFileSync(caFile)
@tokenMap = generateTokens()
host = process.env.KUBE_HOST or 'https://localhost'
version = process.env.KUBE_VERSION or 'v1'
@domain = host + '/api/' + version + '/'
getKubeUser: (roles) ->
# if there is only one token, then return it right away
if @tokenMap.length is 1
for role, token of @tokenMap
return role
for role in roles
if @tokenMap[role]
return role
if @tokenMap["bearer_"+role]
return "bearer_"+role
return ""
get: ({path, roles}, callback) ->
requestOptions =
url : @domain + path
if @ca
requestOptions.agentOptions =
ca: @ca
authOptions = {}
user = @getKubeUser roles
if user and user isnt ""
if user.search 'bearer_' == 0
requestOptions['auth'] =
bearer: @tokenMap[user]
else
requestOptions['auth'] =
user: user
pass: @<PASSWORD>[user]
request.get requestOptions, (err, response, data) ->
return callback(err) if err
if response.statusCode != 200
return callback new Error("Status code is not OK: #{response.statusCode}")
callback null, JSON.parse(data)
generateTokens = ->
tokens = {}
tokensVar = process.env.KUBE_TOKENS
if tokensVar
tokenArr = tokensVar.split(',')
for token in tokenArr
keyPair = token.split(":")
unless keyPair.length is 2
continue
tokens[keyPair[0]] = keyPair[1]
tokensVarBearer = process.env.KUBE_TOKENS_BEARER
if tokensVarBearer
tokenBearerArr = tokensVarBearer.split(',')
for token in tokenBearerArr
keyPair = token.split(":")
unless keyPair.length is 2
continue
tokens["bearer_" + keyPair[0]] = keyPair[1]
return tokens
timeSince = (date) ->
d = new Date(date).getTime()
seconds = Math.floor((new Date() - d) / 1000)
return "#{Math.floor(seconds)}s" if seconds < 60
return "#{Math.floor(seconds/60)}m" if seconds < 3600
return "#{Math.floor(seconds/3600)}h" if seconds < 86400
return "#{Math.floor(seconds/86400)}d" if seconds < 2592000
return "#{Math.floor(seconds/2592000)}mo" if seconds < 31536000
return "#{Math.floor(seconds/31536000)}y"
| true | # Description:
# Hubot Kubernetes REST API helper commands.
#
# Dependencies:
# None
#
# Configuration:
# KUBE_HOST
# KUBE_VERSION
# KUBE_CONTEXT
# KUBE_CA
# KUBE_TOKENS
#
# Commands:
# hubot k8s [po|rc|svc] (labels) - List all k8s resources under given context
# hubot k8s context <name> - Show/change current k8s context
#
# Author:
# canthefason
module.exports = (robot) ->
getContext = (res) ->
user = res.message.user.id
key = PI:KEY:<KEY>END_PI"
return robot.brain.get(key) or defaultCtx
setContext = (res, context) ->
user = res.message.user.id
key = PI:KEY:<KEY>END_PI"
return robot.brain.set(key, context or defaultCtx)
defaultCtx = "default" or process.env.KUBE_CONTEXT
kubeapi = new Request()
aliasMap =
"svc": "services"
"rc": "replicationcontrollers"
"po": "pods"
decorateFnMap =
'replicationcontrollers': (response) ->
reply = ''
for rc in response.items
image = rc.spec.template.spec.containers[0].image
{metadata: {name, creationTimestamp}, spec: {replicas}} = rc
reply += ">*#{name}*: \n"+
">Replicas: #{replicas}\n>Age: #{timeSince(creationTimestamp)}\n"+
">Image: #{image}\n"
return reply
'services': (response) ->
reply = ''
for service in response.items
{metadata: {creationTimestamp}, spec: {clusterIP, ports}} = service
ps = ""
for p in ports
{protocol, port} = p
ps += "#{port}/#{protocol} "
reply += ">*#{service.metadata.name}*:\n" +
">Cluster ip: #{clusterIP}\n>Ports: #{ps}\n>Age: #{timeSince(creationTimestamp)}\n"
return reply
'pods': (response) ->
reply = ''
for pod in response.items
{metadata: {name}, status: {phase, startTime, containerStatuses}} = pod
reply += ">*#{name}*: \n>Status: #{phase} for: #{timeSince(startTime)} \n"
for cs in containerStatuses
{name, restartCount, image} = cs
reply += ">Name: #{name} \n>Restarts: #{restartCount}\n>Image: #{image}\n"
return reply
robot.respond /k8s\s*(services|pods|replicationcontrollers|svc|po|rc)\s*(.+)?/i, (res) ->
namespace = getContext(res)
type = res.match[1]
if alias = aliasMap[type] then type = alias
url = "namespaces/#{namespace}/#{type}"
if res.match[2] and res.match[2] != ""
url += "?labelSelector=#{res.match[2].trim()}"
roles = ["admin"]
if (robot.hasOwnProperty("auth"))
roles = robot.auth.userRoles res.envelope.user
kubeapi.get {path: url, roles}, (err, response) ->
if err
robot.logger.error err
return res.send "Could not fetch #{type} on *#{namespace}*"
return res.reply 'Requested resource is not found' unless response.items and response.items.length
reply = "\n"
decorateFn = decorateFnMap[type] or ->
reply = "Here is the list of #{type} running on *#{namespace}*\n"
reply += decorateFn response
res.reply reply
# update/fetch kubernetes context
robot.respond /k8s\s*context\s*(.+)?/i, (res) ->
context = res.match[1]
if not context or context is ""
return res.reply "Your current context is: `#{getContext(res)}`"
setContext res, context
res.reply "Your current context is changed to `#{context}`"
class Request
request = require 'request'
constructor: ->
caFile = process.env.KUBE_CA
if caFile and caFile != ""
fs = require('fs')
path = require('path')
@ca = fs.readFileSync(caFile)
@tokenMap = generateTokens()
host = process.env.KUBE_HOST or 'https://localhost'
version = process.env.KUBE_VERSION or 'v1'
@domain = host + '/api/' + version + '/'
getKubeUser: (roles) ->
# if there is only one token, then return it right away
if @tokenMap.length is 1
for role, token of @tokenMap
return role
for role in roles
if @tokenMap[role]
return role
if @tokenMap["bearer_"+role]
return "bearer_"+role
return ""
get: ({path, roles}, callback) ->
requestOptions =
url : @domain + path
if @ca
requestOptions.agentOptions =
ca: @ca
authOptions = {}
user = @getKubeUser roles
if user and user isnt ""
if user.search 'bearer_' == 0
requestOptions['auth'] =
bearer: @tokenMap[user]
else
requestOptions['auth'] =
user: user
pass: @PI:PASSWORD:<PASSWORD>END_PI[user]
request.get requestOptions, (err, response, data) ->
return callback(err) if err
if response.statusCode != 200
return callback new Error("Status code is not OK: #{response.statusCode}")
callback null, JSON.parse(data)
generateTokens = ->
tokens = {}
tokensVar = process.env.KUBE_TOKENS
if tokensVar
tokenArr = tokensVar.split(',')
for token in tokenArr
keyPair = token.split(":")
unless keyPair.length is 2
continue
tokens[keyPair[0]] = keyPair[1]
tokensVarBearer = process.env.KUBE_TOKENS_BEARER
if tokensVarBearer
tokenBearerArr = tokensVarBearer.split(',')
for token in tokenBearerArr
keyPair = token.split(":")
unless keyPair.length is 2
continue
tokens["bearer_" + keyPair[0]] = keyPair[1]
return tokens
timeSince = (date) ->
d = new Date(date).getTime()
seconds = Math.floor((new Date() - d) / 1000)
return "#{Math.floor(seconds)}s" if seconds < 60
return "#{Math.floor(seconds/60)}m" if seconds < 3600
return "#{Math.floor(seconds/3600)}h" if seconds < 86400
return "#{Math.floor(seconds/86400)}d" if seconds < 2592000
return "#{Math.floor(seconds/2592000)}mo" if seconds < 31536000
return "#{Math.floor(seconds/31536000)}y"
|
[
{
"context": "/PEM--/grunt-phonegapsplash\n#\n# Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)\n# Licensed under",
"end": 120,
"score": 0.9998791217803955,
"start": 98,
"tag": "NAME",
"value": "Pierre-Eric Marchandet"
},
{
"context": "Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)\n# Licensed under the MIT licence.\n###\n\n'use str",
"end": 151,
"score": 0.9999251365661621,
"start": 129,
"tag": "EMAIL",
"value": "pemarchandet@gmail.com"
}
] | lib/profiles.coffee | gruntjs-updater/grunt-phonegapsplash | 0 | ###
# grunt-phonegapsplash
# https://github.com/PEM--/grunt-phonegapsplash
#
# Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)
# Licensed under the MIT licence.
###
'use strict'
# Path from NodeJS app is used to merge directory and sub drectories.
path = require 'path'
###
# All profiles for every splashscreens covered by PhoneGap are stored hereafter
# with the following structure:
#
# * platform: A dictionary key representing the OS (the platform)
# * dir: The subfolder where are stored the splashscreens
# * layout: A dictionary key representing the available layouts
# * splashs: An array of the required splashscreens
# * name: The name of the splashscreen
# * width: The width of the splashscreen
# * height: The height of the splascreen
###
module.exports = (config) ->
# Android
'android':
dir: path.join 'platforms', 'android', 'res'
layout:
landscape:
splashs: [
{
name: (path.join 'drawable-land-ldpi', 'screen.png')
width: 320, height: 200
}
{
name: (path.join 'drawable-land-mdpi', 'screen.png')
width: 480, height: 320
}
{
name: (path.join 'drawable-land-hdpi', 'screen.png')
width: 800, height: 480
}
{
name: (path.join 'drawable-land-xhdpi', 'screen.png')
width: 1280, height: 720
}
]
portrait:
splashs: [
{
name: (path.join 'drawable-port-ldpi', 'screen.png')
width: 200, height: 320
}
{
name: (path.join 'drawable-port-mdpi', 'screen.png')
width: 320, height: 480
}
{
name: (path.join 'drawable-port-hdpi', 'screen.png')
width: 480, height: 800
}
{
name: (path.join 'drawable-port-xhdpi', 'screen.png')
width: 720, height: 1280
}
]
# Bada and Bada WAC
'bada':
dir: path.join 'res', 'screen', 'bada'
layout:
portrait:
splashs: [
{ name: 'screen-type5.png', width: 240, height: 400 }
{ name: 'screen-type3.png', width: 320, height: 480 }
{ name: 'screen-type4.png', width: 480, height: 800 }
{ name: 'screen-portrait.png', width: 480, height: 800 }
]
# Blackberry
'blackberry':
dir: path.join 'res', 'screen', 'blackberry'
layout:
none:
splashs: [
{ name: 'screen-225.png', width: 225, height: 225 }
]
# iOS (Retina and legacy resolutions)
'ios':
dir: path.join 'platforms', 'ios', config.prjName, 'Resources', 'splash'
layout:
landscape:
splashs: [
{ name: 'Default-Landscape~ipad.png', width: 1024, height: 768 }
{ name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 }
{ name: 'Default-Landscape-736h.png', width: 2208, height: 1242 }
]
portrait:
splashs: [
{ name: 'Default~iphone.png', width: 320, height: 480 }
{ name: 'Default@2x~iphone.png', width: 640, height: 960 }
{ name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 }
{ name: 'Default-Portrait~ipad.png', width: 768, height: 1004 }
{ name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2008 }
{ name: 'Default-667h.png', width: 750, height: 1334 }
{ name: 'Default-736h.png', width: 1242, height: 2208 }
]
# WebOS
'webos':
dir: path.join 'res', 'screen', 'webos'
layout:
none:
splashs: [
{ name: 'screen-64.png', width: 64, height: 64 }
]
# Windows Phone, Tablets and Desktop (Windows 8)
'windows-phone':
dir: path.join 'res', 'screen', 'windows-phone'
layout:
portrait:
splashs: [
{ name: 'screen-portrait.png', width: 480, height: 800 }
]
| 93879 | ###
# grunt-phonegapsplash
# https://github.com/PEM--/grunt-phonegapsplash
#
# Copyright (c) 2013 <NAME> (PEM-- <<EMAIL>>)
# Licensed under the MIT licence.
###
'use strict'
# Path from NodeJS app is used to merge directory and sub drectories.
path = require 'path'
###
# All profiles for every splashscreens covered by PhoneGap are stored hereafter
# with the following structure:
#
# * platform: A dictionary key representing the OS (the platform)
# * dir: The subfolder where are stored the splashscreens
# * layout: A dictionary key representing the available layouts
# * splashs: An array of the required splashscreens
# * name: The name of the splashscreen
# * width: The width of the splashscreen
# * height: The height of the splascreen
###
module.exports = (config) ->
# Android
'android':
dir: path.join 'platforms', 'android', 'res'
layout:
landscape:
splashs: [
{
name: (path.join 'drawable-land-ldpi', 'screen.png')
width: 320, height: 200
}
{
name: (path.join 'drawable-land-mdpi', 'screen.png')
width: 480, height: 320
}
{
name: (path.join 'drawable-land-hdpi', 'screen.png')
width: 800, height: 480
}
{
name: (path.join 'drawable-land-xhdpi', 'screen.png')
width: 1280, height: 720
}
]
portrait:
splashs: [
{
name: (path.join 'drawable-port-ldpi', 'screen.png')
width: 200, height: 320
}
{
name: (path.join 'drawable-port-mdpi', 'screen.png')
width: 320, height: 480
}
{
name: (path.join 'drawable-port-hdpi', 'screen.png')
width: 480, height: 800
}
{
name: (path.join 'drawable-port-xhdpi', 'screen.png')
width: 720, height: 1280
}
]
# Bada and Bada WAC
'bada':
dir: path.join 'res', 'screen', 'bada'
layout:
portrait:
splashs: [
{ name: 'screen-type5.png', width: 240, height: 400 }
{ name: 'screen-type3.png', width: 320, height: 480 }
{ name: 'screen-type4.png', width: 480, height: 800 }
{ name: 'screen-portrait.png', width: 480, height: 800 }
]
# Blackberry
'blackberry':
dir: path.join 'res', 'screen', 'blackberry'
layout:
none:
splashs: [
{ name: 'screen-225.png', width: 225, height: 225 }
]
# iOS (Retina and legacy resolutions)
'ios':
dir: path.join 'platforms', 'ios', config.prjName, 'Resources', 'splash'
layout:
landscape:
splashs: [
{ name: 'Default-Landscape~ipad.png', width: 1024, height: 768 }
{ name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 }
{ name: 'Default-Landscape-736h.png', width: 2208, height: 1242 }
]
portrait:
splashs: [
{ name: 'Default~iphone.png', width: 320, height: 480 }
{ name: 'Default@2x~iphone.png', width: 640, height: 960 }
{ name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 }
{ name: 'Default-Portrait~ipad.png', width: 768, height: 1004 }
{ name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2008 }
{ name: 'Default-667h.png', width: 750, height: 1334 }
{ name: 'Default-736h.png', width: 1242, height: 2208 }
]
# WebOS
'webos':
dir: path.join 'res', 'screen', 'webos'
layout:
none:
splashs: [
{ name: 'screen-64.png', width: 64, height: 64 }
]
# Windows Phone, Tablets and Desktop (Windows 8)
'windows-phone':
dir: path.join 'res', 'screen', 'windows-phone'
layout:
portrait:
splashs: [
{ name: 'screen-portrait.png', width: 480, height: 800 }
]
| true | ###
# grunt-phonegapsplash
# https://github.com/PEM--/grunt-phonegapsplash
#
# Copyright (c) 2013 PI:NAME:<NAME>END_PI (PEM-- <PI:EMAIL:<EMAIL>END_PI>)
# Licensed under the MIT licence.
###
'use strict'
# Path from NodeJS app is used to merge directory and sub drectories.
path = require 'path'
###
# All profiles for every splashscreens covered by PhoneGap are stored hereafter
# with the following structure:
#
# * platform: A dictionary key representing the OS (the platform)
# * dir: The subfolder where are stored the splashscreens
# * layout: A dictionary key representing the available layouts
# * splashs: An array of the required splashscreens
# * name: The name of the splashscreen
# * width: The width of the splashscreen
# * height: The height of the splascreen
###
module.exports = (config) ->
# Android
'android':
dir: path.join 'platforms', 'android', 'res'
layout:
landscape:
splashs: [
{
name: (path.join 'drawable-land-ldpi', 'screen.png')
width: 320, height: 200
}
{
name: (path.join 'drawable-land-mdpi', 'screen.png')
width: 480, height: 320
}
{
name: (path.join 'drawable-land-hdpi', 'screen.png')
width: 800, height: 480
}
{
name: (path.join 'drawable-land-xhdpi', 'screen.png')
width: 1280, height: 720
}
]
portrait:
splashs: [
{
name: (path.join 'drawable-port-ldpi', 'screen.png')
width: 200, height: 320
}
{
name: (path.join 'drawable-port-mdpi', 'screen.png')
width: 320, height: 480
}
{
name: (path.join 'drawable-port-hdpi', 'screen.png')
width: 480, height: 800
}
{
name: (path.join 'drawable-port-xhdpi', 'screen.png')
width: 720, height: 1280
}
]
# Bada and Bada WAC
'bada':
dir: path.join 'res', 'screen', 'bada'
layout:
portrait:
splashs: [
{ name: 'screen-type5.png', width: 240, height: 400 }
{ name: 'screen-type3.png', width: 320, height: 480 }
{ name: 'screen-type4.png', width: 480, height: 800 }
{ name: 'screen-portrait.png', width: 480, height: 800 }
]
# Blackberry
'blackberry':
dir: path.join 'res', 'screen', 'blackberry'
layout:
none:
splashs: [
{ name: 'screen-225.png', width: 225, height: 225 }
]
# iOS (Retina and legacy resolutions)
'ios':
dir: path.join 'platforms', 'ios', config.prjName, 'Resources', 'splash'
layout:
landscape:
splashs: [
{ name: 'Default-Landscape~ipad.png', width: 1024, height: 768 }
{ name: 'Default-Landscape@2x~ipad.png', width: 2048, height: 1536 }
{ name: 'Default-Landscape-736h.png', width: 2208, height: 1242 }
]
portrait:
splashs: [
{ name: 'Default~iphone.png', width: 320, height: 480 }
{ name: 'Default@2x~iphone.png', width: 640, height: 960 }
{ name: 'Default-568h@2x~iphone.png', width: 640, height: 1136 }
{ name: 'Default-Portrait~ipad.png', width: 768, height: 1004 }
{ name: 'Default-Portrait@2x~ipad.png', width: 1536, height: 2008 }
{ name: 'Default-667h.png', width: 750, height: 1334 }
{ name: 'Default-736h.png', width: 1242, height: 2208 }
]
# WebOS
'webos':
dir: path.join 'res', 'screen', 'webos'
layout:
none:
splashs: [
{ name: 'screen-64.png', width: 64, height: 64 }
]
# Windows Phone, Tablets and Desktop (Windows 8)
'windows-phone':
dir: path.join 'res', 'screen', 'windows-phone'
layout:
portrait:
splashs: [
{ name: 'screen-portrait.png', width: 480, height: 800 }
]
|
[
{
"context": "ring it inplace.\n#\n# {% capture heading %}\n# Monkeys!\n# {% endcapture %}\n# ...\n# <h1>{{ head",
"end": 155,
"score": 0.7638830542564392,
"start": 152,
"tag": "NAME",
"value": "Mon"
}
] | src/liquid/tags/capture.coffee | innerfunction/liquid-node | 1 | Liquid = require "../../liquid"
# Capture stores the result of a block into a variable without rendering it inplace.
#
# {% capture heading %}
# Monkeys!
# {% endcapture %}
# ...
# <h1>{{ heading }}</h1>
#
# Capture is useful for saving content for use later in your template, such as
# in a sidebar or footer.
#
module.exports = class Capture extends Liquid.Block
Syntax = /(\w+)/
SyntaxHelp = "Syntax Error in 'capture' - Valid syntax: capture [var]"
constructor: (template, tagName, markup) ->
match = Syntax.exec(markup)
if match
@to = match[1]
else
throw new Liquid.SyntaxError(SyntaxHelp)
super
render: (context) ->
super.then (chunks) =>
output = Liquid.Helpers.toFlatString chunks
context.lastScope()[@to] = output
""
| 145408 | Liquid = require "../../liquid"
# Capture stores the result of a block into a variable without rendering it inplace.
#
# {% capture heading %}
# <NAME>keys!
# {% endcapture %}
# ...
# <h1>{{ heading }}</h1>
#
# Capture is useful for saving content for use later in your template, such as
# in a sidebar or footer.
#
module.exports = class Capture extends Liquid.Block
Syntax = /(\w+)/
SyntaxHelp = "Syntax Error in 'capture' - Valid syntax: capture [var]"
constructor: (template, tagName, markup) ->
match = Syntax.exec(markup)
if match
@to = match[1]
else
throw new Liquid.SyntaxError(SyntaxHelp)
super
render: (context) ->
super.then (chunks) =>
output = Liquid.Helpers.toFlatString chunks
context.lastScope()[@to] = output
""
| true | Liquid = require "../../liquid"
# Capture stores the result of a block into a variable without rendering it inplace.
#
# {% capture heading %}
# PI:NAME:<NAME>END_PIkeys!
# {% endcapture %}
# ...
# <h1>{{ heading }}</h1>
#
# Capture is useful for saving content for use later in your template, such as
# in a sidebar or footer.
#
module.exports = class Capture extends Liquid.Block
Syntax = /(\w+)/
SyntaxHelp = "Syntax Error in 'capture' - Valid syntax: capture [var]"
constructor: (template, tagName, markup) ->
match = Syntax.exec(markup)
if match
@to = match[1]
else
throw new Liquid.SyntaxError(SyntaxHelp)
super
render: (context) ->
super.then (chunks) =>
output = Liquid.Helpers.toFlatString chunks
context.lastScope()[@to] = output
""
|
[
{
"context": "process.env.DEPLOY_STATE_USERNAME\n password : process.env.DEPLOY_STATE_PASSWORD\n }\n\n panic: (error) =>\n console.error erro",
"end": 348,
"score": 0.8664510846138,
"start": 315,
"tag": "PASSWORD",
"value": "process.env.DEPLOY_STATE_PASSWORD"
}
] | command.coffee | octoblu/deploy-state-service | 1 | _ = require 'lodash'
mongojs = require 'mongojs'
Server = require './src/server'
class Command
constructor: ->
@mongoDbUri = process.env.MONGODB_URI
@serverOptions = {
port : process.env.PORT || 80
username : process.env.DEPLOY_STATE_USERNAME
password : process.env.DEPLOY_STATE_PASSWORD
}
panic: (error) =>
console.error error.stack
process.exit 1
run: =>
@panic new Error('Missing required environment variable: MONGODB_URI') unless @mongoDbUri?
@panic new Error('Missing required environment variable: DEPLOY_STATE_USERNAME') unless @serverOptions.username?
@panic new Error('Missing required environment variable: DEPLOY_STATE_PASSWORD') unless @serverOptions.password?
@panic new Error('Missing port') unless @serverOptions.port?
database = mongojs @mongoDbUri, ['deployments', 'webhooks']
@serverOptions.database = database
server = new Server @serverOptions
server.run (error) =>
return @panic error if error?
{address,port} = server.address()
console.log "DeployStateService listening on port: #{port}"
process.on 'SIGTERM', =>
console.log 'SIGTERM caught, exiting'
database?.close()
process.exit 0 unless server?.stop?
server.stop =>
process.exit 0
command = new Command()
command.run()
| 74415 | _ = require 'lodash'
mongojs = require 'mongojs'
Server = require './src/server'
class Command
constructor: ->
@mongoDbUri = process.env.MONGODB_URI
@serverOptions = {
port : process.env.PORT || 80
username : process.env.DEPLOY_STATE_USERNAME
password : <PASSWORD>
}
panic: (error) =>
console.error error.stack
process.exit 1
run: =>
@panic new Error('Missing required environment variable: MONGODB_URI') unless @mongoDbUri?
@panic new Error('Missing required environment variable: DEPLOY_STATE_USERNAME') unless @serverOptions.username?
@panic new Error('Missing required environment variable: DEPLOY_STATE_PASSWORD') unless @serverOptions.password?
@panic new Error('Missing port') unless @serverOptions.port?
database = mongojs @mongoDbUri, ['deployments', 'webhooks']
@serverOptions.database = database
server = new Server @serverOptions
server.run (error) =>
return @panic error if error?
{address,port} = server.address()
console.log "DeployStateService listening on port: #{port}"
process.on 'SIGTERM', =>
console.log 'SIGTERM caught, exiting'
database?.close()
process.exit 0 unless server?.stop?
server.stop =>
process.exit 0
command = new Command()
command.run()
| true | _ = require 'lodash'
mongojs = require 'mongojs'
Server = require './src/server'
class Command
constructor: ->
@mongoDbUri = process.env.MONGODB_URI
@serverOptions = {
port : process.env.PORT || 80
username : process.env.DEPLOY_STATE_USERNAME
password : PI:PASSWORD:<PASSWORD>END_PI
}
panic: (error) =>
console.error error.stack
process.exit 1
run: =>
@panic new Error('Missing required environment variable: MONGODB_URI') unless @mongoDbUri?
@panic new Error('Missing required environment variable: DEPLOY_STATE_USERNAME') unless @serverOptions.username?
@panic new Error('Missing required environment variable: DEPLOY_STATE_PASSWORD') unless @serverOptions.password?
@panic new Error('Missing port') unless @serverOptions.port?
database = mongojs @mongoDbUri, ['deployments', 'webhooks']
@serverOptions.database = database
server = new Server @serverOptions
server.run (error) =>
return @panic error if error?
{address,port} = server.address()
console.log "DeployStateService listening on port: #{port}"
process.on 'SIGTERM', =>
console.log 'SIGTERM caught, exiting'
database?.close()
process.exit 0 unless server?.stop?
server.stop =>
process.exit 0
command = new Command()
command.run()
|
[
{
"context": "'\n exportObj.renameShip 'Scurrg H-6 Bomber', 'Bombardero Scurrg H-6'\n exportObj.renameShip 'M12-L Kimogila Fig",
"end": 13067,
"score": 0.663848340511322,
"start": 13051,
"tag": "NAME",
"value": "ombardero Scurrg"
},
{
"context": "nimo de 0).\"\"\"\n ship: \"Ala-X\"\n \"Garven Dreis\":\n text: \"\"\"Después de gastar una fich",
"end": 13347,
"score": 0.9179073572158813,
"start": 13335,
"tag": "NAME",
"value": "Garven Dreis"
},
{
"context": "scuadrón Rojo\"\n ship: \"Ala-X\"\n \"Rookie Pilot\":\n name: \"Piloto Novato\"\n ",
"end": 13665,
"score": 0.7085398435592651,
"start": 13659,
"tag": "NAME",
"value": "Rookie"
},
{
"context": "Ala-X\"\n \"Rookie Pilot\":\n name: \"Piloto Novato\"\n ship: \"Ala-X\"\n \"Biggs Darklig",
"end": 13706,
"score": 0.9964075088500977,
"start": 13693,
"tag": "NAME",
"value": "Piloto Novato"
},
{
"context": "o objetivo.\"\"\"\n ship: \"Ala-X\"\n \"Luke Skywalker\":\n text: \"\"\"Cuando te defiendas ",
"end": 14001,
"score": 0.7612300515174866,
"start": 13993,
"tag": "NAME",
"value": "Luke Sky"
},
{
"context": "diatamente.\"\"\"\n ship: \"Ala-Y\"\n \"Horton Salm\":\n text: \"\"\"Cuando ataques a alcance 2",
"end": 14494,
"score": 0.9989779591560364,
"start": 14483,
"tag": "NAME",
"value": "Horton Salm"
},
{
"context": "rón Negro\"\n ship: \"Caza TIE\"\n '\"Winged Gundark\"':\n name: '\"Gundark Alado\"'\n ",
"end": 15101,
"score": 0.9732192158699036,
"start": 15087,
"tag": "NAME",
"value": "Winged Gundark"
},
{
"context": "\"\n '\"Winged Gundark\"':\n name: '\"Gundark Alado\"'\n text: \"\"\"Cuando ataques a alcance 1",
"end": 15138,
"score": 0.9995428323745728,
"start": 15125,
"tag": "NAME",
"value": "Gundark Alado"
},
{
"context": "TIE\"\n '\"Night Beast\"':\n name: '\"Bestia Nocturna\"'\n text: \"\"\"Después de que ejecutes un",
"end": 15347,
"score": 0.9969861507415771,
"start": 15332,
"tag": "NAME",
"value": "Bestia Nocturna"
},
{
"context": "TIE\"\n '\"Backstabber\"':\n name: '\"Asesino Furtivo\"'\n text: \"\"\"Cuando ataques desde fuera",
"end": 15560,
"score": 0.9973493218421936,
"start": 15545,
"tag": "NAME",
"value": "Asesino Furtivo"
},
{
"context": "al.\"\"\"\n ship: \"Caza TIE\"\n '\"Dark Curse\"':\n name: '\"Maldición Oscura\"'\n ",
"end": 15726,
"score": 0.7755587697029114,
"start": 15723,
"tag": "NAME",
"value": "Cur"
},
{
"context": " TIE\"\n '\"Dark Curse\"':\n name: '\"Maldición Oscura\"'\n text: \"\"\"Cuando te defiendas en com",
"end": 15768,
"score": 0.9992995858192444,
"start": 15752,
"tag": "NAME",
"value": "Maldición Oscura"
},
{
"context": "ataque.\"\"\"\n ship: \"Caza TIE\"\n '\"Mauler Mithel\"':\n name: '\"Mutilador Mithel\"'\n ",
"end": 15980,
"score": 0.9997750520706177,
"start": 15967,
"tag": "NAME",
"value": "Mauler Mithel"
},
{
"context": "E\"\n '\"Mauler Mithel\"':\n name: '\"Mutilador Mithel\"'\n text: \"\"\"Si atacas a alcance 1, tir",
"end": 16020,
"score": 0.9998682737350464,
"start": 16004,
"tag": "NAME",
"value": "Mutilador Mithel"
},
{
"context": "cional.\"\"\"\n ship: \"Caza TIE\"\n '\"Howlrunner\"':\n name: '\"Aullador Veloz\"'\n ",
"end": 16152,
"score": 0.7900125980377197,
"start": 16142,
"tag": "NAME",
"value": "Howlrunner"
},
{
"context": " TIE\"\n '\"Howlrunner\"':\n name: '\"Aullador Veloz\"'\n text: \"\"\"Cuando otra nave aliada qu",
"end": 16190,
"score": 0.9998171925544739,
"start": 16176,
"tag": "NAME",
"value": "Aullador Veloz"
},
{
"context": "rmenta\"\n ship: \"TIE Avanzado\"\n \"Maarek Stele\":\n text: \"\"\"Cuando tu ataque inflija u",
"end": 16621,
"score": 0.9991941452026367,
"start": 16609,
"tag": "NAME",
"value": "Maarek Stele"
},
{
"context": "ras.\"\"\"\n ship: \"TIE Avanzado\"\n \"Darth Vader\":\n text: \"\"\"Puedes llevar a cabo dos a",
"end": 16865,
"score": 0.9957716464996338,
"start": 16854,
"tag": "NAME",
"value": "Darth Vader"
},
{
"context": "E\"\n \"\\\"Fel's Wrath\\\"\":\n name: '\"Ira de Fel\"'\n ship: \"Interceptor TIE\"\n ",
"end": 17392,
"score": 0.9993476867675781,
"start": 17382,
"tag": "NAME",
"value": "Ira de Fel"
},
{
"context": "hasta el final de la fase de Combate.\"\"\"\n \"Turr Phennir\":\n ship: \"Interceptor TIE\"\n ",
"end": 17600,
"score": 0.9982143640518188,
"start": 17588,
"tag": "NAME",
"value": "Turr Phennir"
},
{
"context": "n gratuita de impulso o tonel volado.\"\"\"\n \"Soontir Fel\":\n ship: \"Interceptor TIE\"\n ",
"end": 17786,
"score": 0.9903074502944946,
"start": 17775,
"tag": "NAME",
"value": "Soontir Fel"
},
{
"context": "r 1 ficha de Concentración a tu nave.\"\"\"\n \"Tycho Celchu\":\n text: \"\"\"Puedes realizar acciones i",
"end": 17958,
"score": 0.9961342215538025,
"start": 17946,
"tag": "NAME",
"value": "Tycho Celchu"
},
{
"context": ": \"Contrabandista del Borde Exterior\"\n \"Chewbacca\":\n text: \"\"\"Cuando recibas una carta d",
"end": 18571,
"score": 0.8140313029289246,
"start": 18565,
"tag": "NAME",
"value": "wbacca"
},
{
"context": "ente sin resolver su texto de reglas.\"\"\"\n \"Lando Calrissian\":\n text: \"\"\"Después de que ejecutes un",
"end": 18734,
"score": 0.9998324513435364,
"start": 18718,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "as indicadas en su barra de acciones.\"\"\"\n \"Han Solo\":\n text: \"\"\"Cuando ataques, puedes vol",
"end": 18955,
"score": 0.9840947985649109,
"start": 18947,
"tag": "NAME",
"value": "Han Solo"
},
{
"context": "r a tirar tantos como te sea posible.\"\"\"\n \"Bounty Hunter\":\n name: \"Cazarrecompensas\"\n \"K",
"end": 19128,
"score": 0.9997352361679077,
"start": 19115,
"tag": "NAME",
"value": "Bounty Hunter"
},
{
"context": "e.\"\"\"\n \"Bounty Hunter\":\n name: \"Cazarrecompensas\"\n \"Kath Scarlet\":\n text: \"\"\"Cua",
"end": 19166,
"score": 0.9996488690376282,
"start": 19150,
"tag": "NAME",
"value": "Cazarrecompensas"
},
{
"context": "r\":\n name: \"Cazarrecompensas\"\n \"Kath Scarlet\":\n text: \"\"\"Cuando ataques, el defenso",
"end": 19189,
"score": 0.9996560215950012,
"start": 19177,
"tag": "NAME",
"value": "Kath Scarlet"
},
{
"context": "si anula al menos 1 resultado %CRIT%.\"\"\"\n \"Boba Fett\":\n text: \"\"\"Cuando realices una maniob",
"end": 19326,
"score": 0.9998282194137573,
"start": 19317,
"tag": "NAME",
"value": "Boba Fett"
},
{
"context": "de inclinación de la misma velocidad.\"\"\"\n \"Krassis Trelix\":\n text: \"\"\"Cuando ataques con un arma",
"end": 19554,
"score": 0.9991008043289185,
"start": 19540,
"tag": "NAME",
"value": "Krassis Trelix"
},
{
"context": "-B\"\n \"Rebel Operative\":\n name: \"Agente Rebelde\"\n ship: \"HWK-290\"\n \"Roark Garne",
"end": 20268,
"score": 0.999642014503479,
"start": 20254,
"tag": "NAME",
"value": "Agente Rebelde"
},
{
"context": "nte Rebelde\"\n ship: \"HWK-290\"\n \"Roark Garnet\":\n text: \"\"\"Al comienzo de la fase de ",
"end": 20319,
"score": 0.9998977184295654,
"start": 20307,
"tag": "NAME",
"value": "Roark Garnet"
},
{
"context": "lidad 12.\"\"\"\n ship: \"HWK-290\"\n \"Kyle Katarn\":\n text: \"\"\"Al comienzo de la fase de ",
"end": 20564,
"score": 0.9998935461044312,
"start": 20553,
"tag": "NAME",
"value": "Kyle Katarn"
},
{
"context": "ance 1-3.\"\"\"\n ship: \"HWK-290\"\n \"Jan Ors\":\n text: \"\"\"Cuando otra nave aliada qu",
"end": 20763,
"score": 0.9997461438179016,
"start": 20756,
"tag": "NAME",
"value": "Jan Ors"
},
{
"context": " \"Gamma Squadron Veteran\":\n name: \"Veterano del escuadrón Gamma\"\n ship: \"Bombardero TI",
"end": 21302,
"score": 0.8283863663673401,
"start": 21290,
"tag": "NAME",
"value": "Veterano del"
},
{
"context": "eteran\":\n name: \"Veterano del escuadrón Gamma\"\n ship: \"Bombardero TIE\"\n \"Capt",
"end": 21318,
"score": 0.9875603318214417,
"start": 21313,
"tag": "NAME",
"value": "Gamma"
},
{
"context": "amma\"\n ship: \"Bombardero TIE\"\n \"Captain Jonus\":\n name: \"Capitán Jonus\"\n s",
"end": 21377,
"score": 0.9974627494812012,
"start": 21364,
"tag": "NAME",
"value": "Captain Jonus"
},
{
"context": " TIE\"\n \"Captain Jonus\":\n name: \"Capitán Jonus\"\n ship: \"Bombardero TIE\"\n t",
"end": 21412,
"score": 0.9998437762260437,
"start": 21399,
"tag": "NAME",
"value": "Capitán Jonus"
},
{
"context": "tirar un máximo de 2 dados de ataque.\"\"\"\n \"Major Rhymer\":\n name: \"Comandante Rhymer\"\n ",
"end": 21641,
"score": 0.9882380366325378,
"start": 21629,
"tag": "NAME",
"value": "Major Rhymer"
},
{
"context": "ue.\"\"\"\n \"Major Rhymer\":\n name: \"Comandante Rhymer\"\n ship: \"Bombardero TIE\"\n t",
"end": 21680,
"score": 0.9989879131317139,
"start": 21663,
"tag": "NAME",
"value": "Comandante Rhymer"
},
{
"context": " \"Omicron Group Pilot\":\n name: \"Piloto del grupo Ómicron\"\n ship: \"Lanzadera",
"end": 21957,
"score": 0.6638087034225464,
"start": 21955,
"tag": "NAME",
"value": "lo"
},
{
"context": "roup Pilot\":\n name: \"Piloto del grupo Ómicron\"\n ship: \"Lanzadera clase Lambda\"\n ",
"end": 21977,
"score": 0.8291358947753906,
"start": 21971,
"tag": "NAME",
"value": "micron"
},
{
"context": " ship: \"Lanzadera clase Lambda\"\n \"Captain Kagi\":\n name: \"Capitán Kagi\"\n te",
"end": 22043,
"score": 0.9985358715057373,
"start": 22031,
"tag": "NAME",
"value": "Captain Kagi"
},
{
"context": "ambda\"\n \"Captain Kagi\":\n name: \"Capitán Kagi\"\n text: \"\"\"Cuando una nave enemiga fij",
"end": 22077,
"score": 0.9998819231987,
"start": 22065,
"tag": "NAME",
"value": "Capitán Kagi"
},
{
"context": " ship: \"Lanzadera clase Lambda\"\n \"Colonel Jendon\":\n name: \"Coronel Jendon\"\n ",
"end": 22259,
"score": 0.9991390109062195,
"start": 22245,
"tag": "NAME",
"value": "Colonel Jendon"
},
{
"context": "bda\"\n \"Colonel Jendon\":\n name: \"Coronel Jendon\"\n text: \"\"\"Al comienzo de la fase de C",
"end": 22295,
"score": 0.9998418688774109,
"start": 22281,
"tag": "NAME",
"value": "Coronel Jendon"
},
{
"context": " ship: \"Lanzadera clase Lambda\"\n \"Captain Yorr\":\n name: \"Capitán Yorr\"\n te",
"end": 22564,
"score": 0.9949307441711426,
"start": 22552,
"tag": "NAME",
"value": "Captain Yorr"
},
{
"context": "ambda\"\n \"Captain Yorr\":\n name: \"Capitán Yorr\"\n text: \"\"\"Cuando otra nave aliada que",
"end": 22598,
"score": 0.9998642802238464,
"start": 22586,
"tag": "NAME",
"value": "Capitán Yorr"
},
{
"context": " ship: \"Lanzadera clase Lambda\"\n \"Lieutenant Lorrir\":\n ship: \"Interceptor TIE\"\n ",
"end": 22850,
"score": 0.9447944760322571,
"start": 22833,
"tag": "NAME",
"value": "Lieutenant Lorrir"
},
{
"context": "\"\n \"Royal Guard Pilot\":\n name: \"Piloto de la Guardia Real\"\n ship: \"Interceptor T",
"end": 23156,
"score": 0.8790132403373718,
"start": 23147,
"tag": "NAME",
"value": "Piloto de"
},
{
"context": "uard Pilot\":\n name: \"Piloto de la Guardia Real\"\n ship: \"Interceptor TIE\"\n \"Tet",
"end": 23172,
"score": 0.6459673047065735,
"start": 23165,
"tag": "NAME",
"value": "ia Real"
},
{
"context": "eal\"\n ship: \"Interceptor TIE\"\n \"Tetran Cowall\":\n ship: \"Interceptor TIE\"\n ",
"end": 23232,
"score": 0.9994271993637085,
"start": 23219,
"tag": "NAME",
"value": "Tetran Cowall"
},
{
"context": "mo si su velocidad fuese de 1, 3 ó 5.\"\"\"\n \"Kir Kanos\":\n ship: \"Interceptor TIE\"\n ",
"end": 23408,
"score": 0.9995868802070618,
"start": 23399,
"tag": "NAME",
"value": "Kir Kanos"
},
{
"context": "añadir 1 resultado %HIT% a tu tirada.\"\"\"\n \"Carnor Jax\":\n ship: \"Interceptor TIE\"\n ",
"end": 23600,
"score": 0.998572826385498,
"start": 23590,
"tag": "NAME",
"value": "Carnor Jax"
},
{
"context": " Pilot\":\n name: \"Piloto del escuadrón Bandido\"\n ship: \"Z-95 Cazacabezas\"\n \"T",
"end": 24027,
"score": 0.5383711457252502,
"start": 24022,
"tag": "NAME",
"value": "andid"
},
{
"context": "la\"\n ship: \"Z-95 Cazacabezas\"\n \"Lieutenant Blount\":\n name: \"Teniente Blount\"\n ",
"end": 24207,
"score": 0.9960388541221619,
"start": 24190,
"tag": "NAME",
"value": "Lieutenant Blount"
},
{
"context": "\"\n \"Lieutenant Blount\":\n name: \"Teniente Blount\"\n text: \"\"\"Cuando ataques, el defensor",
"end": 24244,
"score": 0.9994805455207825,
"start": 24229,
"tag": "NAME",
"value": "Teniente Blount"
},
{
"context": "\"\"\"\n ship: \"Z-95 Cazacabezas\"\n \"Airen Cracken\":\n name: \"Airen Cracken\"\n t",
"end": 24422,
"score": 0.9875316619873047,
"start": 24409,
"tag": "NAME",
"value": "Airen Cracken"
},
{
"context": "ezas\"\n \"Airen Cracken\":\n name: \"Airen Cracken\"\n text: \"\"\"Después de que realices un ",
"end": 24457,
"score": 0.9990574717521667,
"start": 24444,
"tag": "NAME",
"value": "Airen Cracken"
},
{
"context": " Ónice\"\n ship: \"Defensor TIE\"\n \"Colonel Vessery\":\n name: \"Coronel Vessery\"\n ",
"end": 24894,
"score": 0.9987550973892212,
"start": 24879,
"tag": "NAME",
"value": "Colonel Vessery"
},
{
"context": "IE\"\n \"Colonel Vessery\":\n name: \"Coronel Vessery\"\n text: \"\"\"Cuando ataques, inmediatame",
"end": 24931,
"score": 0.9996698498725891,
"start": 24916,
"tag": "NAME",
"value": "Coronel Vessery"
},
{
"context": "ado.\"\"\"\n ship: \"Defensor TIE\"\n \"Rexler Brath\":\n text: \"\"\"Después de que efectúes un",
"end": 25170,
"score": 0.9993674159049988,
"start": 25158,
"tag": "NAME",
"value": "Rexler Brath"
},
{
"context": " Pilot\":\n name: \"Piloto del escuadrón Luna Negra\"\n ship: \"Ala-E\"\n \"Etahn A'baht\"",
"end": 25583,
"score": 0.7157090306282043,
"start": 25574,
"tag": "NAME",
"value": "una Negra"
},
{
"context": "ón Luna Negra\"\n ship: \"Ala-E\"\n \"Etahn A'baht\":\n text: \"\"\"Cuando una nave neemiga si",
"end": 25632,
"score": 0.9969968199729919,
"start": 25620,
"tag": "NAME",
"value": "Etahn A'baht"
},
{
"context": "ado %CRIT%.\"\"\"\n ship: \"Ala-E\"\n \"Corran Horn\":\n text: \"\"\"Puedes efectuar 1 ataque a",
"end": 25867,
"score": 0.9995847940444946,
"start": 25856,
"tag": "NAME",
"value": "Corran Horn"
},
{
"context": "on Pilot\":\n name: \"Piloto del escuadrón Sigma\"\n ship: \"TIE Fantasma\"\n \"Shadow",
"end": 26109,
"score": 0.6785013675689697,
"start": 26104,
"tag": "NAME",
"value": "Sigma"
},
{
"context": "E Fantasma\"\n '\"Echo\"':\n name: '\"Eco\"'\n text: \"\"\"Cuando desactives tu camuf",
"end": 26299,
"score": 0.8294800519943237,
"start": 26296,
"tag": "NAME",
"value": "Eco"
},
{
"context": "2).\"\"\"\n ship: \"TIE Fantasma\"\n '\"Whisper\"':\n name: '\"Susurro\"'\n text",
"end": 26524,
"score": 0.6843775510787964,
"start": 26517,
"tag": "NAME",
"value": "Whisper"
},
{
"context": "antasma\"\n '\"Whisper\"':\n name: '\"Susurro\"'\n text: \"\"\"Después de que efectúes un",
"end": 26555,
"score": 0.9422035217285156,
"start": 26548,
"tag": "NAME",
"value": "Susurro"
},
{
"context": " \"CR90 Corvette (Fore)\":\n name: \"Corbeta CR90 (Proa)\"\n ship: \"Corbeta CR90 ",
"end": 26769,
"score": 0.6780776381492615,
"start": 26766,
"tag": "NAME",
"value": "Cor"
},
{
"context": " \"CR90 Corvette (Aft)\":\n name: \"Corbeta CR90 (Popa)\"\n ship: \"Corbeta CR90 (Pop",
"end": 27017,
"score": 0.7427607774734497,
"start": 27010,
"tag": "NAME",
"value": "Corbeta"
},
{
"context": "\n ship: \"Corbeta CR90 (Popa)\"\n \"Wes Janson\":\n text: \"\"\"Después de que efectúes un",
"end": 27090,
"score": 0.999346137046814,
"start": 27080,
"tag": "NAME",
"value": "Wes Janson"
},
{
"context": "l defensor.\"\"\"\n ship: \"Ala-X\"\n \"Jek Porkins\":\n text: \"\"\"Cuando recibas una ficha d",
"end": 27285,
"score": 0.9995697140693665,
"start": 27274,
"tag": "NAME",
"value": "Jek Porkins"
},
{
"context": "oca abajo.\"\"\"\n ship: \"Ala-X\"\n '\"Hobbie\" Klivian':\n text: \"\"\"Cuando fijes un b",
"end": 27497,
"score": 0.9830662608146667,
"start": 27491,
"tag": "NAME",
"value": "Hobbie"
},
{
"context": "jo.\"\"\"\n ship: \"Ala-X\"\n '\"Hobbie\" Klivian':\n text: \"\"\"Cuando fijes un blanco o g",
"end": 27506,
"score": 0.9997009634971619,
"start": 27499,
"tag": "NAME",
"value": "Klivian"
},
{
"context": "de tu nave.\"\"\"\n ship: \"Ala-X\"\n \"Tarn Mison\":\n text: \"\"\"Cuando una nave enemiga te",
"end": 27683,
"score": 0.9999033212661743,
"start": 27673,
"tag": "NAME",
"value": "Tarn Mison"
},
{
"context": "omo blanco.\"\"\"\n ship: \"Ala-X\"\n \"Jake Farrell\":\n text: \"\"\"Después de que realices un",
"end": 27855,
"score": 0.9999035000801086,
"start": 27843,
"tag": "NAME",
"value": "Jake Farrell"
},
{
"context": "nel volado.\"\"\"\n ship: \"Ala-A\"\n \"Gemmer Sojan\":\n text: \"\"\"Mientras te encuentres a a",
"end": 28085,
"score": 0.9999039173126221,
"start": 28073,
"tag": "NAME",
"value": "Gemmer Sojan"
},
{
"context": "menta en 1.\"\"\"\n ship: \"Ala-A\"\n \"Keyan Farlander\":\n text: \"\"\"Cuando ataques, puedes qui",
"end": 28251,
"score": 0.999902069568634,
"start": 28236,
"tag": "NAME",
"value": "Keyan Farlander"
},
{
"context": " por %HIT%.\"\"\"\n ship: \"Ala-B\"\n \"Nera Dantels\":\n text: \"\"\"Puedes efectuar ataques co",
"end": 28430,
"score": 0.9998968839645386,
"start": 28418,
"tag": "NAME",
"value": "Nera Dantels"
},
{
"context": "las a tu elección y descarta la otra.\"\"\"\n \"Eaden Vrill\":\n text: \"\"\"Si efectúas un ataque con ",
"end": 29417,
"score": 0.9961276054382324,
"start": 29406,
"tag": "NAME",
"value": "Eaden Vrill"
},
{
"context": "l.\"\"\"\n \"Patrol Leader\":\n name: \"Jefe de Patrulla\"\n ship: \"VT-49 Diezmador\"\n \"Rea",
"end": 29632,
"score": 0.9998888969421387,
"start": 29616,
"tag": "NAME",
"value": "Jefe de Patrulla"
},
{
"context": "lla\"\n ship: \"VT-49 Diezmador\"\n \"Rear Admiral Chiraneau\":\n name: \"Contralmirante Chiraneau\"\n ",
"end": 29701,
"score": 0.9990111589431763,
"start": 29679,
"tag": "NAME",
"value": "Rear Admiral Chiraneau"
},
{
"context": " \"Rear Admiral Chiraneau\":\n name: \"Contralmirante Chiraneau\"\n text: \"\"\"Cuando atacas a alcance 1-2",
"end": 29747,
"score": 0.9998519420623779,
"start": 29723,
"tag": "NAME",
"value": "Contralmirante Chiraneau"
},
{
"context": ".\"\"\"\n ship: \"VT-49 Diezmador\"\n \"Commander Kenkirk\":\n ship: \"VT-49 Diezmador\"\n ",
"end": 29935,
"score": 0.9998303651809692,
"start": 29918,
"tag": "NAME",
"value": "Commander Kenkirk"
},
{
"context": " ship: \"VT-49 Diezmador\"\n name: \"Comandante Kenkirk\"\n text: \"\"\"Si no te quedan escudos y t",
"end": 30011,
"score": 0.9998686909675598,
"start": 29993,
"tag": "NAME",
"value": "Comandante Kenkirk"
},
{
"context": "ta de Daño, tu Agilidad aumenta en 1.\"\"\"\n \"Captain Oicunn\":\n name: \"Capitán Oicunn\"\n ",
"end": 30154,
"score": 0.9998464584350586,
"start": 30140,
"tag": "NAME",
"value": "Captain Oicunn"
},
{
"context": ".\"\"\"\n \"Captain Oicunn\":\n name: \"Capitán Oicunn\"\n text: \"\"\"Después de ejecutar un mani",
"end": 30190,
"score": 0.9998918175697327,
"start": 30176,
"tag": "NAME",
"value": "Capitán Oicunn"
},
{
"context": "egro\"\n ship: \"Víbora Estelar\"\n \"Prince Xizor\":\n name: \"Príncipe Xizor\"\n ",
"end": 30575,
"score": 0.9994437098503113,
"start": 30563,
"tag": "NAME",
"value": "Prince Xizor"
},
{
"context": "telar\"\n \"Prince Xizor\":\n name: \"Príncipe Xizor\"\n text: \"\"\"Cuando te defiendas, una na",
"end": 30611,
"score": 0.9998736381530762,
"start": 30597,
"tag": "NAME",
"value": "Príncipe Xizor"
},
{
"context": "o.\"\"\"\n ship: \"Víbora Estelar\"\n \"Guri\":\n text: \"\"\"Al comienzo de la fase de ",
"end": 30809,
"score": 0.9919307231903076,
"start": 30805,
"tag": "NAME",
"value": "Guri"
},
{
"context": "e.\"\"\"\n ship: \"Víbora Estelar\"\n \"Cartel Spacer\":\n name: \"Agente del Cártel\"\n ",
"end": 31021,
"score": 0.9865367412567139,
"start": 31008,
"tag": "NAME",
"value": "Cartel Spacer"
},
{
"context": "elar\"\n \"Cartel Spacer\":\n name: \"Agente del Cártel\"\n ship: \"Interceptor M3-A\"\n \"Ta",
"end": 31060,
"score": 0.9993780851364136,
"start": 31043,
"tag": "NAME",
"value": "Agente del Cártel"
},
{
"context": " \"Tansarii Point Veteran\":\n name: \"Veterano de Punto Tansarii\"\n ship: \"Interceptor M3-A\"\n \"Se",
"end": 31178,
"score": 0.9996282458305359,
"start": 31152,
"tag": "NAME",
"value": "Veterano de Punto Tansarii"
},
{
"context": "ii\"\n ship: \"Interceptor M3-A\"\n \"Serissu\":\n text: \"\"\"Cuando otra nave aliada si",
"end": 31233,
"score": 0.9511868357658386,
"start": 31226,
"tag": "NAME",
"value": "Serissu"
},
{
"context": "\"\"\"\n ship: \"Interceptor M3-A\"\n \"Laetin A'shera\":\n text: \"\"\"Después de que te hayas de",
"end": 31417,
"score": 0.9998241066932678,
"start": 31403,
"tag": "NAME",
"value": "Laetin A'shera"
},
{
"context": "ondiente.\"\"\"\n ship: \"Agresor\"\n \"Mandalorian Mercenary\":\n name: \"Mercenario Mandaloriano\"\n ",
"end": 32404,
"score": 0.9998834133148193,
"start": 32383,
"tag": "NAME",
"value": "Mandalorian Mercenary"
},
{
"context": " \"Mandalorian Mercenary\":\n name: \"Mercenario Mandaloriano\"\n \"Boba Fett (Scum)\":\n text: \"\"",
"end": 32449,
"score": 0.999846339225769,
"start": 32426,
"tag": "NAME",
"value": "Mercenario Mandaloriano"
},
{
"context": " name: \"Mercenario Mandaloriano\"\n \"Boba Fett (Scum)\":\n text: \"\"\"Cuando ataques o te",
"end": 32469,
"score": 0.9998812675476074,
"start": 32460,
"tag": "NAME",
"value": "Boba Fett"
},
{
"context": " nave enemiga que tengas a alcance 1.\"\"\"\n \"Kath Scarlet (Scum)\":\n text: \"\"\"Cuando ataques una ",
"end": 32638,
"score": 0.9998559951782227,
"start": 32626,
"tag": "NAME",
"value": "Kath Scarlet"
},
{
"context": "iar, tira 1 dado de ataque adicional.\"\"\"\n \"Emon Azzameen\":\n text: \"\"\"Cuando sueltes una bomba, ",
"end": 32797,
"score": 0.9998257756233215,
"start": 32784,
"tag": "NAME",
"value": "Emon Azzameen"
},
{
"context": "ez de la plantilla de [%STRAIGHT% 1].\"\"\"\n \"Kavil\":\n ship: \"Ala-Y\"\n text: \"\"\"",
"end": 32996,
"score": 0.9989592432975769,
"start": 32991,
"tag": "NAME",
"value": "Kavil"
},
{
"context": "ego, tira 1 dado de ataque adicional.\"\"\"\n \"Drea Renthal\":\n ship: \"Ala-Y\"\n text: \"\"\"",
"end": 33163,
"score": 0.9996355772018433,
"start": 33151,
"tag": "NAME",
"value": "Drea Renthal"
},
{
"context": "icha de Tensión para fijar un blanco.\"\"\"\n \"Syndicate Thug\":\n name: \"Esbirro del sindicato\"\n ",
"end": 33341,
"score": 0.9979459047317505,
"start": 33327,
"tag": "NAME",
"value": "Syndicate Thug"
},
{
"context": ".\"\"\"\n \"Syndicate Thug\":\n name: \"Esbirro del sindicato\"\n ship: \"Ala-Y\"\n \"Hired Gun\":\n ",
"end": 33384,
"score": 0.998206377029419,
"start": 33363,
"tag": "NAME",
"value": "Esbirro del sindicato"
},
{
"context": "del sindicato\"\n ship: \"Ala-Y\"\n \"Hired Gun\":\n name: \"Piloto de fortuna\"\n ",
"end": 33430,
"score": 0.9972915649414062,
"start": 33421,
"tag": "NAME",
"value": "Hired Gun"
},
{
"context": ": \"Ala-Y\"\n \"Hired Gun\":\n name: \"Piloto de fortuna\"\n ship: \"Ala-Y\"\n \"Spice Runner\"",
"end": 33469,
"score": 0.9984105229377747,
"start": 33452,
"tag": "NAME",
"value": "Piloto de fortuna"
},
{
"context": "to de fortuna\"\n ship: \"Ala-Y\"\n \"Spice Runner\":\n name: \"Traficante de Especia\"\n ",
"end": 33518,
"score": 0.9554569125175476,
"start": 33506,
"tag": "NAME",
"value": "Spice Runner"
},
{
"context": "Ala-Y\"\n \"Spice Runner\":\n name: \"Traficante de Especia\"\n ship: \"HWK-290\"\n \"Dace Bonear",
"end": 33561,
"score": 0.9973313212394714,
"start": 33540,
"tag": "NAME",
"value": "Traficante de Especia"
},
{
"context": " de Especia\"\n ship: \"HWK-290\"\n \"Dace Bonearm\":\n text: \"\"\"Cuando una nave enemiga a ",
"end": 33612,
"score": 0.9967349767684937,
"start": 33600,
"tag": "NAME",
"value": "Dace Bonearm"
},
{
"context": " de daño.\"\"\"\n ship: \"HWK-290\"\n \"Palob Godalhi\":\n text: \"\"\"Al comienzo de la fase de ",
"end": 33864,
"score": 0.9987670183181763,
"start": 33851,
"tag": "NAME",
"value": "Palob Godalhi"
},
{
"context": "ce 1-2 y asignar esa ficha a tu nave.\"\"\"\n \"Torkil Mux\":\n text: \"\"\"Al final de la fase de Act",
"end": 34059,
"score": 0.9996347427368164,
"start": 34049,
"tag": "NAME",
"value": "Torkil Mux"
},
{
"context": "piloto de esa nave tiene Habilidad 0.\"\"\"\n \"Binayre Pirate\":\n name: \"Pirata Binayre\"\n ",
"end": 34276,
"score": 0.9987954497337341,
"start": 34262,
"tag": "NAME",
"value": "Binayre Pirate"
},
{
"context": ".\"\"\"\n \"Binayre Pirate\":\n name: \"Pirata Binayre\"\n ship: \"Z-95 Cazacabezas\"\n \"Bl",
"end": 34312,
"score": 0.9997889995574951,
"start": 34298,
"tag": "NAME",
"value": "Pirata Binayre"
},
{
"context": " ship: \"Z-95 Cazacabezas\"\n \"Black Sun Soldier\":\n name: \"Sicario del Sol Negro\"\n ",
"end": 34377,
"score": 0.8170326352119446,
"start": 34366,
"tag": "NAME",
"value": "Sun Soldier"
},
{
"context": "\"\n \"Black Sun Soldier\":\n name: \"Sicario del Sol Negro\"\n ship: \"Z-95 Cazacabezas\"\n \"N'",
"end": 34420,
"score": 0.999505877494812,
"start": 34399,
"tag": "NAME",
"value": "Sicario del Sol Negro"
},
{
"context": "ro\"\n ship: \"Z-95 Cazacabezas\"\n \"N'Dru Suhlak\":\n text: \"\"\"Cuando ataques, si no tien",
"end": 34480,
"score": 0.9997078776359558,
"start": 34468,
"tag": "NAME",
"value": "N'Dru Suhlak"
},
{
"context": "\"\"\"\n ship: \"Z-95 Cazacabezas\"\n \"Kaa'to Leeachos\":\n text: \"\"\"Al comienzo de la fase de ",
"end": 34670,
"score": 0.9996739625930786,
"start": 34655,
"tag": "NAME",
"value": "Kaa'to Leeachos"
},
{
"context": "\"\"\"\n ship: \"Z-95 Cazacabezas\"\n \"Commander Alozen\":\n name: \"Comandante Alozen\"\n ",
"end": 34919,
"score": 0.9998092651367188,
"start": 34903,
"tag": "NAME",
"value": "Commander Alozen"
},
{
"context": "s\"\n \"Commander Alozen\":\n name: \"Comandante Alozen\"\n ship: \"TIE Avanzado\"\n tex",
"end": 34958,
"score": 0.999857485294342,
"start": 34941,
"tag": "NAME",
"value": "Comandante Alozen"
},
{
"context": " nave enemiga que tengas a alcance 1.\"\"\"\n \"Juno Eclipse\":\n ship: \"TIE Avanzado\"\n te",
"end": 35139,
"score": 0.9997058510780334,
"start": 35127,
"tag": "NAME",
"value": "Juno Eclipse"
},
{
"context": "e la maniobra (hasta un mínimo de 1).\"\"\"\n \"Zertik Strom\":\n ship: \"TIE Avanzado\"\n te",
"end": 35334,
"score": 0.999774158000946,
"start": 35322,
"tag": "NAME",
"value": "Zertik Strom"
},
{
"context": "l combate por alcance cuando ataquen.\"\"\"\n \"Lieutenant Colzet\":\n name: \"Teniente Colzet\"\n ",
"end": 35534,
"score": 0.9998779892921448,
"start": 35517,
"tag": "NAME",
"value": "Lieutenant Colzet"
},
{
"context": "\"\n \"Lieutenant Colzet\":\n name: \"Teniente Colzet\"\n ship: \"TIE Avanzado\"\n tex",
"end": 35571,
"score": 0.9998676776885986,
"start": 35556,
"tag": "NAME",
"value": "Teniente Colzet"
},
{
"context": "e esa nave tenga asignada boca abajo.\"\"\"\n \"Latts Razzi\":\n text: \"\"\"Cuando una nave aliada dec",
"end": 35859,
"score": 0.999468982219696,
"start": 35848,
"tag": "NAME",
"value": "Latts Razzi"
},
{
"context": "idad en 1 contra el ataque declarado.\"\"\"\n \"Miranda Doni\":\n ship: 'Ala-K'\n text: \"\"\"",
"end": 36079,
"score": 0.9997281432151794,
"start": 36067,
"tag": "NAME",
"value": "Miranda Doni"
},
{
"context": "ue menos para recuperar 1 de Escudos.\"\"\"\n \"Esege Tuketu\":\n ship: 'Ala-K'\n text: \"\"\"",
"end": 36348,
"score": 0.9965338110923767,
"start": 36336,
"tag": "NAME",
"value": "Esege Tuketu"
},
{
"context": " \"Guardian Squadron Pilot\":\n name: \"Piloto del Escuadrón Guardián\"\n ship: 'Ala-",
"end": 36563,
"score": 0.830383837223053,
"start": 36561,
"tag": "NAME",
"value": "lo"
},
{
"context": " 'Ala-K'\n '\"Redline\"':\n name: '\"Velocidad Terminal\"'\n ship: 'Castigador TIE'\n ",
"end": 36784,
"score": 0.8859695196151733,
"start": 36766,
"tag": "NAME",
"value": "Velocidad Terminal"
},
{
"context": "ez.\"\"\"\n '\"Deathrain\"':\n name: '\"Lluvia de Muerte\"'\n ship: 'Castigador TIE'\n ",
"end": 37041,
"score": 0.9998235702514648,
"start": 37025,
"tag": "NAME",
"value": "Lluvia de Muerte"
},
{
"context": " 'Black Eight Squadron Pilot':\n name: \"Piloto del Escuadrón Ocho Negro\"\n ship: 'Castigador TIE'\n 'Cutl",
"end": 37358,
"score": 0.9103155732154846,
"start": 37327,
"tag": "NAME",
"value": "Piloto del Escuadrón Ocho Negro"
},
{
"context": " 'Cutlass Squadron Pilot':\n name: \"Piloto del Escuadrón Alfanje\"\n ship: 'Castigador TIE'\n \"Mora",
"end": 37476,
"score": 0.9137307405471802,
"start": 37448,
"tag": "NAME",
"value": "Piloto del Escuadrón Alfanje"
},
{
"context": "u may deploy up to 2 attached ships.\"\"\"\n '\"Scourge\"':\n name: \"Azote\"\n ship: \"C",
"end": 37834,
"score": 0.9313817024230957,
"start": 37827,
"tag": "NAME",
"value": "Scourge"
},
{
"context": "ships.\"\"\"\n '\"Scourge\"':\n name: \"Azote\"\n ship: \"Caza TIE\"\n text: \"",
"end": 37862,
"score": 0.9903996586799622,
"start": 37857,
"tag": "NAME",
"value": "Azote"
},
{
"context": "ira 1 dado de ataque adicional.\"\"\"\n \"The Inquisitor\":\n name: \"El Inquisidor\"\n ",
"end": 38032,
"score": 0.527858316898346,
"start": 38028,
"tag": "NAME",
"value": "quis"
},
{
"context": ".\"\"\"\n \"The Inquisitor\":\n name: \"El Inquisidor\"\n ship: \"Prototipo de TIE Avanzado\"\n ",
"end": 38071,
"score": 0.9795547723770142,
"start": 38058,
"tag": "NAME",
"value": "El Inquisidor"
},
{
"context": "el alcance del ataque se considera 1.\"\"\"\n \"Zuckuss\":\n ship: \"Caza Estelar G-1A\"\n ",
"end": 38254,
"score": 0.9318737387657166,
"start": 38247,
"tag": "NAME",
"value": "Zuckuss"
},
{
"context": "or tira 1 dado de defensa adicional.\"\"\"\n \"Ruthless Freelancer\":\n name: \"Mercenario De",
"end": 38455,
"score": 0.5610802173614502,
"start": 38452,
"tag": "NAME",
"value": "uth"
},
{
"context": " 1 dado de defensa adicional.\"\"\"\n \"Ruthless Freelancer\":\n name: \"Mercenario Despiadado",
"end": 38463,
"score": 0.5607768297195435,
"start": 38460,
"tag": "NAME",
"value": "Fre"
},
{
"context": " \"Ruthless Freelancer\":\n name: \"Mercenario Despiadado\"\n ship: \"Caza Estelar G-1A\"\n \"G",
"end": 38513,
"score": 0.9873572587966919,
"start": 38492,
"tag": "NAME",
"value": "Mercenario Despiadado"
},
{
"context": "o\"\n ship: \"Caza Estelar G-1A\"\n \"Gand Findsman\":\n name: \"Buscador Gandiano\"\n ",
"end": 38575,
"score": 0.9995118379592896,
"start": 38562,
"tag": "NAME",
"value": "Gand Findsman"
},
{
"context": "G-1A\"\n \"Gand Findsman\":\n name: \"Buscador Gandiano\"\n ship: \"Caza Estelar G-1A\"\n \"D",
"end": 38614,
"score": 0.9998607635498047,
"start": 38597,
"tag": "NAME",
"value": "Buscador Gandiano"
},
{
"context": "o\"\n ship: \"Caza Estelar G-1A\"\n \"Dengar\":\n ship: \"Saltador Maestro 5000\"\n ",
"end": 38669,
"score": 0.8715019822120667,
"start": 38663,
"tag": "NAME",
"value": "Dengar"
},
{
"context": "ificaciones al combate por alcance.\"\"\"\n \"Graz the Hunter\":\n name: \"Graz el Cazador\"\n ",
"end": 39080,
"score": 0.9154031276702881,
"start": 39067,
"tag": "NAME",
"value": "az the Hunter"
},
{
"context": "\"\"\"\n \"Graz the Hunter\":\n name: \"Graz el Cazador\"\n ship: \"Caza Kihraxz\"\n tex",
"end": 39117,
"score": 0.9940435886383057,
"start": 39102,
"tag": "NAME",
"value": "Graz el Cazador"
},
{
"context": " Negro\"\n ship: \"Caza Kihraxz\"\n \"Cartel Marauder\":\n name: \"Salteador del Cártel\"\n ",
"end": 39405,
"score": 0.9997595548629761,
"start": 39390,
"tag": "NAME",
"value": "Cartel Marauder"
},
{
"context": "xz\"\n \"Cartel Marauder\":\n name: \"Salteador del Cártel\"\n ship: \"Caza Kihraxz\"\n \"Trando",
"end": 39447,
"score": 0.9990395307540894,
"start": 39427,
"tag": "NAME",
"value": "Salteador del Cártel"
},
{
"context": "Cártel\"\n ship: \"Caza Kihraxz\"\n \"Trandoshan Slaver\":\n name: \"Esclavista Trandoshano\"\n ",
"end": 39508,
"score": 0.9972378611564636,
"start": 39491,
"tag": "NAME",
"value": "Trandoshan Slaver"
},
{
"context": "\"\n \"Trandoshan Slaver\":\n name: \"Esclavista Trandoshano\"\n ship: \"YV-666\"\n \"Bossk\":\n ",
"end": 39552,
"score": 0.9997552633285522,
"start": 39530,
"tag": "NAME",
"value": "Esclavista Trandoshano"
},
{
"context": " Trandoshano\"\n ship: \"YV-666\"\n \"Bossk\":\n ship: \"YV-666\"\n text: \"\"",
"end": 39595,
"score": 0.901289701461792,
"start": 39590,
"tag": "NAME",
"value": "Bossk"
},
{
"context": "ir 2 resultados %HIT%.\"\"\"\n # T-70\n \"Poe Dameron\":\n ship: \"T-70 Ala-X\"\n text",
"end": 39821,
"score": 0.9993141293525696,
"start": 39810,
"tag": "NAME",
"value": "Poe Dameron"
},
{
"context": "DE%.\"\"\"\n '\"Blue Ace\"':\n name: '\"As Azul\"'\n ship: \"T-70 Ala-X\"\n text",
"end": 40074,
"score": 0.969216525554657,
"start": 40067,
"tag": "NAME",
"value": "As Azul"
},
{
"context": " \"Red Squadron Veteran\":\n name: \"Veterano del Esc. Rojo\"\n ship: \"T-70 Ala-X\"\n \"Blue Squ",
"end": 40319,
"score": 0.9995594024658203,
"start": 40297,
"tag": "NAME",
"value": "Veterano del Esc. Rojo"
},
{
"context": "70 Ala-X\"\n '\"Red Ace\"':\n name: \"As Rojo\"\n ship: \"T-70 Ala-X\"\n text:",
"end": 40503,
"score": 0.8442475199699402,
"start": 40496,
"tag": "NAME",
"value": "As Rojo"
},
{
"context": "\"\n '\"Epsilon Leader\"':\n name: '\"Jefe Epsilon\"'\n ship: \"Caza TIE/fo\"\n tex",
"end": 41051,
"score": 0.9878674745559692,
"start": 41039,
"tag": "NAME",
"value": "Jefe Epsilon"
},
{
"context": "/fo\"\n '\"Omega Leader\"':\n name: \"Jefe Omega\"\n ship: \"Caza TIE/fo\"\n text",
"end": 41837,
"score": 0.99654221534729,
"start": 41827,
"tag": "NAME",
"value": "Jefe Omega"
},
{
"context": "atacan o se defienden de tus ataques.'''\n 'Hera Syndulla':\n text: '''Cuando reveles una maniobr",
"end": 42047,
"score": 0.9931618571281433,
"start": 42034,
"tag": "NAME",
"value": "Hera Syndulla"
},
{
"context": "coger otra maniobra del mismo color.'''\n '\"Youngster\"':\n name: \"Pipiolo\"\n ship: ",
"end": 42217,
"score": 0.9953483939170837,
"start": 42208,
"tag": "NAME",
"value": "Youngster"
},
{
"context": "lor.'''\n '\"Youngster\"':\n name: \"Pipiolo\"\n ship: \"Caza TIE\"\n text: \"",
"end": 42247,
"score": 0.9997506737709045,
"start": 42240,
"tag": "NAME",
"value": "Pipiolo"
},
{
"context": "tu carta de Mejora %ELITE% equipada.\"\"\"\n '\"Wampa\"':\n ship: \"Caza TIE\"\n text:",
"end": 42430,
"score": 0.9954032301902771,
"start": 42425,
"tag": "NAME",
"value": "Wampa"
},
{
"context": "arta de Daño boca abajo al defensor.\"\"\"\n '\"Chaser\"':\n name: \"Perseguidor\"\n sh",
"end": 42705,
"score": 0.9984538555145264,
"start": 42699,
"tag": "NAME",
"value": "Chaser"
},
{
"context": "fensor.\"\"\"\n '\"Chaser\"':\n name: \"Perseguidor\"\n ship: \"Caza TIE\"\n text: \"",
"end": 42739,
"score": 0.9996795654296875,
"start": 42728,
"tag": "NAME",
"value": "Perseguidor"
},
{
"context": "a 1 ficha de Concentración a tu nave.\"\"\"\n 'Ezra Bridger':\n ship: \"Lanzadera de Ataque\"\n ",
"end": 42939,
"score": 0.999380886554718,
"start": 42927,
"tag": "NAME",
"value": "Ezra Bridger"
},
{
"context": "ados %FOCUS% por resultados %EVADE%.\"\"\"\n '\"Zeta Leader\"':\n name: \"Jefe Zeta\"\n ",
"end": 43137,
"score": 0.7834669351577759,
"start": 43133,
"tag": "NAME",
"value": "Zeta"
},
{
"context": "%.\"\"\"\n '\"Zeta Leader\"':\n name: \"Jefe Zeta\"\n text: '''Cuando ataques, si no estás",
"end": 43176,
"score": 0.9998437762260437,
"start": 43167,
"tag": "NAME",
"value": "Jefe Zeta"
},
{
"context": "E/fo\"\n '\"Epsilon Ace\"':\n name: \"As Epsilon\"\n text: '''Mientras no tengas ninguna ",
"end": 43403,
"score": 0.9832921028137207,
"start": 43393,
"tag": "NAME",
"value": "As Epsilon"
},
{
"context": "d 12.'''\n ship: \"Caza TIE/fo\"\n \"Kanan Jarrus\":\n text: \"\"\"Cuando una nave enemiga qu",
"end": 43571,
"score": 0.9947901964187622,
"start": 43559,
"tag": "NAME",
"value": "Kanan Jarrus"
},
{
"context": "tacante tira 1 dado de ataque menos.\"\"\"\n '\"Chopper\"':\n text: \"\"\"Al comienzo de la fase de",
"end": 43786,
"score": 0.785443127155304,
"start": 43779,
"tag": "NAME",
"value": "Chopper"
},
{
"context": " contacto recibe 1 ficha de Tensión.\"\"\"\n 'Hera Syndulla (Attack Shuttle)':\n name: \"He",
"end": 43936,
"score": 0.873158872127533,
"start": 43933,
"tag": "NAME",
"value": "era"
},
{
"context": "ra Syndulla (Attack Shuttle)':\n name: \"Hera Syndulla (Lanzadera de Ataque)\"\n ship: \"Lanzade",
"end": 43997,
"score": 0.9898610711097717,
"start": 43984,
"tag": "NAME",
"value": "Hera Syndulla"
},
{
"context": "scoger otra maniobra del mismo color.\"\"\"\n 'Sabine Wren':\n ship: \"Lanzadera de Ataque\"\n ",
"end": 44229,
"score": 0.9977928400039673,
"start": 44218,
"tag": "NAME",
"value": "Sabine Wren"
},
{
"context": " gratuita de impulso o tonel volado.\"\"\"\n '\"Zeb\" Orrelios':\n ship: \"Lanzadera de Ataque\"\n ",
"end": 44427,
"score": 0.9742516875267029,
"start": 44414,
"tag": "NAME",
"value": "Zeb\" Orrelios"
},
{
"context": "IT% antes de anular resultados %HIT%.'''\n \"Lothal Rebel\":\n name: \"Rebelde de Lothal\"\n ",
"end": 44602,
"score": 0.9984588623046875,
"start": 44590,
"tag": "NAME",
"value": "Lothal Rebel"
},
{
"context": "T%.'''\n \"Lothal Rebel\":\n name: \"Rebelde de Lothal\"\n ship: \"VCX-100\"\n 'Tomax Bren'",
"end": 44641,
"score": 0.999289333820343,
"start": 44624,
"tag": "NAME",
"value": "Rebelde de Lothal"
},
{
"context": "e de Lothal\"\n ship: \"VCX-100\"\n 'Tomax Bren':\n text: '''Una vez por ronda, después",
"end": 44690,
"score": 0.9980391263961792,
"start": 44680,
"tag": "NAME",
"value": "Tomax Bren"
},
{
"context": "a.'''\n ship: \"Bombardero TIE\"\n 'Ello Asty':\n text: '''Mientras no estés bajo ten",
"end": 44902,
"score": 0.9950981140136719,
"start": 44893,
"tag": "NAME",
"value": "Ello Asty"
},
{
"context": "ancas.'''\n ship: \"T-70 Ala-X\"\n \"Valen Rudor\":\n text: \"\"\"Después de que te defienda",
"end": 45093,
"score": 0.9948791265487671,
"start": 45082,
"tag": "NAME",
"value": "Valen Rudor"
},
{
"context": " otra nave que tengas a alcance 1.\"\"\"\n \"Tel Trevura\":\n ship: \"Saltador Maestro 5000\"\n ",
"end": 45438,
"score": 0.9914799332618713,
"start": 45431,
"tag": "NAME",
"value": "Trevura"
},
{
"context": "artas de Daño boca abajo a esta nave.\"\"\"\n \"Manaroo\":\n ship: \"Saltador Maestro 5000\"\n ",
"end": 45687,
"score": 0.7416531443595886,
"start": 45680,
"tag": "NAME",
"value": "Manaroo"
},
{
"context": "\"\"\n \"Contracted Scout\":\n name: \"Explorador Contratado\"\n ship: \"Saltador Maestro 5000\"\n ",
"end": 45986,
"score": 0.9991495013237,
"start": 45965,
"tag": "NAME",
"value": "Explorador Contratado"
},
{
"context": "o 5000\"\n '\"Deathfire\"':\n name: \"Muerte Ígnea\"\n text: '''Cuando reveles tu selector ",
"end": 46084,
"score": 0.9997164607048035,
"start": 46072,
"tag": "NAME",
"value": "Muerte Ígnea"
},
{
"context": " \"Baron of the Empire\":\n name: \"Barón del Imperio\"\n ship: \"Prototipo de TIE Avanzado\"\n ",
"end": 46488,
"score": 0.978897750377655,
"start": 46471,
"tag": "NAME",
"value": "Barón del Imperio"
},
{
"context": " ship: \"Prototipo de TIE Avanzado\"\n \"Maarek Stele (TIE Defender)\":\n name: \"Maarek ",
"end": 46551,
"score": 0.8309138417243958,
"start": 46545,
"tag": "NAME",
"value": "Maarek"
},
{
"context": "\"Maarek Stele (TIE Defender)\":\n name: \"Maarek Stele (Defensor TIE)\"\n text: \"\"\"Cuando tu at",
"end": 46606,
"score": 0.9996126890182495,
"start": 46594,
"tag": "NAME",
"value": "Maarek Stele"
},
{
"context": "ras.\"\"\"\n ship: \"Defensor TIE\"\n \"Countess Ryad\":\n name: \"Condesa Ryad\"\n te",
"end": 46866,
"score": 0.9940062761306763,
"start": 46853,
"tag": "NAME",
"value": "Countess Ryad"
},
{
"context": " TIE\"\n \"Countess Ryad\":\n name: \"Condesa Ryad\"\n text: \"\"\"Cuando reveles una maniobra",
"end": 46900,
"score": 0.9995027184486389,
"start": 46888,
"tag": "NAME",
"value": "Condesa Ryad"
},
{
"context": " \"Glaive Squadron Pilot\":\n name: \"Piloto del escuadrón Guja\"\n ship: \"Defensor T",
"end": 47104,
"score": 0.7280270457267761,
"start": 47098,
"tag": "NAME",
"value": "Piloto"
},
{
"context": "quadron Pilot\":\n name: \"Piloto del escuadrón Guja\"\n ship: \"Defensor TIE\"\n \"Poe Da",
"end": 47123,
"score": 0.6947072148323059,
"start": 47113,
"tag": "NAME",
"value": "adrón Guja"
},
{
"context": "n Guja\"\n ship: \"Defensor TIE\"\n \"Poe Dameron (PS9)\":\n text: \"\"\"Cuando ataques o te ",
"end": 47178,
"score": 0.9763248562812805,
"start": 47167,
"tag": "NAME",
"value": "Poe Dameron"
},
{
"context": " \"Resistance Sympathizer\":\n name: \"Simpatizante de la Resistencia\"\n ship: \"YT-",
"end": 47445,
"score": 0.544996440410614,
"start": 47441,
"tag": "NAME",
"value": "Simp"
},
{
"context": "los que hayas sacado caras vacías.\"\"\"\n 'Han Solo (TFA)':\n text: '''En el momento de des",
"end": 47714,
"score": 0.6603339910507202,
"start": 47710,
"tag": "NAME",
"value": "Solo"
},
{
"context": "e alcance 3 de las naves enemigas.'''\n 'Chewbacca (TFA)':\n text: '''Después de que otra ",
"end": 47945,
"score": 0.6390733122825623,
"start": 47939,
"tag": "NAME",
"value": "wbacca"
},
{
"context": " batalla), puedes efectuar un ataque.'''\n 'Norra Wexley':\n ship: \"ARC-170\"\n text: '",
"end": 48144,
"score": 0.9976738691329956,
"start": 48132,
"tag": "NAME",
"value": "Norra Wexley"
},
{
"context": "adir 1 resultado %FOCUS% a tu tirada.'''\n 'Shara Bey':\n ship: \"ARC-170\"\n text: '",
"end": 48367,
"score": 0.9679972529411316,
"start": 48358,
"tag": "NAME",
"value": "Shara Bey"
},
{
"context": "e Blanco fijado como si fuesen suyas.'''\n 'Thane Kyrell':\n ship: \"ARC-170\"\n text: '",
"end": 48575,
"score": 0.9994660019874573,
"start": 48563,
"tag": "NAME",
"value": "Thane Kyrell"
},
{
"context": " puedes realizar una acción gratuita.'''\n 'Braylen Stramm':\n ship: \"ARC-170\"\n text: '",
"end": 48801,
"score": 0.9978928565979004,
"start": 48787,
"tag": "NAME",
"value": "Braylen Stramm"
},
{
"context": "ave.'''\n '\"Quickdraw\"':\n name: \"Centella\"\n ship: \"Caza TIE/sf\"\n text",
"end": 49037,
"score": 0.9992625117301941,
"start": 49029,
"tag": "NAME",
"value": "Centella"
},
{
"context": "pal.'''\n '\"Backdraft\"':\n name: \"Llamarada\"\n ship: \"Caza TIE/sf\"\n text",
"end": 49252,
"score": 0.9997078776359558,
"start": 49243,
"tag": "NAME",
"value": "Llamarada"
},
{
"context": "ón Zeta\"\n ship: \"Caza TIE/sf\"\n 'Fenn Rau':\n ship: \"Caza Estelar del Protectorad",
"end": 49657,
"score": 0.9975463151931763,
"start": 49649,
"tag": "NAME",
"value": "Fenn Rau"
},
{
"context": "nce 1, puedes tirar 1 dado adicional.'''\n 'Old Teroch':\n name: \"Viejo Teroch\"\n sh",
"end": 49854,
"score": 0.9235828518867493,
"start": 49844,
"tag": "NAME",
"value": "Old Teroch"
},
{
"context": "onal.'''\n 'Old Teroch':\n name: \"Viejo Teroch\"\n ship: \"Caza Estelar del Protectorado",
"end": 49888,
"score": 0.9996735453605652,
"start": 49876,
"tag": "NAME",
"value": "Viejo Teroch"
},
{
"context": "us fichas de Concentración y Evasión.'''\n 'Kad Solus':\n ship: \"Caza Estelar del Protectorad",
"end": 50170,
"score": 0.979016900062561,
"start": 50161,
"tag": "NAME",
"value": "Kad Solus"
},
{
"context": " 2 fichas de Concentración a tu nave.'''\n 'Concord Dawn Ace':\n name: \"As de Concord Dawn\"\n ",
"end": 50359,
"score": 0.9755303263664246,
"start": 50343,
"tag": "NAME",
"value": "Concord Dawn Ace"
},
{
"context": "''\n 'Concord Dawn Ace':\n name: \"As de Concord Dawn\"\n ship: \"Caza Estelar del Protectorado",
"end": 50399,
"score": 0.8924334645271301,
"start": 50381,
"tag": "NAME",
"value": "As de Concord Dawn"
},
{
"context": " ship: \"Caza Estelar del Protectorado\"\n 'Concord Dawn Veteran':\n name: \"Veterano de Concord Dawn\"\n ",
"end": 50480,
"score": 0.9358344078063965,
"start": 50460,
"tag": "NAME",
"value": "Concord Dawn Veteran"
},
{
"context": " 'Concord Dawn Veteran':\n name: \"Veterano de Concord Dawn\"\n ship: \"Caza Estelar del Protectorado",
"end": 50526,
"score": 0.9785444736480713,
"start": 50502,
"tag": "NAME",
"value": "Veterano de Concord Dawn"
},
{
"context": " ship: \"Caza Estelar del Protectorado\"\n 'Zealous Recruit':\n name: \"Recluta entusiasta\"\n ",
"end": 50602,
"score": 0.7347378730773926,
"start": 50587,
"tag": "NAME",
"value": "Zealous Recruit"
},
{
"context": "do\"\n 'Zealous Recruit':\n name: \"Recluta entusiasta\"\n ship: \"Caza Estelar del Protectorado",
"end": 50642,
"score": 0.8762590289115906,
"start": 50624,
"tag": "NAME",
"value": "Recluta entusiasta"
},
{
"context": " ship: \"Caza Estelar del Protectorado\"\n 'Ketsu Onyo':\n ship: \"Nave de persecución clase La",
"end": 50713,
"score": 0.9898622632026672,
"start": 50703,
"tag": "NAME",
"value": "Ketsu Onyo"
},
{
"context": "sígnale 1 ficha de Campo de tracción.'''\n 'Asajj Ventress':\n ship: \"Nave de persecución clase La",
"end": 51017,
"score": 0.9842326045036316,
"start": 51003,
"tag": "NAME",
"value": "Asajj Ventress"
},
{
"context": "o móvil, asígnale 1 ficha de Tensión.'''\n 'Sabine Wren (Scum)':\n ship: \"Nave de persecución c",
"end": 51282,
"score": 0.973946750164032,
"start": 51271,
"tag": "NAME",
"value": "Sabine Wren"
},
{
"context": "adir 1 resultado %FOCUS% a tu tirada.'''\n 'Shadowport Hunter':\n name: \"Cazador de puerto clandestin",
"end": 51546,
"score": 0.9235715270042419,
"start": 51529,
"tag": "NAME",
"value": "Shadowport Hunter"
},
{
"context": "er':\n name: \"Cazador de puerto clandestino\"\n ship: \"Nave de persecución clase Lan",
"end": 51597,
"score": 0.9990468621253967,
"start": 51594,
"tag": "NAME",
"value": "ino"
},
{
"context": "hip: \"Nave de persecución clase Lancero\"\n 'Sabine Wren (TIE Fighter)':\n ship: \"Caza TIE\"\n ",
"end": 51673,
"score": 0.9982343912124634,
"start": 51662,
"tag": "NAME",
"value": "Sabine Wren"
},
{
"context": "IT% antes de anular resultados %HIT%.'''\n 'Kylo Ren':\n ship: \"Lanzadera clase Ípsilon\"\n ",
"end": 52048,
"score": 0.9984830021858215,
"start": 52040,
"tag": "NAME",
"value": "Kylo Ren"
},
{
"context": "mostraré el Lado Oscuro\" al atacante.'''\n 'Unkar Plutt':\n ship: \"Saltador Quad\"\n t",
"end": 52272,
"score": 0.9996670484542847,
"start": 52261,
"tag": "NAME",
"value": "Unkar Plutt"
},
{
"context": "da nave con la que estés en contacto.'''\n 'Cassian Andor':\n ship: \"Ala-U\"\n text: '''",
"end": 52494,
"score": 0.9998183250427246,
"start": 52481,
"tag": "NAME",
"value": "Cassian Andor"
},
{
"context": "nave aliada que tengas a alcance 1-2.'''\n 'Bodhi Rook':\n ship: \"Ala-U\"\n text: '''",
"end": 52685,
"score": 0.9997071027755737,
"start": 52675,
"tag": "NAME",
"value": "Bodhi Rook"
},
{
"context": "alcance 1-3 de cualquier nave aliada.'''\n 'Heff Tobber':\n ship: \"Ala-U\"\n text: '''",
"end": 52900,
"score": 0.9997591972351074,
"start": 52889,
"tag": "NAME",
"value": "Heff Tobber"
},
{
"context": "edes realizar una acción gratuita.'''\n '''\"Duchess\"''':\n ship: \"Fustigador TIE\"\n ",
"end": 53097,
"score": 0.9997336864471436,
"start": 53090,
"tag": "NAME",
"value": "Duchess"
},
{
"context": " ship: \"Fustigador TIE\"\n name: '\"Duquesa\"'\n text: '''Cuando tengas equipada la ",
"end": 53165,
"score": 0.9998146891593933,
"start": 53158,
"tag": "NAME",
"value": "Duquesa"
},
{
"context": " ship: \"Fustigador TIE\"\n name: '\"Sabacc Puro\"'\n text: '''Cuando ataques, si tienes ",
"end": 53398,
"score": 0.9973651766777039,
"start": 53387,
"tag": "NAME",
"value": "Sabacc Puro"
},
{
"context": " ship: \"Fustigador TIE\"\n name: '\"Cuenta Atrás\"'\n text: '''Cuando te defiendas, si no",
"end": 53604,
"score": 0.9992682337760925,
"start": 53592,
"tag": "NAME",
"value": "Cuenta Atrás"
},
{
"context": "lo haces, recibes 1 ficha de Tensión.'''\n 'Nien Nunb':\n ship: \"T-70 Ala-X\"\n text",
"end": 53874,
"score": 0.9998732805252075,
"start": 53865,
"tag": "NAME",
"value": "Nien Nunb"
},
{
"context": "descartar esa ficha de Tensión.'''\n '\"Snap\" Wexley':\n ship: \"T-70 Ala-X\"\n text",
"end": 54097,
"score": 0.9656021595001221,
"start": 54091,
"tag": "NAME",
"value": "Wexley"
},
{
"context": "lizar una acción gratuita de impulso.'''\n 'Jess Pava':\n ship: \"T-70 Ala-X\"\n text",
"end": 54323,
"score": 0.9998435974121094,
"start": 54314,
"tag": "NAME",
"value": "Jess Pava"
},
{
"context": "a nave aliada que tengas a Alcance 1.'''\n 'Ahsoka Tano':\n ship: \"Caza TIE\"\n text: ",
"end": 54519,
"score": 0.9977507591247559,
"start": 54508,
"tag": "NAME",
"value": "Ahsoka Tano"
},
{
"context": "ave puede realizar 1 acción gratuita.'''\n 'Captain Rex':\n ship: \"Caza TIE\"\n name: ",
"end": 54764,
"score": 0.997290849685669,
"start": 54753,
"tag": "NAME",
"value": "Captain Rex"
},
{
"context": ":\n ship: \"Caza TIE\"\n name: \"Capitán Rex\"\n text: '''Después de que efectúes un ",
"end": 54826,
"score": 0.9960487484931946,
"start": 54815,
"tag": "NAME",
"value": "Capitán Rex"
},
{
"context": "o de supresión\" al defensor.'''\n 'Major Stridan':\n ship: \"Lanzadera clase Ípsilon\"\n ",
"end": 54967,
"score": 0.6782506704330444,
"start": 54965,
"tag": "NAME",
"value": "id"
},
{
"context": "hip: \"Lanzadera clase Ípsilon\"\n name: \"Mayor Stridan\"\n text: '''A efectos de tus acciones y",
"end": 55048,
"score": 0.9998332262039185,
"start": 55035,
"tag": "NAME",
"value": "Mayor Stridan"
},
{
"context": "e 2-3 como si estuvieran a alcance 1.'''\n 'Lieutenant Dormitz':\n ship: \"Lanzadera clase Ípsilon\"\n ",
"end": 55240,
"score": 0.9997386932373047,
"start": 55222,
"tag": "NAME",
"value": "Lieutenant Dormitz"
},
{
"context": "hip: \"Lanzadera clase Ípsilon\"\n name: \"Teniente Dormitz\"\n text: '''Durante la preparación de l",
"end": 55322,
"score": 0.9998186826705933,
"start": 55306,
"tag": "NAME",
"value": "Teniente Dormitz"
},
{
"context": "que esté situado a alcance 1-2 de ti.'''\n 'Constable Zuvio':\n ship: \"Saltador Quad\"\n n",
"end": 55526,
"score": 0.828803539276123,
"start": 55511,
"tag": "NAME",
"value": "Constable Zuvio"
},
{
"context": " ship: \"Saltador Quad\"\n name: \"Alguacil Zuvio\"\n text: '''Cuando reveles una maniobra",
"end": 55596,
"score": 0.9997618794441223,
"start": 55582,
"tag": "NAME",
"value": "Alguacil Zuvio"
},
{
"context": "cabezado \"<strong>Acción:</strong>\").'''\n 'Sarco Plank':\n ship: \"Saltador Quad\"\n t",
"end": 55827,
"score": 0.9982755184173584,
"start": 55816,
"tag": "NAME",
"value": "Sarco Plank"
},
{
"context": " name: \"Piloto de la base Starkiller\"\n \"Jakku Gunrunner\":\n ship: \"Saltador Quad\"\n n",
"end": 56630,
"score": 0.9983689785003662,
"start": 56615,
"tag": "NAME",
"value": "Jakku Gunrunner"
},
{
"context": "or Quad\"\n name: \"Traficante de armas de Jakku\"\n 'Genesis Red':\n ship: \"Interc",
"end": 56714,
"score": 0.9584309458732605,
"start": 56709,
"tag": "NAME",
"value": "Jakku"
},
{
"context": "ada tipo como la nave que has fijado.'''\n 'Quinn Jast':\n ship: \"Interceptor M3-A\"\n ",
"end": 56985,
"score": 0.9734147191047668,
"start": 56975,
"tag": "NAME",
"value": "Quinn Jast"
},
{
"context": "ra %TORPEDO% o %MISSILE% descartadas.'''\n 'Inaldra':\n ship: \"Interceptor M3-A\"\n ",
"end": 57233,
"score": 0.93791264295578,
"start": 57226,
"tag": "NAME",
"value": "Inaldra"
},
{
"context": "r cualquier cantidad de tus dados.'''\n 'Sunny Bounder':\n ship: \"Interceptor M3-A\"\n ",
"end": 57436,
"score": 0.7670138478279114,
"start": 57426,
"tag": "NAME",
"value": "ny Bounder"
},
{
"context": "e esos resultados a la tirada.'''\n 'C-ROC Cruiser':\n ship: \"Crucero C-ROC\"\n ",
"end": 57698,
"score": 0.5382205843925476,
"start": 57696,
"tag": "NAME",
"value": "ru"
},
{
"context": " ship: \"Crucero C-ROC\"\n name: \"Crucero C-ROC\"\n 'Lieutenant Kestal':\n shi",
"end": 57767,
"score": 0.9214059114456177,
"start": 57758,
"tag": "NAME",
"value": "Crucero C"
},
{
"context": "hip: \"Crucero C-ROC\"\n name: \"Crucero C-ROC\"\n 'Lieutenant Kestal':\n ship: \"",
"end": 57771,
"score": 0.8021295070648193,
"start": 57768,
"tag": "NAME",
"value": "ROC"
},
{
"context": "C-ROC\"\n name: \"Crucero C-ROC\"\n 'Lieutenant Kestal':\n ship: \"TIE Agresor\"\n tex",
"end": 57799,
"score": 0.9768286943435669,
"start": 57782,
"tag": "NAME",
"value": "Lieutenant Kestal"
},
{
"context": " ship: \"TIE Agresor\"\n name: \"Doble Filo\"\n text: '''Una vez por ronda, después ",
"end": 58070,
"score": 0.9988444447517395,
"start": 58060,
"tag": "NAME",
"value": "Doble Filo"
},
{
"context": " ship: \"TIE Agresor\"\n name: \"Escolta del Escuadrón Ónice\"\n 'Sienar Specialist':\n ship: \"",
"end": 58352,
"score": 0.9843399524688721,
"start": 58325,
"tag": "NAME",
"value": "Escolta del Escuadrón Ónice"
},
{
"context": ": \"TIE Agresor\"\n name: \"Especialista de Sienar\"\n 'Viktor Hel':\n ship: \"Caza Ki",
"end": 58456,
"score": 0.9054893851280212,
"start": 58450,
"tag": "NAME",
"value": "Sienar"
},
{
"context": " name: \"Especialista de Sienar\"\n 'Viktor Hel':\n ship: \"Caza Kihraxz\"\n te",
"end": 58477,
"score": 0.9970898628234863,
"start": 58467,
"tag": "NAME",
"value": "Viktor Hel"
},
{
"context": "l atacante recibe 1 ficha de Tensión.'''\n 'Lowhhrick':\n ship: \"Cañonera Auzituck\"\n ",
"end": 58699,
"score": 0.9346364736557007,
"start": 58690,
"tag": "NAME",
"value": "Lowhhrick"
},
{
"context": "l defensor añade 1 resultado %EVADE%.'''\n 'Wullffwarro':\n ship: \"Cañonera Auzituck\"\n ",
"end": 58939,
"score": 0.9460828900337219,
"start": 58928,
"tag": "NAME",
"value": "Wullffwarro"
},
{
"context": "año, tira 1 dado de ataque adicional.'''\n 'Wookiee Liberator':\n name: \"Libertador wookie\"\n ",
"end": 59164,
"score": 0.8423874974250793,
"start": 59147,
"tag": "NAME",
"value": "Wookiee Liberator"
},
{
"context": "'\n 'Wookiee Liberator':\n name: \"Libertador wookie\"\n ship: \"Cañonera Auzituck\"\n 'K",
"end": 59203,
"score": 0.9880589246749878,
"start": 59186,
"tag": "NAME",
"value": "Libertador wookie"
},
{
"context": "Kashyyyk Defender':\n name: \"Defensor de Kashyyyk\"\n ship: \"Cañonera Auzituck\"\n 'C",
"end": 59311,
"score": 0.7611202597618103,
"start": 59303,
"tag": "NAME",
"value": "Kashyyyk"
},
{
"context": " ship: \"Cañonera Auzituck\"\n 'Captain Nym (Scum)':\n name: \"Capitán Nym (Scum)\"\n ",
"end": 59371,
"score": 0.6438379287719727,
"start": 59364,
"tag": "NAME",
"value": "ain Nym"
},
{
"context": "\n 'Captain Nym (Scum)':\n name: \"Capitán Nym (Scum)\"\n ship: \"Bombardero Scurrg H-6\"",
"end": 59411,
"score": 0.9992895126342773,
"start": 59400,
"tag": "NAME",
"value": "Capitán Nym"
},
{
"context": " 'Captain Nym (Rebel)':\n name: \"Capitán Nym (Rebelde)\"\n ship: \"Bombardero Scurrg H",
"end": 59741,
"score": 0.9964293241500854,
"start": 59730,
"tag": "NAME",
"value": "Capitán Nym"
},
{
"context": "impedir que una bomba aliada detone.'''\n 'Lok Revenant':\n name: \"Aparecido de Lok\"\n ",
"end": 59903,
"score": 0.9203953742980957,
"start": 59892,
"tag": "NAME",
"value": "ok Revenant"
},
{
"context": "ne.'''\n 'Lok Revenant':\n name: \"Aparecido de Lok\"\n ship: \"Bombardero Scurrg H-6\"\n ",
"end": 59941,
"score": 0.9850631952285767,
"start": 59925,
"tag": "NAME",
"value": "Aparecido de Lok"
},
{
"context": " ship: \"Bombardero Scurrg H-6\"\n 'Karthakk Pirate':\n name: \"Pirata de Karthakk\"\n ",
"end": 60009,
"score": 0.889838695526123,
"start": 59995,
"tag": "NAME",
"value": "arthakk Pirate"
},
{
"context": "-6\"\n 'Karthakk Pirate':\n name: \"Pirata de Karthakk\"\n ship: \"Bombardero Scurrg H-6\"\n ",
"end": 60049,
"score": 0.989604115486145,
"start": 60031,
"tag": "NAME",
"value": "Pirata de Karthakk"
},
{
"context": " ship: \"Bombardero Scurrg H-6\"\n 'Sol Sixxa':\n ship: \"Bombardero Scurrg H-6\"\n ",
"end": 60111,
"score": 0.6199705600738525,
"start": 60106,
"tag": "NAME",
"value": "Sixxa"
},
{
"context": "ez de la plantilla de (%STRAIGHT% 1).'''\n 'Dalan Oberos':\n ship: 'Víbora Estelar'\n ",
"end": 60343,
"score": 0.964849591255188,
"start": 60331,
"tag": "NAME",
"value": "Dalan Oberos"
},
{
"context": "de maniobra revelada originalmente.'''\n 'Thweek':\n ship: 'Víbora Estelar'\n ",
"end": 60683,
"score": 0.5612231492996216,
"start": 60679,
"tag": "NAME",
"value": "week"
},
{
"context": "e Estado \"Vigilado\" o \"Imitado\".'''\n 'Black Sun Assassin':\n name: \"Asesino del Sol Negro\"\n ",
"end": 60930,
"score": 0.8601315021514893,
"start": 60918,
"tag": "NAME",
"value": "Sun Assassin"
},
{
"context": "\n 'Black Sun Assassin':\n name: \"Asesino del Sol Negro\"\n ship: 'Víbora Estelar'\n 'Capt",
"end": 60973,
"score": 0.9521386027336121,
"start": 60952,
"tag": "NAME",
"value": "Asesino del Sol Negro"
},
{
"context": "egro\"\n ship: 'Víbora Estelar'\n 'Captain Jostero':\n name: \"Capitán Jostero\"\n ",
"end": 61034,
"score": 0.8871749639511108,
"start": 61019,
"tag": "NAME",
"value": "Captain Jostero"
},
{
"context": "ar'\n 'Captain Jostero':\n name: \"Capitán Jostero\"\n ship: \"Caza Kihraxz\"\n tex",
"end": 61071,
"score": 0.999797523021698,
"start": 61056,
"tag": "NAME",
"value": "Capitán Jostero"
},
{
"context": "s efectuar un ataque contra esa nave.'''\n 'Major Vynder':\n ship: \"Ala Estelar clase Alfa\"\n ",
"end": 61323,
"score": 0.9906555414199829,
"start": 61311,
"tag": "NAME",
"value": "Major Vynder"
},
{
"context": "ship: \"Ala Estelar clase Alfa\"\n name: \"Mayor Vynder\"\n text: '''Cuando te defiendas, si tie",
"end": 61400,
"score": 0.9997516870498657,
"start": 61388,
"tag": "NAME",
"value": "Mayor Vynder"
},
{
"context": " ship: \"Ala Estelar clase Alfa\"\n 'Lieutenant Karsabi':\n ship: \"Ala Estelar clase Alfa\"\n ",
"end": 61796,
"score": 0.9998462796211243,
"start": 61778,
"tag": "NAME",
"value": "Lieutenant Karsabi"
},
{
"context": "ship: \"Ala Estelar clase Alfa\"\n name: \"Teniente Karsabi\"\n text: '''Cuando recibas una ficha de",
"end": 61877,
"score": 0.9998247027397156,
"start": 61861,
"tag": "NAME",
"value": "Teniente Karsabi"
},
{
"context": "etirar esa ficha de Armas bloqueadas.'''\n 'Cartel Brute':\n name: \"Secuaz del Cártel\"\n ",
"end": 62074,
"score": 0.9990772604942322,
"start": 62062,
"tag": "NAME",
"value": "Cartel Brute"
},
{
"context": "as.'''\n 'Cartel Brute':\n name: \"Secuaz del Cártel\"\n ship: \"Caza M12-L Kimogila\"\n ",
"end": 62113,
"score": 0.9992422461509705,
"start": 62096,
"tag": "NAME",
"value": "Secuaz del Cártel"
},
{
"context": "\n ship: \"Caza M12-L Kimogila\"\n 'Cartel Executioner':\n name: \"Verdugo del Cártel\"\n ",
"end": 62182,
"score": 0.9994287490844727,
"start": 62164,
"tag": "NAME",
"value": "Cartel Executioner"
},
{
"context": "\n 'Cartel Executioner':\n name: \"Verdugo del Cártel\"\n ship: \"Caza M12-L Kimogila\"\n ",
"end": 62222,
"score": 0.9996168613433838,
"start": 62204,
"tag": "NAME",
"value": "Verdugo del Cártel"
},
{
"context": "\n ship: \"Caza M12-L Kimogila\"\n 'Torani Kulda':\n ship: \"Caza M12-L Kimogila\"\n ",
"end": 62285,
"score": 0.9995383024215698,
"start": 62273,
"tag": "NAME",
"value": "Torani Kulda"
},
{
"context": "s fichas de Concrentración y Evasión.'''\n 'Dalan Oberos (Kimogila)':\n ship: \"Caza M12-L Kimogi",
"end": 62590,
"score": 0.9997100830078125,
"start": 62578,
"tag": "NAME",
"value": "Dalan Oberos"
},
{
"context": " dentro de tu arco de fuego centrado.'''\n 'Fenn Rau (Sheathipede)':\n ship: \"Lanzadera cl",
"end": 62837,
"score": 0.8030449748039246,
"start": 62831,
"tag": "NAME",
"value": "Fenn R"
},
{
"context": " 'Crimson Squadron Pilot':\n name: \"Piloto del Escuadrón Carmesí\"\n ship: \"Bombardero B/SF-17\"\n '",
"end": 64043,
"score": 0.9891765117645264,
"start": 64015,
"tag": "NAME",
"value": "Piloto del Escuadrón Carmesí"
},
{
"context": "\"\n '\"Crimson Leader\"':\n name: '\"Jefe Carmesí\"'\n ship: \"Bombardero B/SF-17\"\n ",
"end": 64144,
"score": 0.9998648762702942,
"start": 64132,
"tag": "NAME",
"value": "Jefe Carmesí"
},
{
"context": " '\"Crimson Specialist\"':\n name: '\"Especialista Carmesí\"'\n ship: \"Bombardero B/SF-17\"\n",
"end": 64437,
"score": 0.960577666759491,
"start": 64425,
"tag": "NAME",
"value": "Especialista"
},
{
"context": "son Specialist\"':\n name: '\"Especialista Carmesí\"'\n ship: \"Bombardero B/SF-17\"\n ",
"end": 64441,
"score": 0.8705369234085083,
"start": 64438,
"tag": "NAME",
"value": "Car"
},
{
"context": "Specialist\"':\n name: '\"Especialista Carmesí\"'\n ship: \"Bombardero B/SF-17\"\n ",
"end": 64445,
"score": 0.8746603727340698,
"start": 64441,
"tag": "NAME",
"value": "mesí"
},
{
"context": "''\n '\"Cobalt Leader\"':\n name: '\"Jefe Cobalto\"'\n ship: \"Bombardero B/SF-17\"\n ",
"end": 64759,
"score": 0.9998769760131836,
"start": 64747,
"tag": "NAME",
"value": "Jefe Cobalto"
},
{
"context": "efensa menos (hasta un mínimo de 0).'''\n 'Sienar-Jaemus Analyst':\n name: \"Analista de",
"end": 64982,
"score": 0.5536109805107117,
"start": 64979,
"tag": "NAME",
"value": "ien"
},
{
"context": " 'Sienar-Jaemus Analyst':\n name: \"Analista de Sienar-Jaemus\"\n ship: \"Silenciador TIE\"\n 'Fir",
"end": 65046,
"score": 0.9693393111228943,
"start": 65021,
"tag": "NAME",
"value": "Analista de Sienar-Jaemus"
},
{
"context": "den\"\n ship: \"Silenciador TIE\"\n 'Kylo Ren (TIE Silencer)':\n name: \"Kylo Ren (Sil",
"end": 65229,
"score": 0.9678857922554016,
"start": 65221,
"tag": "NAME",
"value": "Kylo Ren"
},
{
"context": " 'Kylo Ren (TIE Silencer)':\n name: \"Kylo Ren (Silenciador TIE)\"\n ship: \"Silenciador",
"end": 65274,
"score": 0.9993791580200195,
"start": 65266,
"tag": "NAME",
"value": "Kylo Ren"
},
{
"context": "e.'''\n 'Major Vermeil':\n name: \"Mayor Vermeil\"\n ship: \"Segador TIE\"\n text",
"end": 66247,
"score": 0.9998385310173035,
"start": 66234,
"tag": "NAME",
"value": "Mayor Vermeil"
},
{
"context": "e cara vacía por un resultado %HIT%.'''\n '\"Vizier\"':\n name: '\"Visir\"'\n text: ",
"end": 66499,
"score": 0.9906125068664551,
"start": 66493,
"tag": "NAME",
"value": "Vizier"
},
{
"context": "%HIT%.'''\n '\"Vizier\"':\n name: '\"Visir\"'\n text: '''Después de que una nave al",
"end": 66528,
"score": 0.9965200424194336,
"start": 66523,
"tag": "NAME",
"value": "Visir"
},
{
"context": "sión.'''\n ship: \"Segador TIE\"\n 'Captain Feroph':\n name: 'Capitán Feroph'\n ",
"end": 66828,
"score": 0.9993454813957214,
"start": 66814,
"tag": "NAME",
"value": "Captain Feroph"
},
{
"context": "TIE\"\n 'Captain Feroph':\n name: 'Capitán Feroph'\n ship: \"Segador TIE\"\n text",
"end": 66864,
"score": 0.9998834729194641,
"start": 66850,
"tag": "NAME",
"value": "Capitán Feroph"
},
{
"context": "'\n 'Scarif Base Pilot':\n name: \"Piloto de la base de Scarif\"\n ship: \"Segado",
"end": 67067,
"score": 0.7171323299407959,
"start": 67063,
"tag": "NAME",
"value": "Pilo"
},
{
"context": " Scarif\"\n ship: \"Segador TIE\"\n 'Leevan Tenza':\n ship: \"Ala-X\"\n text: '''",
"end": 67145,
"score": 0.994563102722168,
"start": 67133,
"tag": "NAME",
"value": "Leevan Tenza"
},
{
"context": "sión para recibir 1 ficha de Evasión.'''\n 'Saw Gerrera':\n ship: \"Ala-U\"\n text: '''",
"end": 67332,
"score": 0.9871511459350586,
"start": 67321,
"tag": "NAME",
"value": "Saw Gerrera"
},
{
"context": "'\n 'Benthic Two-Tubes':\n name: \"Benthic Dos Tubos\"\n ship: \"Ala-U\"\n text: '''D",
"end": 67633,
"score": 0.9933128952980042,
"start": 67616,
"tag": "NAME",
"value": "Benthic Dos Tubos"
},
{
"context": "nave aliada que tengas a alcance 1-2.'''\n 'Magva Yarro':\n ship: \"Ala-U\"\n text: '''",
"end": 67865,
"score": 0.9949738383293152,
"start": 67854,
"tag": "NAME",
"value": "Magva Yarro"
},
{
"context": "'''\n 'Edrio Two-Tubes':\n name: \"Edrio Dos Tubos\"\n ship: \"Ala-X\"\n text: '''C",
"end": 68102,
"score": 0.9975534081459045,
"start": 68087,
"tag": "NAME",
"value": "Edrio Dos Tubos"
},
{
"context": "an todos los resultados de los dados.\"\"\"\n \"Proton Torpedoes\":\n name: \"Torpedos de protones\"\n ",
"end": 68696,
"score": 0.7595391273498535,
"start": 68680,
"tag": "NAME",
"value": "Proton Torpedoes"
},
{
"context": "\"\"\n \"Proton Torpedoes\":\n name: \"Torpedos de protones\"\n text: \"\"\"<strong>Ataque (Blanco Fija",
"end": 68738,
"score": 0.9437611699104309,
"start": 68718,
"tag": "NAME",
"value": "Torpedos de protones"
},
{
"context": "yo.\"\"\"\n \"Squad Leader\":\n name: \"Jefe de Escuadrón\"\n text: \"\"\"<strong>Acción:</strong> El",
"end": 70750,
"score": 0.9994527697563171,
"start": 70733,
"tag": "NAME",
"value": "Jefe de Escuadrón"
},
{
"context": "\"\"\"\n \"Expert Handling\":\n name: \"Pericia\"\n text: \"\"\"<strong>Acción:</strong> Re",
"end": 71017,
"score": 0.9997028708457947,
"start": 71010,
"tag": "NAME",
"value": "Pericia"
},
{
"context": "ve.\"\"\"\n \"Marksmanship\":\n name: \"Puntería\"\n text: \"\"\"<strong>Acción:</strong> Cu",
"end": 71338,
"score": 0.9997650980949402,
"start": 71330,
"tag": "NAME",
"value": "Puntería"
},
{
"context": "e ataque <strong>dos veces</strong>.\"\"\"\n \"Daredevil\":\n name: \"Temerario\"\n text:",
"end": 72087,
"score": 0.683131217956543,
"start": 72079,
"tag": "NAME",
"value": "aredevil"
},
{
"context": "rong>.\"\"\"\n \"Daredevil\":\n name: \"Temerario\"\n text: \"\"\"<strong>Acción:</strong> Ej",
"end": 72118,
"score": 0.9996672868728638,
"start": 72109,
"tag": "NAME",
"value": "Temerario"
},
{
"context": "dos.\"\"\"\n \"Elusiveness\":\n name: \"Escurridizo\"\n text: \"\"\"Cuando te defiendas en comb",
"end": 72474,
"score": 0.9451717138290405,
"start": 72463,
"tag": "NAME",
"value": "Escurridizo"
},
{
"context": "\"\"\"\n \"Homing Missiles\":\n name: \"Misiles Rastreadores\"\n text: \"\"\"<strong>Ataque (Blanco Fija",
"end": 72783,
"score": 0.976020336151123,
"start": 72763,
"tag": "NAME",
"value": "Misiles Rastreadores"
},
{
"context": ".\"\"\"\n \"Push the Limit\":\n name: \"Máximo Esfuerzo\"\n text: \"\"\"Una vez por r",
"end": 73021,
"score": 0.5909854769706726,
"start": 73020,
"tag": "NAME",
"value": "M"
},
{
"context": "\"\"\n \"Push the Limit\":\n name: \"Máximo Esfuerzo\"\n text: \"\"\"Una vez por ronda, después ",
"end": 73035,
"score": 0.6519831418991089,
"start": 73022,
"tag": "NAME",
"value": "ximo Esfuerzo"
},
{
"context": "Tensión.\"\"\"\n \"Deadeye\":\n name: \"Certero\"\n text: \"\"\"%SMALLSHIPONLY%%LINEBREAK%P",
"end": 73298,
"score": 0.9949906468391418,
"start": 73291,
"tag": "NAME",
"value": "Certero"
},
{
"context": "su lugar.\"\"\"\n \"Expose\":\n name: \"Expuesto\"\n text: \"\"\"<strong>Acción:</strong> Ha",
"end": 73652,
"score": 0.5439679622650146,
"start": 73644,
"tag": "NAME",
"value": "Expuesto"
},
{
"context": "uce en 1.\"\"\"\n \"Gunner\":\n name: \"Artillero\"\n text: \"\"\"Después de que efectúes un ",
"end": 73861,
"score": 0.9986276626586914,
"start": 73852,
"tag": "NAME",
"value": "Artillero"
},
{
"context": "onda.\"\"\"\n \"Ion Cannon\":\n name: \"Cañón de Iones\"\n text: \"\"\"<strong>Ataque:</strong> At",
"end": 74118,
"score": 0.999869167804718,
"start": 74104,
"tag": "NAME",
"value": "Cañón de Iones"
},
{
"context": "\n \"Heavy Laser Cannon\":\n name: \"Cañón Láser Pesado\"\n text: \"\"\"<strong>Ataque:</strong> At",
"end": 74402,
"score": 0.9998705983161926,
"start": 74384,
"tag": "NAME",
"value": "Cañón Láser Pesado"
},
{
"context": " \"Mercenary Copilot\":\n name: \"Copiloto Mercenario\"\n text: \"\"\"Cuando ataques a",
"end": 74949,
"score": 0.530396580696106,
"start": 74947,
"tag": "NAME",
"value": "to"
},
{
"context": "\"Mercenary Copilot\":\n name: \"Copiloto Mercenario\"\n text: \"\"\"Cuando ataques a alcance 3,",
"end": 74960,
"score": 0.7287722826004028,
"start": 74951,
"tag": "NAME",
"value": "ercenario"
},
{
"context": "\"\"\n \"Assault Missiles\":\n name: \"Misiles de Asalto\"\n text: \"\"\"<strong>Ataque (Blanco Fija",
"end": 75144,
"score": 0.8849087357521057,
"start": 75127,
"tag": "NAME",
"value": "Misiles de Asalto"
},
{
"context": "ngún otro ataque en esta misma ronda.\"\"\"\n \"Nien Nunb\":\n text: \"\"\"Todas las maniobras %STRAI",
"end": 76943,
"score": 0.9961042404174805,
"start": 76934,
"tag": "NAME",
"value": "Nien Nunb"
},
{
"context": "u nave.\"\"\"\n \"Saboteur\":\n name: \"Saboteador\"\n text: \"\"\"<strong>Acción:</strong> El",
"end": 78486,
"score": 0.737126350402832,
"start": 78476,
"tag": "NAME",
"value": "Saboteador"
},
{
"context": "ve.\"\"\"\n \"Proton Bombs\":\n name: \"Bombas de Protones\"\n text: \"\"\"Cuando reveles tu selector ",
"end": 79037,
"score": 0.9506072998046875,
"start": 79019,
"tag": "NAME",
"value": "Bombas de Protones"
},
{
"context": "g> al final de la fase de Activación.\"\"\"\n \"Adrenaline Rush\":\n name: \"Descarga de Adrenalina\"\n ",
"end": 79300,
"score": 0.8148460388183594,
"start": 79285,
"tag": "NAME",
"value": "Adrenaline Rush"
},
{
"context": "\"\"\"\n \"Adrenaline Rush\":\n name: \"Descarga de Adrenalina\"\n text: \"\"\"Cuando reveles una maniobra",
"end": 79344,
"score": 0.9242815375328064,
"start": 79322,
"tag": "NAME",
"value": "Descarga de Adrenalina"
},
{
"context": "l dado cuyo resultado hayas cambiado.\"\"\"\n \"Darth Vader\":\n text: \"\"\"Después de que ataques a u",
"end": 80081,
"score": 0.6573373079299927,
"start": 80070,
"tag": "NAME",
"value": "Darth Vader"
},
{
"context": "o.\"\"\"\n \"Rebel Captive\":\n name: \"Prisionero Rebelde\"\n text: \"\"\"Una vez por ronda, la prime",
"end": 80281,
"score": 0.9995562434196472,
"start": 80263,
"tag": "NAME",
"value": "Prisionero Rebelde"
},
{
"context": "\"\n \"Flight Instructor\":\n name: \"Instructor de Vuelo\"\n text: \"\"\"Cuando te defiendas, puedes",
"end": 80493,
"score": 0.9920246005058289,
"start": 80474,
"tag": "NAME",
"value": "Instructor de Vuelo"
},
{
"context": "/strong> los resultados de los dados.\"\"\"\n \"Wingman\":\n name: \"Nave de Escolta\"\n ",
"end": 82543,
"score": 0.9995434880256653,
"start": 82536,
"tag": "NAME",
"value": "Wingman"
},
{
"context": "s dados.\"\"\"\n \"Wingman\":\n name: \"Nave de Escolta\"\n text: \"\"\"Al comienzo de la fase de C",
"end": 82580,
"score": 0.999835729598999,
"start": 82565,
"tag": "NAME",
"value": "Nave de Escolta"
},
{
"context": "a nave aliada que tengas a alcance 1.\"\"\"\n \"Decoy\":\n name: \"Señuelo\"\n text: \"",
"end": 82724,
"score": 0.998338520526886,
"start": 82719,
"tag": "NAME",
"value": "Decoy"
},
{
"context": "alcance 1.\"\"\"\n \"Decoy\":\n name: \"Señuelo\"\n text: \"\"\"Al comienzo de la fase de C",
"end": 82753,
"score": 0.9995452165603638,
"start": 82746,
"tag": "NAME",
"value": "Señuelo"
},
{
"context": "e esa nave hasta el final de la fase.\"\"\"\n \"Outmaneuver\":\n name: \"Superioridad Táctica\"\n ",
"end": 82989,
"score": 0.9963556528091431,
"start": 82978,
"tag": "NAME",
"value": "Outmaneuver"
},
{
"context": "ase.\"\"\"\n \"Outmaneuver\":\n name: \"Superioridad Táctica\"\n text: \"\"\"Cuando ataques a una nave s",
"end": 83031,
"score": 0.9960618615150452,
"start": 83011,
"tag": "NAME",
"value": "Superioridad Táctica"
},
{
"context": "e reduce en 1 (hasta un mínimo de 0).\"\"\"\n \"Predator\":\n name: \"Depredador\"\n text",
"end": 83240,
"score": 0.9908880591392517,
"start": 83232,
"tag": "NAME",
"value": "Predator"
},
{
"context": " de 0).\"\"\"\n \"Predator\":\n name: \"Depredador\"\n text: \"\"\"Cuando ataques, puedes volv",
"end": 83272,
"score": 0.9980461001396179,
"start": 83262,
"tag": "NAME",
"value": "Depredador"
},
{
"context": "lver a tirar hasta 2 dados de ataque.\"\"\"\n \"Flechette Torpedoes\":\n name: \"Torpedos de Fragmentación\"\n ",
"end": 83493,
"score": 0.9976300597190857,
"start": 83474,
"tag": "NAME",
"value": "Flechette Torpedoes"
},
{
"context": " \"Flechette Torpedoes\":\n name: \"Torpedos de Fragmentación\"\n text: \"\"\"<strong>Ataque (Blanco Fija",
"end": 83540,
"score": 0.9960034489631653,
"start": 83515,
"tag": "NAME",
"value": "Torpedos de Fragmentación"
},
{
"context": "sión si su Casco es de 4 o inferior.\"\"\"\n \"R7 Astromech\":\n name: \"Droide Astromecánico R7\"\n ",
"end": 83827,
"score": 0.9220386743545532,
"start": 83816,
"tag": "NAME",
"value": "7 Astromech"
},
{
"context": "or.\"\"\"\n \"R7 Astromech\":\n name: \"Droide Astromecánico R7\"\n text: \"\"\"Una vez por ronda cuando te",
"end": 83872,
"score": 0.9831224679946899,
"start": 83849,
"tag": "NAME",
"value": "Droide Astromecánico R7"
},
{
"context": "\n \"Quad Laser Cannons\":\n name: \"Cañones Láser Cuádruples\"\n text: \"\"\"<strong>Ataque (Energía):</",
"end": 85602,
"score": 0.9998210072517395,
"start": 85578,
"tag": "NAME",
"value": "Cañones Láser Cuádruples"
},
{
"context": " \"Tibanna Gas Supplies\":\n name: \"Suministro de Gas Tibanna\"\n text: \"\"\"<strong>Energía:</strong> P",
"end": 85894,
"score": 0.9782289266586304,
"start": 85869,
"tag": "NAME",
"value": "Suministro de Gas Tibanna"
},
{
"context": "ra 0 durante la fase de Activación.\"\"\"\n \"Chardaan Refit\":\n name: \"Reequipado en Chardaan",
"end": 87243,
"score": 0.5186542868614197,
"start": 87237,
"tag": "NAME",
"value": "ardaan"
},
{
"context": "nte la fase de Activación.\"\"\"\n \"Chardaan Refit\":\n name: \"Reequipado en Chardaan\"\n ",
"end": 87249,
"score": 0.6711158752441406,
"start": 87246,
"tag": "NAME",
"value": "fit"
},
{
"context": "\"\"\n \"Chardaan Refit\":\n name: \"Reequipado en Chardaan\"\n ship: \"Ala-A\"\n ",
"end": 87278,
"score": 0.6137104630470276,
"start": 87273,
"tag": "NAME",
"value": "equip"
},
{
"context": "ardaan Refit\":\n name: \"Reequipado en Chardaan\"\n ship: \"Ala-A\"\n text: \"\"\"<",
"end": 87293,
"score": 0.7532651424407959,
"start": 87287,
"tag": "NAME",
"value": "ardaan"
},
{
"context": ".\"\"\"\n \"Proton Rockets\":\n name: \"Cohetes de Protones\"\n text: \"\"\"<strong>Ataque (Concentraci",
"end": 87529,
"score": 0.7513909935951233,
"start": 87510,
"tag": "NAME",
"value": "Cohetes de Protones"
},
{
"context": "sta un máximo de 3 dados adicionales.\"\"\"\n \"Kyle Katarn\":\n text: \"\"\"Despues de que quites una ",
"end": 87794,
"score": 0.9995478391647339,
"start": 87783,
"tag": "NAME",
"value": "Kyle Katarn"
},
{
"context": "una ficha de Concentración a tu nave.\"\"\"\n \"Jan Ors\":\n text: \"\"\"Una vez por ronda, cuando ",
"end": 87946,
"score": 0.9995279312133789,
"start": 87939,
"tag": "NAME",
"value": "Jan Ors"
},
{
"context": "arle a esa nave una ficha de Evasión.\"\"\"\n \"Toryn Farr\":\n text: \"\"\"<strong>Acción:</strong> G",
"end": 88204,
"score": 0.9998003244400024,
"start": 88194,
"tag": "NAME",
"value": "Toryn Farr"
},
{
"context": "carta de Daño que tengas boca arriba.\"\"\"\n \"Carlist Rieekan\":\n name: \"Carlist Rieekan\"\n ",
"end": 89325,
"score": 0.9998883605003357,
"start": 89310,
"tag": "NAME",
"value": "Carlist Rieekan"
},
{
"context": "\"\"\"\n \"Carlist Rieekan\":\n name: \"Carlist Rieekan\"\n text: \"\"\"Al pincipio de la fase de A",
"end": 89362,
"score": 0.9998763203620911,
"start": 89347,
"tag": "NAME",
"value": "Carlist Rieekan"
},
{
"context": "nsidere 12 hasta el final de la fase.\"\"\"\n \"Jan Dodonna\":\n name: \"Jan Dodonna\"\n tex",
"end": 89558,
"score": 0.9998772740364075,
"start": 89547,
"tag": "NAME",
"value": "Jan Dodonna"
},
{
"context": "ase.\"\"\"\n \"Jan Dodonna\":\n name: \"Jan Dodonna\"\n text: \"\"\"Cuando otra nave aliada que",
"end": 89591,
"score": 0.9998742938041687,
"start": 89580,
"tag": "NAME",
"value": "Jan Dodonna"
},
{
"context": " elegida recibe una ficha de Tension.\"\"\"\n \"Han Solo\":\n name: \"Han Solo\"\n text: ",
"end": 90851,
"score": 0.9236180186271667,
"start": 90843,
"tag": "NAME",
"value": "Han Solo"
},
{
"context": "ension.\"\"\"\n \"Han Solo\":\n name: \"Han Solo\"\n text: \"\"\"Cuando ataques, si tienes l",
"end": 90881,
"score": 0.99648118019104,
"start": 90873,
"tag": "NAME",
"value": "Han Solo"
},
{
"context": "s de %FOCUS% por resultados de %HIT%.\"\"\"\n \"Leia Organa\":\n name: \"Leia Organa\"\n tex",
"end": 91096,
"score": 0.9679936170578003,
"start": 91085,
"tag": "NAME",
"value": "Leia Organa"
},
{
"context": "IT%.\"\"\"\n \"Leia Organa\":\n name: \"Leia Organa\"\n text: \"\"\"Al comienzo de la fase de A",
"end": 91129,
"score": 0.999588668346405,
"start": 91118,
"tag": "NAME",
"value": "Leia Organa"
},
{
"context": "bra blanca hasta el final de la fase.\"\"\"\n \"Raymus Antilles\":\n name: \"Raymus Antilles\"\n ",
"end": 91393,
"score": 0.9968764185905457,
"start": 91378,
"tag": "NAME",
"value": "Raymus Antilles"
},
{
"context": "\"\"\"\n \"Raymus Antilles\":\n name: \"Raymus Antilles\"\n text: \"\"\"Al comiuenzo de la fase de ",
"end": 91430,
"score": 0.9997979998588562,
"start": 91415,
"tag": "NAME",
"value": "Raymus Antilles"
},
{
"context": "ve.\"\"\"\n \"Gunnery Team\":\n name: \"Dotación de Artillería\"\n text: \"\"\"Una vez por ronda, cuando a",
"end": 91726,
"score": 0.9998602271080017,
"start": 91704,
"tag": "NAME",
"value": "Dotación de Artillería"
},
{
"context": "durante el paso de \"Obtener Energía\".\"\"\"\n \"Lando Calrissian\":\n name: \"Lando Calrissian\"\n ",
"end": 92351,
"score": 0.9990467429161072,
"start": 92335,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "\"\"\n \"Lando Calrissian\":\n name: \"Lando Calrissian\"\n text: \"\"\"<strong>Acción:</strong> Ti",
"end": 92389,
"score": 0.9998769760131836,
"start": 92373,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": " asigna 1 ficha de Evasión a tu nave.\"\"\"\n \"Mara Jade\":\n name: \"Mara Jade\"\n text:",
"end": 92634,
"score": 0.9982298612594604,
"start": 92625,
"tag": "NAME",
"value": "Mara Jade"
},
{
"context": " nave.\"\"\"\n \"Mara Jade\":\n name: \"Mara Jade\"\n text: \"\"\"Al final de la fase de Comb",
"end": 92665,
"score": 0.9998379349708557,
"start": 92656,
"tag": "NAME",
"value": "Mara Jade"
},
{
"context": "n.\"\"\"\n \"Fleet Officer\":\n name: \"Oficial de la Flota\"\n text: \"\"\"<strong>Acción:</strong> El",
"end": 92883,
"score": 0.864044725894928,
"start": 92864,
"tag": "NAME",
"value": "Oficial de la Flota"
},
{
"context": "s. Luego recibes 1 ficha de Tensión.\"\"\"\n \"Lone Wolf\":\n name: \"Lobo solitario\"\n ",
"end": 93096,
"score": 0.6565951704978943,
"start": 93093,
"tag": "NAME",
"value": "one"
},
{
"context": "nsión.\"\"\"\n \"Lone Wolf\":\n name: \"Lobo solitario\"\n text: \"\"\"Cuando ataques o defiendas,",
"end": 93137,
"score": 0.9969973564147949,
"start": 93123,
"tag": "NAME",
"value": "Lobo solitario"
},
{
"context": "es.\"\"\"\n \"Ruthlessness\":\n name: \"Crueldad\"\n text: \"\"\"Después de que efectúes un ",
"end": 93910,
"score": 0.9894253611564636,
"start": 93902,
"tag": "NAME",
"value": "Crueldad"
},
{
"context": "o la tuya). Esa nave sufre 1 daño.\"\"\"\n \"Intimidation\":\n name: \"Intimidación\"\n ",
"end": 94118,
"score": 0.6377012729644775,
"start": 94114,
"tag": "NAME",
"value": "imid"
},
{
"context": "ño.\"\"\"\n \"Intimidation\":\n name: \"Intimidación\"\n text: \"\"\"Mientras estes en contacto ",
"end": 94157,
"score": 0.9419722557067871,
"start": 94145,
"tag": "NAME",
"value": "Intimidación"
},
{
"context": " Agilidad de esa nave se reduce en 1.\"\"\"\n \"Ysanne Isard\":\n text: \"\"\"Al comienzo de la fase de ",
"end": 94293,
"score": 0.9997051954269409,
"start": 94281,
"tag": "NAME",
"value": "Ysanne Isard"
},
{
"context": "lizar una acción gratuita de Evasión.\"\"\"\n \"Moff Jerjerrod\":\n text: \"\"\"Cuando recibas una carta d",
"end": 94501,
"score": 0.9998248815536499,
"start": 94487,
"tag": "NAME",
"value": "Moff Jerjerrod"
},
{
"context": "o.\"\"\"\n \"Ion Torpedoes\":\n name: \"Torpedos de Iones\"\n text: \"\"\"<strong>Ataque (Blanco Fija",
"end": 94760,
"score": 0.8481863141059875,
"start": 94743,
"tag": "NAME",
"value": "Torpedos de Iones"
},
{
"context": ": \"Ala-Y\"\n \"Bodyguard\":\n name: \"Guardaespaldas\"\n text: \"\"\"%SCUMONLY%<br /><br />Al pr",
"end": 95298,
"score": 0.997922956943512,
"start": 95284,
"tag": "NAME",
"value": "Guardaespaldas"
},
{
"context": "\n \"Accuracy Corrector\":\n name: \"Corrector de Puntería\"\n text: \"\"\"Cuando ataques, durante el ",
"end": 95879,
"score": 0.9933309555053711,
"start": 95858,
"tag": "NAME",
"value": "Corrector de Puntería"
},
{
"context": "\n \"Inertial Dampeners\":\n name: \"Amortiguadores de Inercia\"\n text: \"\"\"Cuando reveles tu maniobra,",
"end": 96238,
"score": 0.9792652726173401,
"start": 96213,
"tag": "NAME",
"value": "Amortiguadores de Inercia"
},
{
"context": ". Después recibes 1 ficha de Tensión.\"\"\"\n \"Flechette Cannon\":\n name: \"Cañón de Fragmentación\"\n ",
"end": 96438,
"score": 0.813162088394165,
"start": 96422,
"tag": "NAME",
"value": "Flechette Cannon"
},
{
"context": "\"\"\n \"Flechette Cannon\":\n name: \"Cañón de Fragmentación\"\n text: \"\"\"<strong>Ataque:</strong> At",
"end": 96482,
"score": 0.966837465763092,
"start": 96460,
"tag": "NAME",
"value": "Cañón de Fragmentación"
},
{
"context": "strong> los resultados de los dados.\"\"\"\n '\"Mangler\" Cannon':\n name: 'Cañón \"Mutilador\"'\n ",
"end": 96783,
"score": 0.9924962520599365,
"start": 96776,
"tag": "NAME",
"value": "Mangler"
},
{
"context": "los resultados de los dados.\"\"\"\n '\"Mangler\" Cannon':\n name: 'Cañón \"Mutilador\"'\n ",
"end": 96791,
"score": 0.9356615543365479,
"start": 96785,
"tag": "NAME",
"value": "Cannon"
},
{
"context": "\n '\"Mangler\" Cannon':\n name: 'Cañón \"Mutilador\"'\n text: \"\"\"<strong>Ataque:",
"end": 96818,
"score": 0.7432714700698853,
"start": 96815,
"tag": "NAME",
"value": "ñón"
},
{
"context": " '\"Mangler\" Cannon':\n name: 'Cañón \"Mutilador\"'\n text: \"\"\"<strong>Ataque:</strong> A",
"end": 96829,
"score": 0.9902065396308899,
"start": 96820,
"tag": "NAME",
"value": "Mutilador"
},
{
"context": "\n '\"Hot Shot\" Blaster':\n name: \"Cañón Bláster Desechable\"\n text: \"\"\"<strong>Ataque:</strong> De",
"end": 97499,
"score": 0.8599494695663452,
"start": 97475,
"tag": "NAME",
"value": "Cañón Bláster Desechable"
},
{
"context": "iba.\"\"\"\n \"Outlaw Tech\":\n name: \"Técnico Clandestino\"\n text: \"\"\"%SCUMONLY%<br /><br />Despu",
"end": 97904,
"score": 0.9984912872314453,
"start": 97885,
"tag": "NAME",
"value": "Técnico Clandestino"
},
{
"context": "go descarta esta carta de Mejora.\"\"\"\n '\"Genius\"':\n name: '\"Genio\"'\n text: ",
"end": 98550,
"score": 0.7856799960136414,
"start": 98547,
"tag": "NAME",
"value": "ius"
},
{
"context": "ejora.\"\"\"\n '\"Genius\"':\n name: '\"Genio\"'\n text: \"\"\"Si estás equipado con una ",
"end": 98579,
"score": 0.7632629871368408,
"start": 98574,
"tag": "NAME",
"value": "Genio"
},
{
"context": "\n \"Ion Cannon Battery\":\n name: \"Batería de Cañones de Iones\"\n text: \"\"\"<strong>Ataque (Energía):</",
"end": 100258,
"score": 0.9998143315315247,
"start": 100231,
"tag": "NAME",
"value": "Batería de Cañones de Iones"
},
{
"context": "<strong> los resultados de los dados.\"\"\"\n \"Emperor Palpatine\":\n name: \"Emperador Palpatine\"\n ",
"end": 100561,
"score": 0.9982481002807617,
"start": 100544,
"tag": "NAME",
"value": "Emperor Palpatine"
},
{
"context": "\"\n \"Emperor Palpatine\":\n name: \"Emperador Palpatine\"\n text: \"\"\"%IMPERIALONLY%%LINEBREAK%Un",
"end": 100602,
"score": 0.9997958540916443,
"start": 100583,
"tag": "NAME",
"value": "Emperador Palpatine"
},
{
"context": "no podrá volver a ser modificado.\"\"\"\n \"Bossk\":\n text: \"\"\"%SCUMONLY%%LINEBREAK%Despu",
"end": 100922,
"score": 0.8467799425125122,
"start": 100921,
"tag": "NAME",
"value": "k"
},
{
"context": " nave y fija al defensor como blanco.\"\"\"\n \"Lightning Reflexes\":\n name: \"Reflejos Rápidos\"\n ",
"end": 101205,
"score": 0.8737949132919312,
"start": 101187,
"tag": "NAME",
"value": "Lightning Reflexes"
},
{
"context": "\n \"Lightning Reflexes\":\n name: \"Reflejos Rápidos\"\n text: \"\"\"%SMALLSHIPONLY%%LINEBREAK%D",
"end": 101243,
"score": 0.9989249110221863,
"start": 101227,
"tag": "NAME",
"value": "Reflejos Rápidos"
},
{
"context": "\"\n \"Twin Laser Turret\":\n name: \"Torreta Láser Doble\"\n text: \"\"\"<strong>Ataque:</strong> Ef",
"end": 101584,
"score": 0.9995899200439453,
"start": 101565,
"tag": "NAME",
"value": "Torreta Láser Doble"
},
{
"context": "\"\"\n \"Plasma Torpedoes\":\n name: \"Torpedos de Plasma\"\n text: \"\"\"<strong>Ataque (B",
"end": 101940,
"score": 0.6672317385673523,
"start": 101932,
"tag": "NAME",
"value": "Torpedos"
},
{
"context": "asma Torpedoes\":\n name: \"Torpedos de Plasma\"\n text: \"\"\"<strong>Ataque (Blanco fija",
"end": 101950,
"score": 0.6504330635070801,
"start": 101946,
"tag": "NAME",
"value": "asma"
},
{
"context": "ensor.\"\"\"\n \"Ion Bombs\":\n name: \"Bombas de Iones\"\n text: \"\"\"Cuando reveles tu selector ",
"end": 102252,
"score": 0.7246456146240234,
"start": 102237,
"tag": "NAME",
"value": "Bombas de Iones"
},
{
"context": "icha.\"\"\"\n \"Conner Net\":\n name: \"Red Conner\"\n text: \"\"\"<strong>Acción:</strong> De",
"end": 102731,
"score": 0.8193690180778503,
"start": 102721,
"tag": "NAME",
"value": "Red Conner"
},
{
"context": "ión\". Después se descarta esta ficha.\"\"\"\n \"Bombardier\":\n name: \"Bombardero\"\n text",
"end": 103239,
"score": 0.9676274061203003,
"start": 103229,
"tag": "NAME",
"value": "Bombardier"
},
{
"context": "icha.\"\"\"\n \"Bombardier\":\n name: \"Bombardero\"\n text: \"\"\"Cuando sueltes una bomba, p",
"end": 103271,
"score": 0.9976353645324707,
"start": 103261,
"tag": "NAME",
"value": "Bombardero"
},
{
"context": ").\"\"\"\n \"Cluster Mines\":\n name: \"Minas de Racimo\"\n text: \"\"\"<strong>Acción:</strong> De",
"end": 103463,
"score": 0.9978131651878357,
"start": 103448,
"tag": "NAME",
"value": "Minas de Racimo"
},
{
"context": "rada. Después se descarta esta ficha.\"\"\"\n 'Crack Shot':\n name: \"Tiro Certero\"\n ",
"end": 104012,
"score": 0.5683813691139221,
"start": 104010,
"tag": "NAME",
"value": "Cr"
},
{
"context": "icha.\"\"\"\n 'Crack Shot':\n name: \"Tiro Certero\"\n text: '''Cuando ataques a una nave s",
"end": 104054,
"score": 0.9995356202125549,
"start": 104042,
"tag": "NAME",
"value": "Tiro Certero"
},
{
"context": " \"Advanced Homing Missiles\":\n name: \"Misiles Rastreadores Avanzados\"\n text: \"\"\"<strong>Ataque (Blanco fija",
"end": 104349,
"score": 0.8448967933654785,
"start": 104319,
"tag": "NAME",
"value": "Misiles Rastreadores Avanzados"
},
{
"context": "> los resultados de los dados.\"\"\"\n 'Agent Kallus':\n name: \"Agente Kallus\"\n t",
"end": 104634,
"score": 0.8017556667327881,
"start": 104629,
"tag": "NAME",
"value": "allus"
},
{
"context": "os.\"\"\"\n 'Agent Kallus':\n name: \"Agente Kallus\"\n text: '''%IMPERIALONLY%%LINEBREAK%Al",
"end": 104669,
"score": 0.9985755681991577,
"start": 104656,
"tag": "NAME",
"value": "Agente Kallus"
},
{
"context": " 1 ficha de Concentración a esa nave.\"\"\"\n \"Captain Needa\":\n name: \"Capitán Needa\"\n t",
"end": 106550,
"score": 0.999844491481781,
"start": 106537,
"tag": "NAME",
"value": "Captain Needa"
},
{
"context": "e.\"\"\"\n \"Captain Needa\":\n name: \"Capitán Needa\"\n text: \"\"\"%HUGESHIPONLY%%IMPERIALONLY",
"end": 106585,
"score": 0.9998921155929565,
"start": 106572,
"tag": "NAME",
"value": "Capitán Needa"
},
{
"context": "cas %HIT% o %CRIT%, sufres 1 de daño.\"\"\"\n \"Admiral Ozzel\":\n name: \"Almirante Ozzel\"\n ",
"end": 106847,
"score": 0.9997773766517639,
"start": 106834,
"tag": "NAME",
"value": "Admiral Ozzel"
},
{
"context": "o.\"\"\"\n \"Admiral Ozzel\":\n name: \"Almirante Ozzel\"\n text: \"\"\"%HUGESHIPONLY%%IMPERIALONLY",
"end": 106884,
"score": 0.9998917579650879,
"start": 106869,
"tag": "NAME",
"value": "Almirante Ozzel"
},
{
"context": "os descartada, obtienes 1 de Energía.\"\"\"\n 'Glitterstim':\n name: \"Brillestim\"\n text",
"end": 107111,
"score": 0.9914557933807373,
"start": 107100,
"tag": "NAME",
"value": "Glitterstim"
},
{
"context": "gía.\"\"\"\n 'Glitterstim':\n name: \"Brillestim\"\n text: \"\"\"Al comienzo de la fase de C",
"end": 107143,
"score": 0.9979179501533508,
"start": 107133,
"tag": "NAME",
"value": "Brillestim"
},
{
"context": " 'Extra Munitions':\n name: \"Munición Adicional\"\n text: \"\"\"Cuando te equipas",
"end": 107460,
"score": 0.7792579531669617,
"start": 107457,
"tag": "NAME",
"value": "ión"
},
{
"context": " 'Extra Munitions':\n name: \"Munición Adicional\"\n text: \"\"\"Cuando te equipas con esta ",
"end": 107470,
"score": 0.6875139474868774,
"start": 107462,
"tag": "NAME",
"value": "dicional"
},
{
"context": " la ronda.\"\"\"\n \"Wired\":\n name: \"Enardecido\"\n text: \"\"\"Cuando ataques o te defiend",
"end": 108362,
"score": 0.7581605911254883,
"start": 108352,
"tag": "NAME",
"value": "Enardecido"
},
{
"context": "OCUS%.\"\"\"\n 'Cool Hand':\n name: \"Mano Firme\"\n text: '''Cuando recibas una ficha de",
"end": 108549,
"score": 0.9996576309204102,
"start": 108539,
"tag": "NAME",
"value": "Mano Firme"
},
{
"context": " a tu nave.'''\n 'Juke':\n name: \"Finta\"\n text: '''%SMALLSHIPONLY%%LINEBREAK%C",
"end": 108741,
"score": 0.9984121918678284,
"start": 108736,
"tag": "NAME",
"value": "Finta"
},
{
"context": "the %JAM% action icon.'''\n 'Rear Admiral Chiraneau':\n text: '''%HUGESHIPONLY% %IMPER",
"end": 109521,
"score": 0.8020790219306946,
"start": 109519,
"tag": "NAME",
"value": "ir"
},
{
"context": " activéis durante la fase de Combate.\"\"\"\n 'Kanan Jarrus':\n text: \"\"\"%REBELONLY%%LINEBREAK%Una ",
"end": 110380,
"score": 0.9052227139472961,
"start": 110368,
"tag": "NAME",
"value": "Kanan Jarrus"
},
{
"context": ").\"\"\"\n 'Dorsal Turret':\n name: \"Torreta Dorsal\"\n text: \"\"\"<strong>Ataque:</strong> At",
"end": 110949,
"score": 0.8409018516540527,
"start": 110935,
"tag": "NAME",
"value": "Torreta Dorsal"
},
{
"context": ", puedes fijar un blanco.'''\n 'Hera Syndulla':\n text: \"\"\"%REBELONLY%%LINEBREAK%Pued",
"end": 111357,
"score": 0.9406148195266724,
"start": 111356,
"tag": "NAME",
"value": "a"
},
{
"context": "as incluso aunque estés bajo tensión.\"\"\"\n 'Ezra Bridger':\n text: \"\"\"%REBELONLY%%LINEBREAK%Cuan",
"end": 111504,
"score": 0.9841778874397278,
"start": 111492,
"tag": "NAME",
"value": "Ezra Bridger"
},
{
"context": "ados %FOCUS% por un resultado %CRIT%.\"\"\"\n 'Sabine Wren':\n text: \"\"\"%REBELONLY%%LINEBREAK%Tu b",
"end": 111679,
"score": 0.9864650964736938,
"start": 111668,
"tag": "NAME",
"value": "Sabine Wren"
},
{
"context": "a ficha. Esa nave sufre 1 de daño.\"\"\"\n '\"Chopper\"':\n text: \"\"\"%REBELONLY%%LINEBREAK%Pue",
"end": 111932,
"score": 0.8603156805038452,
"start": 111927,
"tag": "NAME",
"value": "opper"
},
{
"context": " se puede gastar durante este ataque.\"\"\"\n \"Zuckuss\":\n text: \"\"\"%SCUMONLY%%LINEBREAK%Cuand",
"end": 113346,
"score": 0.9690642952919006,
"start": 113339,
"tag": "NAME",
"value": "Zuckuss"
},
{
"context": "ensor debe volver a tirar esos dados.\"\"\"\n 'Rage':\n name: \"Furia\"\n text: \"\"\"",
"end": 113596,
"score": 0.9987475872039795,
"start": 113592,
"tag": "NAME",
"value": "Rage"
},
{
"context": "esos dados.\"\"\"\n 'Rage':\n name: \"Furia\"\n text: \"\"\"<strong>Acción:</strong> As",
"end": 113623,
"score": 0.9998273849487305,
"start": 113618,
"tag": "NAME",
"value": "Furia"
},
{
"context": "lver a tirar hasta 3 dados de ataque.\"\"\"\n \"Attanni Mindlink\":\n name: \"Enlace Mental Attani\"\n ",
"end": 113861,
"score": 0.9997355937957764,
"start": 113845,
"tag": "NAME",
"value": "Attanni Mindlink"
},
{
"context": "\"\"\n \"Attanni Mindlink\":\n name: \"Enlace Mental Attani\"\n text: \"\"\"%SCUMONLY%%LINEBREAK%Cada v",
"end": 113903,
"score": 0.9970811009407043,
"start": 113883,
"tag": "NAME",
"value": "Enlace Mental Attani"
},
{
"context": "ismo tipo si es que no tienen ya una.\"\"\"\n \"Boba Fett\":\n text: \"\"\"%SCUMONLY%%LINEBREAK%Despu",
"end": 114188,
"score": 0.9998080730438232,
"start": 114179,
"tag": "NAME",
"value": "Boba Fett"
},
{
"context": "de las cartas de Mejora del defensor.\"\"\"\n \"Dengar\":\n text: \"\"\"%SCUMONLY%%LINEBREAK%Cuand",
"end": 114439,
"score": 0.9983137249946594,
"start": 114433,
"tag": "NAME",
"value": "Dengar"
},
{
"context": "ver a tirar hasta 2 dados de ataque.\"\"\"\n '\"Gonk\"':\n name: '\"Gonk\"'\n text: \"",
"end": 114653,
"score": 0.9810459017753601,
"start": 114649,
"tag": "NAME",
"value": "Gonk"
},
{
"context": " ataque.\"\"\"\n '\"Gonk\"':\n name: '\"Gonk\"'\n text: \"\"\"%SCUMONLY%%LINEBREAK%<stro",
"end": 114681,
"score": 0.991294801235199,
"start": 114677,
"tag": "NAME",
"value": "Gonk"
},
{
"context": "\n 'Thermal Detonators':\n name: \"Detonadores Térmicos\"\n text: \"\"\"Cuando rev",
"end": 115232,
"score": 0.5292549133300781,
"start": 115229,
"tag": "NAME",
"value": "Det"
},
{
"context": "ce 1. Esa nave puede fijar un blanco.'''\n 'Tail Gunner':\n name: \"Artillero de cola\"\n ",
"end": 116176,
"score": 0.9866971373558044,
"start": 116165,
"tag": "NAME",
"value": "Tail Gunner"
},
{
"context": "nco.'''\n 'Tail Gunner':\n name: \"Artillero de cola\"\n text: '''Cuando ataques desde tu arc",
"end": 116215,
"score": 0.9969442486763,
"start": 116198,
"tag": "NAME",
"value": "Artillero de cola"
},
{
"context": "E%.'''\n 'Fearlessness':\n name: \"Intrepidez\"\n text: '''%SCUMONLY%%LINEBREAK",
"end": 117280,
"score": 0.5456205010414124,
"start": 117277,
"tag": "NAME",
"value": "Int"
},
{
"context": " 'Fearlessness':\n name: \"Intrepidez\"\n text: '''%SCUMONLY%%LINEBREAK%Cuando",
"end": 117287,
"score": 0.5985714793205261,
"start": 117286,
"tag": "NAME",
"value": "z"
},
{
"context": "ave enemiga que tengas a alcance 1-3.'''\n 'Unkar Plutt':\n text: '''%SCUMONLY%%LINEBREAK%Despu",
"end": 119307,
"score": 0.9904929399490356,
"start": 119296,
"tag": "NAME",
"value": "Unkar Plutt"
},
{
"context": "tado %FOCUS% por un resultado %CRIT%.'''\n 'Jyn Erso':\n text: '''%REBELONLY%%LINEBREAK%<str",
"end": 119910,
"score": 0.9995675086975098,
"start": 119902,
"tag": "NAME",
"value": "Jyn Erso"
},
{
"context": "signar más de 3 fichas de esta forma.'''\n 'Cassian Andor':\n text: '''%REBELONLY%%LINEBREAK%Al f",
"end": 120219,
"score": 0.9998139142990112,
"start": 120206,
"tag": "NAME",
"value": "Cassian Andor"
},
{
"context": "ctor para asignarle otra maniobra.'''\n 'Finn':\n text: '''%REBELONLY%%LINEBREAK%Cuan",
"end": 120570,
"score": 0.8425591588020325,
"start": 120569,
"tag": "NAME",
"value": "n"
},
{
"context": "s a toda nave que tengas a alcance 1.'''\n 'Captain Rex':\n name: \"Capitán Rex\"\n tex",
"end": 122629,
"score": 0.909173846244812,
"start": 122618,
"tag": "NAME",
"value": "Captain Rex"
},
{
"context": "e 1.'''\n 'Captain Rex':\n name: \"Capitán Rex\"\n text: '''%REBELONLY%%LINEBREAK%Despu",
"end": 122662,
"score": 0.9988718032836914,
"start": 122651,
"tag": "NAME",
"value": "Capitán Rex"
},
{
"context": "e.'''\n 'Trick Shot':\n name: \"Disparo inverosímil\"\n text: '''Cuando ataques, si el ataqu",
"end": 124360,
"score": 0.6639096140861511,
"start": 124344,
"tag": "NAME",
"value": "paro inverosímil"
},
{
"context": " 'Hotshot Co-pilot':\n name: \"Copiloto extraordinario\"\n text: '''Cuando ataqu",
"end": 124535,
"score": 0.7042952179908752,
"start": 124530,
"tag": "NAME",
"value": "iloto"
},
{
"context": "ot Co-pilot':\n name: \"Copiloto extraordinario\"\n text: '''Cuando ataques con un armam",
"end": 124550,
"score": 0.5760537385940552,
"start": 124544,
"tag": "NAME",
"value": "inario"
},
{
"context": " '''Scavenger Crane''':\n name: \"Grúa de salvamento\"\n text: '''Después de qu",
"end": 124839,
"score": 0.6254739761352539,
"start": 124835,
"tag": "NAME",
"value": "Grúa"
},
{
"context": " '''Scavenger Crane''':\n name: \"Grúa de salvamento\"\n text: '''Después de que una nave que",
"end": 124853,
"score": 0.6523334980010986,
"start": 124843,
"tag": "NAME",
"value": "salvamento"
},
{
"context": "a, descarta tu \"Grúa de salvamento\".'''\n 'Bodhi Rook':\n text: '''%REBELONLY%%LINEBREAK%Cuan",
"end": 125206,
"score": 0.7972812056541443,
"start": 125197,
"tag": "NAME",
"value": "odhi Rook"
},
{
"context": "'\n 'Inspiring Recruit':\n name: \"Recluta inspirador\"\n text: '''Una vez por ronda, cuando u",
"end": 125713,
"score": 0.9915871620178223,
"start": 125695,
"tag": "NAME",
"value": "Recluta inspirador"
},
{
"context": "al.'''\n 'Swarm Leader':\n name: \"Jefe de enjambre\"\n text: '''Cuando ataques con un armam",
"end": 125941,
"score": 0.999756932258606,
"start": 125925,
"tag": "NAME",
"value": "Jefe de enjambre"
},
{
"context": "CRIT%.'''\n 'Expertise':\n name: \"Maestría\"\n text: '''Cuando ataques, si no estás",
"end": 126427,
"score": 0.99965500831604,
"start": 126419,
"tag": "NAME",
"value": "Maestría"
},
{
"context": "nave fuera de tu arco de fuego).'''\n 'Cikatro Vizago':\n text: '''%SCUMONLY%%LINEBREAK%Al co",
"end": 127293,
"score": 0.9967105388641357,
"start": 127284,
"tag": "NAME",
"value": "ro Vizago"
},
{
"context": "ormal.'''\n 'Intensity':\n name: \"Ímpetu\"\n text: '''%SMALLSHIPONLY% %DUALCARD%%",
"end": 129735,
"score": 0.7444214224815369,
"start": 129729,
"tag": "NAME",
"value": "Ímpetu"
},
{
"context": "n para darle la vuelta a esta carta.'''\n 'Jabba the Hutt':\n name: \"Jabba el Hutt\"\n ",
"end": 130169,
"score": 0.530441403388977,
"start": 130167,
"tag": "NAME",
"value": "ab"
},
{
"context": ".'''\n 'Jabba the Hutt':\n name: \"Jabba el Hutt\"\n text: '''%SCUMONLY%%LINEBREAK%Cuando",
"end": 130215,
"score": 0.8976089358329773,
"start": 130202,
"tag": "NAME",
"value": "Jabba el Hutt"
},
{
"context": "'\n 'Selflessness':\n name: \"Autosacrificio\"\n text: '''%SMALLSHIPONLY% %REBELONLY%",
"end": 130749,
"score": 0.7177249789237976,
"start": 130740,
"tag": "NAME",
"value": "acrificio"
},
{
"context": ".'''\n 'Ordnance Silos':\n name: \"Silos de munición\"\n ship: \"Bombardero B/SF-17\"\n ",
"end": 133876,
"score": 0.9994750618934631,
"start": 133859,
"tag": "NAME",
"value": "Silos de munición"
},
{
"context": ".'''\n 'Courier Droid':\n name: \"Droide mensajero\"\n text: '''Al comienzo del paso \"Despl",
"end": 136397,
"score": 0.8052986264228821,
"start": 136382,
"tag": "NAME",
"value": "roide mensajero"
},
{
"context": ".'''\n 'Threat Tracker':\n name: \"Rastreador de amenazas\"\n text: '''%SMALLSHIPONLY%%LINEBREAK%C",
"end": 138025,
"score": 0.6070987582206726,
"start": 138003,
"tag": "NAME",
"value": "Rastreador de amenazas"
},
{
"context": "ltados %FOCUS% por resultados %CRIT%.'''\n 'Director Krennic':\n text: '''Durante la prepara",
"end": 139922,
"score": 0.7866635322570801,
"start": 139914,
"tag": "NAME",
"value": "Director"
},
{
"context": "FOCUS% por resultados %CRIT%.'''\n 'Director Krennic':\n text: '''Durante la preparación de ",
"end": 139930,
"score": 0.9072412848472595,
"start": 139923,
"tag": "NAME",
"value": "Krennic"
},
{
"context": "alor de Escudos igual o inferior a 3.'''\n 'Magva Yarro':\n text: '''%REBELONLY%%LINEBREAK%Desp",
"end": 140183,
"score": 0.9987127184867859,
"start": 140172,
"tag": "NAME",
"value": "Magva Yarro"
},
{
"context": "''\n 'Thrust Corrector':\n name: \"Corrector de empuje\"\n text: '''Cuando te defiendas, si no ",
"end": 140757,
"score": 0.6608794331550598,
"start": 140738,
"tag": "NAME",
"value": "Corrector de empuje"
},
{
"context": "\n 'Servomotor S-Foils':\n name: \"Alas móviles\"\n text: '''<span class=\"card-restricti",
"end": 150422,
"score": 0.954804539680481,
"start": 150410,
"tag": "NAME",
"value": "Alas móviles"
},
{
"context": "\"\n \"Millennium Falcon\":\n name: \"Halcón Milenario\"\n text: \"\"\"<span class=\"card-restricti",
"end": 151800,
"score": 0.9998741149902344,
"start": 151784,
"tag": "NAME",
"value": "Halcón Milenario"
},
{
"context": "ra de acciones gana el icono %EVADE%.\"\"\"\n \"Moldy Crow\":\n name: \"Cuervo Oxidado\"\n ",
"end": 151952,
"score": 0.9364473223686218,
"start": 151942,
"tag": "NAME",
"value": "Moldy Crow"
},
{
"context": "ADE%.\"\"\"\n \"Moldy Crow\":\n name: \"Cuervo Oxidado\"\n text: \"\"\"<span class=\"card-restricti",
"end": 151988,
"score": 0.9998679757118225,
"start": 151974,
"tag": "NAME",
"value": "Cuervo Oxidado"
},
{
"context": "pilotos de Habilidad 4 o inferior.\"\"\"\n \"Dodonna's Pride\":\n name: \"Orgullo de Donna\"\n ",
"end": 152816,
"score": 0.6425632238388062,
"start": 152812,
"tag": "NAME",
"value": "onna"
},
{
"context": "\"\"\"\n \"Dodonna's Pride\":\n name: \"Orgullo de Donna\"\n text: \"\"\"<span class=\"card-restricti",
"end": 152862,
"score": 0.9998671412467957,
"start": 152846,
"tag": "NAME",
"value": "Orgullo de Donna"
},
{
"context": " \"Ala-A\"\n \"Tantive IV\":\n name: \"Tantive IV\"\n text: \"\"\"<span class=\"card-restricti",
"end": 153597,
"score": 0.921660304069519,
"start": 153587,
"tag": "NAME",
"value": "Tantive IV"
},
{
"context": " ship: \"Corbeta CR90 (Proa)\"\n \"Bright Hope\":\n name: \"Esperanza Brillante\"\n ",
"end": 153863,
"score": 0.5537048578262329,
"start": 153858,
"tag": "NAME",
"value": "right"
},
{
"context": "(Proa)\"\n \"Bright Hope\":\n name: \"Esperanza Brillante\"\n text: \"\"\"<span class=\"card-restricti",
"end": 153909,
"score": 0.919032871723175,
"start": 153890,
"tag": "NAME",
"value": "Esperanza Brillante"
},
{
"context": "R-75'\n \"Quantum Storm\":\n name: \"Tormenta Cuántica\"\n text: \"\"\"<span class=\"card-restricti",
"end": 154197,
"score": 0.9542049765586853,
"start": 154180,
"tag": "NAME",
"value": "Tormenta Cuántica"
},
{
"context": "ano GR-75'\n \"Dutyfree\":\n name: \"Libre de Impuestos\"\n text: \"\"\"<span class=\"card-restricti",
"end": 154481,
"score": 0.9387040734291077,
"start": 154463,
"tag": "NAME",
"value": "Libre de Impuestos"
},
{
"context": "R-75'\n \"Jaina's Light\":\n name: \"Luz de Jaina\"\n text: \"\"\"<span class=\"card-restricti",
"end": 154783,
"score": 0.940041720867157,
"start": 154771,
"tag": "NAME",
"value": "Luz de Jaina"
},
{
"context": "arriba.\"\"\"\n \"Outrider\":\n name: \"Jinete del Espacio\"\n text: \"\"\"<span class=\"card-restricti",
"end": 155087,
"score": 0.9872523546218872,
"start": 155069,
"tag": "NAME",
"value": "Jinete del Espacio"
},
{
"context": " fuego.\"\"\"\n \"Andrasta\":\n name: \"Andrasta\"\n text: \"\"\"<span class=\"card-restricti",
"end": 155441,
"score": 0.9894562363624573,
"start": 155433,
"tag": "NAME",
"value": "Andrasta"
},
{
"context": "en 4 (hasta un mínimo de 0).\"\"\"\n \"BTL-A4 Y-Wing\":\n name: \"BTL-A4 Ala-Y\"\n te",
"end": 155917,
"score": 0.6736727356910706,
"start": 155913,
"tag": "NAME",
"value": "Wing"
},
{
"context": ").\"\"\"\n \"BTL-A4 Y-Wing\":\n name: \"BTL-A4 Ala-Y\"\n text: \"\"\"<span class=\"card-restricti",
"end": 155951,
"score": 0.9728149771690369,
"start": 155939,
"tag": "NAME",
"value": "BTL-A4 Ala-Y"
},
{
"context": "p: \"Agresor\"\n \"Virago\":\n name: \"Virago\"\n text: \"\"\"<span class=\"card-restricti",
"end": 156628,
"score": 0.9963361620903015,
"start": 156622,
"tag": "NAME",
"value": "Virago"
},
{
"context": "tor M3-A'\n \"Dauntless\":\n name: \"Intrépido\"\n text: \"\"\"<span class=\"card-restricti",
"end": 157904,
"score": 0.8649431467056274,
"start": 157895,
"tag": "NAME",
"value": "Intrépido"
},
{
"context": "49 Diezmador'\n \"Ghost\":\n name: \"Espíritu\"\n text: \"\"\"<span class=\"card-restricti",
"end": 158216,
"score": 0.9997251033782959,
"start": 158208,
"tag": "NAME",
"value": "Espíritu"
},
{
"context": "u peana.\"\"\"\n \"Phantom\":\n name: \"Fantasma\"\n text: \"\"\"Mientras estás acoplado, el",
"end": 158592,
"score": 0.9996568560600281,
"start": 158584,
"tag": "NAME",
"value": "Fantasma"
},
{
"context": " ship: 'Prototipo de TIE Avanzado'\n \"Mist Hunter\":\n name: \"Cazador de la Niebla\"\n ",
"end": 159212,
"score": 0.9979347586631775,
"start": 159201,
"tag": "NAME",
"value": "Mist Hunter"
},
{
"context": "anzado'\n \"Mist Hunter\":\n name: \"Cazador de la Niebla\"\n text: \"\"\"<span class=\"card-restricti",
"end": 159254,
"score": 0.9998525977134705,
"start": 159234,
"tag": "NAME",
"value": "Cazador de la Niebla"
},
{
"context": "G-1A'\n \"Punishing One\":\n name: \"Castigadora\"\n text: \"\"\"<span class=\"card-restricti",
"end": 159640,
"score": 0.9997711777687073,
"start": 159629,
"tag": "NAME",
"value": "Castigadora"
},
{
"context": " ship: 'Saltador Maestro 5000'\n \"Hound's Tooth\":\n name: \"Diente de Perro\"",
"end": 159846,
"score": 0.5984580516815186,
"start": 159845,
"tag": "NAME",
"value": "H"
},
{
"context": "5000'\n \"Hound's Tooth\":\n name: \"Diente de Perro\"\n text: \"\"\"<span class=\"card-restricti",
"end": 159895,
"score": 0.9992122650146484,
"start": 159880,
"tag": "NAME",
"value": "Diente de Perro"
},
{
"context": "an> no puede atacar en esta ronda.\"\"\"\n \"Assailer\":\n name: \"Acometedor\"\n text",
"end": 160231,
"score": 0.5419741272926331,
"start": 160226,
"tag": "NAME",
"value": "ailer"
},
{
"context": " ronda.\"\"\"\n \"Assailer\":\n name: \"Acometedor\"\n text: \"\"\"<span class=\"card-restricti",
"end": 160263,
"score": 0.9886232614517212,
"start": 160253,
"tag": "NAME",
"value": "Acometedor"
},
{
"context": "ADE%.\"\"\"\n \"Instigator\":\n name: \"Instigador\"\n text: \"\"\"<span class=\"card-restricti",
"end": 160589,
"score": 0.9595492482185364,
"start": 160579,
"tag": "NAME",
"value": "Instigador"
},
{
"context": "ional.\"\"\"\n \"Impetuous\":\n name: \"Impetuoso\"\n text: \"\"\"<span class=\"card-restricti",
"end": 160868,
"score": 0.9420689940452576,
"start": 160859,
"tag": "NAME",
"value": "Impetuoso"
},
{
"context": "or TIE'\n 'TIE Shuttle':\n name: \"Lanzadera TIE\"\n text: '''<span class=\"card-restricti",
"end": 161859,
"score": 0.9863530993461609,
"start": 161846,
"tag": "NAME",
"value": "Lanzadera TIE"
},
{
"context": " ship.'''\n 'Black One':\n name: \"Negro Uno\"\n text: '''Después de que realices una",
"end": 162752,
"score": 0.9982293248176575,
"start": 162743,
"tag": "NAME",
"value": "Negro Uno"
},
{
"context": " 'Millennium Falcon (TFA)':\n name: \"Halcón Milenario (TFA)\"\n text: '''Después de que ejecut",
"end": 163113,
"score": 0.9998983144760132,
"start": 163097,
"tag": "NAME",
"value": "Halcón Milenario"
},
{
"context": "%.'''\n 'Shadow Caster':\n name: \"Sombra Alargada\"\n ship: \"Nave de persecución clase Lan",
"end": 164649,
"score": 0.9791808128356934,
"start": 164634,
"tag": "NAME",
"value": "Sombra Alargada"
},
{
"context": "\n ship: \"Caza TIE\"\n name: \"Obra maestra de Sabine\"\n text: '''<span class=",
"end": 165088,
"score": 0.7862123250961304,
"start": 165082,
"tag": "NAME",
"value": "bra ma"
},
{
"context": " ship: \"Caza TIE\"\n name: \"Obra maestra de Sabine\"\n text: '''<span class=\"card-restricti",
"end": 165103,
"score": 0.782685399055481,
"start": 165091,
"tag": "NAME",
"value": "ra de Sabine"
},
{
"context": "gana los iconos %CREW% y %ILLICIT%.'''\n '''Kylo Ren's Shuttle''':\n ship: \"Lanzadera clase Íp",
"end": 165280,
"score": 0.9242830276489258,
"start": 165270,
"tag": "NAME",
"value": "Kylo Ren's"
},
{
"context": "hip: \"Lanzadera clase Ípsilon\"\n name: \"Lanzadera de Kylo Ren\"\n text: '''<span class=\"card-",
"end": 165368,
"score": 0.9743380546569824,
"start": 165356,
"tag": "NAME",
"value": "Lanzadera de"
},
{
"context": "era clase Ípsilon\"\n name: \"Lanzadera de Kylo Ren\"\n text: '''<span class=\"card-restricti",
"end": 165377,
"score": 0.9770758152008057,
"start": 165369,
"tag": "NAME",
"value": "Kylo Ren"
},
{
"context": ".'''\n '''Pivot Wing''':\n name: \"Ala pivotante\"\n ship: \"Ala-U\"\n text: '''<",
"end": 165795,
"score": 0.9919382333755493,
"start": 165782,
"tag": "NAME",
"value": "Ala pivotante"
},
{
"context": " '''Adaptive Ailerons''':\n name: \"Alerones adaptativos\"\n ship: \"Fustigador TIE\"\n t",
"end": 166368,
"score": 0.9616318941116333,
"start": 166348,
"tag": "NAME",
"value": "Alerones adaptativos"
},
{
"context": "OC\n '''Merchant One''':\n name: \"Mercader Uno\"\n ship: \"Crucero C-ROC\" \n t",
"end": 166742,
"score": 0.9993769526481628,
"start": 166730,
"tag": "NAME",
"value": "Mercader Uno"
},
{
"context": "\" Interceptor''':\n name: 'Interceptor \"Scyk Ligero\"'\n ship: \"Interceptor M3-A\"\n ",
"end": 167057,
"score": 0.9270485043525696,
"start": 167046,
"tag": "NAME",
"value": "Scyk Ligero"
},
{
"context": " '''Insatiable Worrt''':\n name: \"Worrt insaciable\"\n ship: \"Crucero C-ROC\" \n ",
"end": 167479,
"score": 0.9922411441802979,
"start": 167463,
"tag": "NAME",
"value": "Worrt insaciable"
},
{
"context": "'''\n '''Broken Horn''':\n name: \"Cuerno Roto\"\n ship: \"Crucero C-ROC\"\n te",
"end": 167679,
"score": 0.9998244047164917,
"start": 167668,
"tag": "NAME",
"value": "Cuerno Roto"
},
{
"context": "derte, descarta tu ficha de Refuerzo.'''\n 'Havoc':\n name: \"Estrago\"\n ship: \"",
"end": 167923,
"score": 0.7785760760307312,
"start": 167918,
"tag": "NAME",
"value": "Havoc"
},
{
"context": " Refuerzo.'''\n 'Havoc':\n name: \"Estrago\"\n ship: \"Bombardero Scurrg H-6\"\n ",
"end": 167952,
"score": 0.9984674453735352,
"start": 167945,
"tag": "NAME",
"value": "Estrago"
},
{
"context": "''\n 'StarViper Mk. II':\n name: \"Víbora Estelar modelo II\"\n ship: \"Víbora Estelar\"\n t",
"end": 168675,
"score": 0.7920681834220886,
"start": 168651,
"tag": "NAME",
"value": "Víbora Estelar modelo II"
},
{
"context": "ueadas.'''\n 'Enforcer':\n name: \"Brazo Ejecutor\"\n ship: \"Caza M12-L Kimogila\"\n ",
"end": 169558,
"score": 0.9970476031303406,
"start": 169544,
"tag": "NAME",
"value": "Brazo Ejecutor"
},
{
"context": "\n 'Ghost (Phantom II)':\n name: \"Espíritu (Fantasma II)\"\n text: '''<span class=\"ca",
"end": 169876,
"score": 0.9066015481948853,
"start": 169868,
"tag": "NAME",
"value": "Espíritu"
},
{
"context": "Ghost (Phantom II)':\n name: \"Espíritu (Fantasma II)\"\n text: '''<span class=\"card-restrict",
"end": 169889,
"score": 0.8753908276557922,
"start": 169878,
"tag": "NAME",
"value": "Fantasma II"
},
{
"context": "eana.'''\n 'Phantom II':\n name: \"Fantasma II\"\n ship: \"Lanzadera clase Sheathipede\"\n",
"end": 170297,
"score": 0.997672438621521,
"start": 170286,
"tag": "NAME",
"value": "Fantasma II"
},
{
"context": " 'First Order Vanguard':\n name: \"Vanguardia de la Primera Orden\"\n ship: \"Silenciador TIE\"\n ",
"end": 170724,
"score": 0.963799774646759,
"start": 170694,
"tag": "NAME",
"value": "Vanguardia de la Primera Orden"
},
{
"context": "\n 'Fanatical Devotion':\n name: \"Lealtad Fanática\"\n text: '''Cuando te defiendas, no pud",
"end": 173530,
"score": 0.9916524887084961,
"start": 173514,
"tag": "NAME",
"value": "Lealtad Fanática"
},
{
"context": "%CRIT%.'''\n 'Shadowed':\n name: \"Vigilado\" \n text: '''Se considera que \"Thweek\" ",
"end": 174278,
"score": 0.9937386512756348,
"start": 174270,
"tag": "NAME",
"value": "Vigilado"
},
{
"context": "truido.'''\n 'Mimicked':\n name: \"Imitado\"\n text: '''Se considera que \"Thweek\" t",
"end": 174594,
"score": 0.9949716925621033,
"start": 174587,
"tag": "NAME",
"value": "Imitado"
},
{
"context": "uido.'''\n 'Harpooned!':\n name: \"¡Arponeado!\"\n text: '''Cuando seas impac",
"end": 174915,
"score": 0.7666375041007996,
"start": 174915,
"tag": "NAME",
"value": ""
},
{
"context": "ido.'''\n 'Harpooned!':\n name: \"¡Arponeado!\"\n text: '''Cuando seas impactado por un",
"end": 174925,
"score": 0.9183187484741211,
"start": 174916,
"tag": "NAME",
"value": "Arponeado"
},
{
"context": "de daño.'''\n 'Rattled':\n name: \"Estremecido\"\n text: '''Cuando sufras daño normal o",
"end": 175431,
"score": 0.9901547431945801,
"start": 175420,
"tag": "NAME",
"value": "Estremecido"
},
{
"context": "cance 1-2 y esté equipada con la carta de Mejora \"Director Krennic\" puede fijar como blanco al defensor.'''\n\n exp",
"end": 176464,
"score": 0.840740978717804,
"start": 176448,
"tag": "NAME",
"value": "Director Krennic"
}
] | coffeescripts/cards-es.coffee | idavidka/xwing | 100 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.es = 'Español'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations['Español'] =
action:
"Barrel Roll": "Tonel Volado"
"Boost": "Impulso"
"Evade": "Evadir"
"Focus": "Concentración"
"Target Lock": "Blanco Fijado"
"Recover": "Recuperar"
"Reinforce": "Reforzar"
"Jam": "Interferir"
"Coordinate": "Coordinar"
"Cloak": "Camuflaje"
slot:
"Astromech": "Droide Astromech"
"Bomb": "Bomba"
"Cannon": "Cañón"
"Crew": "Tripulación"
"Elite": "Élite"
"Missile": "Misiles"
"System": "Sistemas"
"Torpedo": "Torpedos"
"Turret": "Torreta"
"Cargo": "Carga"
"Hardpoint": "Hardpoint"
"Team": "Equipo"
"Illicit": "Ilícita"
"Salvaged Astromech": "Droide Astromech Remendado"
"Tech": "Tecnología"
sources: # needed?
"Core": "Caja Básica"
"A-Wing Expansion Pack": "Pack de Expansión Ala-A"
"B-Wing Expansion Pack": "Pack de Expansión Ala-B"
"X-Wing Expansion Pack": "Pack de Expansión Ala-X"
"Y-Wing Expansion Pack": "Pack de Expansión Ala-Y"
"Millennium Falcon Expansion Pack": "Pack de Expansión Halcón Milenario"
"HWK-290 Expansion Pack": "Pack de Expansión HWK-290"
"TIE Fighter Expansion Pack": "Pack de Expansión Caza TIE"
"TIE Interceptor Expansion Pack": "Pack de Expansión Interceptor TIE"
"TIE Bomber Expansion Pack": "Pack de Expansión Bombardero TIE"
"TIE Advanced Expansion Pack": "Pack de Expansión TIE Avanzado"
"Lambda-Class Shuttle Expansion Pack": "Pack de Expansión Lanzadera clase LAmbda"
"Slave I Expansion Pack": "Pack de Expansión Esclavo 1"
"Imperial Aces Expansion Pack": "Pack de Expansión Ases Imperiales"
"Rebel Transport Expansion Pack": "Pack de Expansión Transporte Rebelde"
"Z-95 Headhunter Expansion Pack": "Pack de Expansión Z-95 Cazacabezas"
"TIE Defender Expansion Pack": "Pack de Expansión Defensor TIE"
"E-Wing Expansion Pack": "Pack de Expansión Ala-E"
"TIE Phantom Expansion Pack": "Pack de Expansión TIE Fantasma"
"Tantive IV Expansion Pack": "Pack de Expansión Tantive IV"
"Rebel Aces Expansion Pack": "Pack de Expansión Ases Rebeldes"
"YT-2400 Freighter Expansion Pack": "Pack de Expansión Carguero YT-2400"
"VT-49 Decimator Expansion Pack": "Pack de Expansión VT-49 Diezmador"
"StarViper Expansion Pack": "Pack de Expansión Víbora Estelar"
"M3-A Interceptor Expansion Pack": "Pack de Expansión Interceptor M3-A"
"IG-2000 Expansion Pack": "Pack de Expansión IG-2000"
"Most Wanted Expansion Pack": "Pack de Expansión Los Más Buscados"
"Imperial Raider Expansion Pack": "Pack de Expansión Incursor Imperial"
"K-Wing Expansion Pack": "Pack de Expansión Ala-K"
"TIE Punisher Expansion Pack": "Pack de Expansión Castigador TIE"
"Kihraxz Fighter Expansion Pack": "Pack de Expansión Caza Kihraxz"
"Hound's Tooth Expansion Pack": "Pack de Expansión Diente de Perro"
"The Force Awakens Core Set": "Caja Básica El Despertar de la Fuerza"
"T-70 X-Wing Expansion Pack": "Pack de Expansión T-70 Ala-X"
"TIE/fo Fighter Expansion Pack": "Pack de Expansión Caza TIE/fo"
"Imperial Assault Carrier Expansion Pack": "Pack de Expansión Portacazas de Asalto Imperial"
"Ghost Expansion Pack": "Pack de Expansión Espíritu"
"Inquisitor's TIE Expansion Pack": "Pack de Expansión TIE del Inquisidor"
"Mist Hunter Expansion Pack": "Pack de Expansión Cazador de la Niebla"
"Punishing One Expansion Pack": "Pack de Expansión Castigadora"
"Imperial Veterans Expansion Pack": "Pack de Expansión Veteranos Imperiales"
"Protectorate Starfighter Expansion Pack": "Pack de Expansión Caza estelar del Protectorado"
"Shadow Caster Expansion Pack": "Pack de Expansión Sombra Alargada"
"Special Forces TIE Expansion Pack": "Pack de Expansión TIE de las Fuerzas Especiales"
"ARC-170 Expansion Pack": "Pack de Expansión ARC-170"
"U-Wing Expansion Pack": "Pack de Expansión Ala-U"
"TIE Striker Expansion Pack": "Pack de Expansión Fustigador TIE"
"Upsilon-class Shuttle Expansion Pack": "Pack de Expansión Lanzadera clase Ípsilon"
"Sabine's TIE Fighter Expansion Pack": "Pack de Expansión Caza TIE de Sabine"
"Quadjumper Expansion Pack": "Pack de Expansión Saltador Quad"
"C-ROC Cruiser Expansion Pack": "Pack de Expansión Crucero C-ROC"
"TIE Aggressor Expansion Pack": "Pack de Expansión Tie Agresor"
"Scurrg H-6 Bomber Expansion Pack": "Pack de Expansión Bombardero Scurrg H-6"
"Auzituck Gunship Expansion Pack": "Pack de Expansión Cañonera Auzituck"
"TIE Silencer Expansion Pack": "Pack de Expansión Silenciador TIE"
"Alpha-class Star Wing Expansion Pack": "Pack de Expansión Ala Estelar clase Alfa"
"Resistance Bomber Expansion Pack": "Pack de Expansión Bombardero de la Resistencia"
"Phantom II Expansion Pack": "Pack de Expansión Fantasma II"
"Kimogila Fighter Expansion Pack": "Pack de Expansión Caza M12-L Kimogila"
"Saw's Renegades Expansion Pack": "Pack de Expansión Renegados de Saw"
"TIE Reaper Expansion Pack": "Pack de Expansión Segador TIE"
ui:
shipSelectorPlaceholder: "Selecciona una nave"
pilotSelectorPlaceholder: "Selecciona un piloto"
upgradePlaceholder: (translator, language, slot) ->
switch slot
when 'Elite'
"Sin Talento de Élite"
when 'Astromech'
"Sin Droide Astromecánico"
when 'Illicit'
"Sin Mejora Ilícita"
when 'Salvaged Astromech'
"Sin Droide Astromech Remendado"
else
"Sin Mejora de #{translator language, 'slot', slot}"
modificationPlaceholder: "Sin Modificación"
titlePlaceholder: "Sin Título"
upgradeHeader: (translator, language, slot) ->
switch slot
when 'Elite'
"Talento de Élite"
when 'Astromech'
"Droide Astromecánico"
when 'Illicit'
"Mejora Ilícita"
when 'Salvaged Astromech'
"Droide Astromech Remendado"
else
"Mejora de #{translator language, 'slot', slot}"
unreleased: "inédito"
epic: "épico"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'This squad uses unreleased content!'
'.epic-content-used .translated': 'This squad uses Epic content!'
'.illegal-epic-too-many-small-ships .translated': 'You may not field more than 12 of the same type Small ship!'
'.illegal-epic-too-many-large-ships .translated': 'You may not field more than 6 of the same type Large ship!'
'.collection-invalid .translated': 'You cannot field this list with your collection!'
# Type selector
'.game-type-selector option[value="standard"]': 'Standard'
'.game-type-selector option[value="custom"]': 'Custom'
'.game-type-selector option[value="epic"]': 'Epic'
'.game-type-selector option[value="team-epic"]': 'Team Epic'
'.xwing-card-browser .translate.sort-cards-by': 'Ordenar cartas por'
'.xwing-card-browser option[value="name"]': 'Nombre'
'.xwing-card-browser option[value="source"]': 'Fuente'
'.xwing-card-browser option[value="type-by-points"]': 'Tipo (por Puntos)'
'.xwing-card-browser option[value="type-by-name"]': 'Tipo (por Nombre)'
'.xwing-card-browser .translate.select-a-card': 'Selecciona una carta del listado de la izquierda.'
# Info well
'.info-well .info-ship td.info-header': 'Nave'
'.info-well .info-skill td.info-header': 'Habilidad'
'.info-well .info-actions td.info-header': 'Acciones'
'.info-well .info-upgrades td.info-header': 'Mejoras'
'.info-well .info-range td.info-header': 'Alcance'
# Squadron edit buttons
'.clear-squad' : 'Nuevo Escuadron'
'.save-list' : 'Grabar'
'.save-list-as' : 'Grabar como...'
'.delete-list' : 'Eliminar'
'.backend-list-my-squads' : 'Cargar Escuadron'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Imprimir/Ver como </span>Text'
'.randomize' : 'Aleatorio!'
'.randomize-options' : 'Opciones de aleatoriedad…'
'.notes-container > span' : 'Squad Notes'
# Print/View modal
'.bbcode-list' : 'Copia el BBCode de debajo y pegalo en el post de tu foro.<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.vertical-space-checkbox' : """Añade espacio para cartas de daño/mejora cuando imprima. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Imprima en color. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="fa fa-print"></i> Imprimir'
# Randomizer options
'.do-randomize' : 'Genera Aleatoriamente!'
# Top tab bar
'#empireTab' : 'Imperio Galactico'
'#rebelTab' : 'Alianza Rebelde'
'#scumTab' : 'Escoria y Villanos'
'#browserTab' : 'Explorador de Cartas'
'#aboutTab' : 'Acerca de'
singular:
'pilots': 'Piloto'
'modifications': 'Modificación'
'titles': 'Título'
types:
'Pilot': 'Piloto'
'Modification': 'Modificación'
'Title': 'Título'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders['Español'] = () ->
exportObj.cardLanguage = 'Español'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# ship translations
exportObj.renameShip 'Lambda-Class Shuttle', 'Lanzadera clase Lambda'
exportObj.renameShip 'TIE Advanced', 'TIE Avanzado'
exportObj.renameShip 'TIE Bomber', 'Bombardero TIE'
exportObj.renameShip 'TIE Fighter', 'Caza TIE'
exportObj.renameShip 'TIE Interceptor', 'Interceptor TIE'
exportObj.renameShip 'TIE Phantom', 'TIE Fantasma'
exportObj.renameShip 'TIE Defender', 'Defensor TIE'
exportObj.renameShip 'TIE Punisher', 'Castigador TIE'
exportObj.renameShip 'TIE Advanced Prototype', 'Prototipo de TIE Avanzado'
exportObj.renameShip 'VT-49 Decimator', 'VT-49 Diezmador'
exportObj.renameShip 'TIE/fo Fighter', 'Caza TIE/fo'
exportObj.renameShip 'TIE/sf Fighter', 'Caza TIE/sf'
exportObj.renameShip 'TIE Striker', 'Fustigador TIE'
exportObj.renameShip 'Upsilon-class Shuttle', 'Lanzadera clase Ípsilon'
exportObj.renameShip 'TIE Aggressor', 'TIE Agresor'
exportObj.renameShip 'TIE Silencer', 'Silenciador TIE'
exportObj.renameShip 'Alpha-class Star Wing', 'Ala Estelar clase Alfa'
exportObj.renameShip 'TIE Reaper', 'Segador TIE'
exportObj.renameShip 'A-Wing', 'Ala-A'
exportObj.renameShip 'B-Wing', 'Ala-B'
exportObj.renameShip 'E-Wing', 'Ala-E'
exportObj.renameShip 'X-Wing', 'Ala-X'
exportObj.renameShip 'Y-Wing', 'Ala-Y'
exportObj.renameShip 'K-Wing', 'Ala-K'
exportObj.renameShip 'Z-95 Headhunter', 'Z-95 Cazacabezas'
exportObj.renameShip 'Attack Shuttle', 'Lanzadera de Ataque'
exportObj.renameShip 'CR90 Corvette (Aft)', 'Corbeta CR90 (Popa)'
exportObj.renameShip 'CR90 Corvette (Fore)', 'Corbeta CR90 (Proa)'
exportObj.renameShip 'GR-75 Medium Transport', 'Transporte mediano GR-75'
exportObj.renameShip 'T-70 X-Wing', 'T-70 Ala-X'
exportObj.renameShip 'U-Wing', 'Ala-U'
exportObj.renameShip 'Auzituck Gunship', 'Cañonera Auzituck'
exportObj.renameShip 'B/SF-17 Bomber', 'Bombardero B/SF-17'
exportObj.renameShip 'Sheathipede-class Shuttle', 'Lanzadera clase Sheathipede'
exportObj.renameShip 'M3-A Interceptor', 'Interceptor M3-A'
exportObj.renameShip 'StarViper', 'Víbora Estelar'
exportObj.renameShip 'Aggressor', 'Agresor'
exportObj.renameShip 'Kihraxz Fighter', 'Caza Kihraxz'
exportObj.renameShip 'G-1A Starfighter', 'Caza Estelar G-1A'
exportObj.renameShip 'JumpMaster 5000', 'Saltador Maestro 5000'
exportObj.renameShip 'Protectorate Starfighter', 'Caza Estelar del Protectorado'
exportObj.renameShip 'Lancer-class Pursuit Craft', 'Nave de persecución clase Lancero'
exportObj.renameShip 'Quadjumper', 'Saltador Quad'
exportObj.renameShip 'C-ROC Cruiser', 'Crucero C-ROC'
exportObj.renameShip 'Scurrg H-6 Bomber', 'Bombardero Scurrg H-6'
exportObj.renameShip 'M12-L Kimogila Fighter', 'Caza M12-L Kimogila'
pilot_translations =
"Wedge Antilles":
text: """Cuando ataques, la Agilidad del piloto se reduce en 1 (hasta un mínimo de 0)."""
ship: "Ala-X"
"Garven Dreis":
text: """Después de gastar una ficha de Concentración, en vez de descartarla puedes asignar esa ficha a cualquier otra nave aliada que tengas a alcance 1-2."""
ship: "Ala-X"
"Red Squadron Pilot":
name: "Piloto del escuadrón Rojo"
ship: "Ala-X"
"Rookie Pilot":
name: "Piloto Novato"
ship: "Ala-X"
"Biggs Darklighter":
text: """Las demás naves aliadas que tengas a alcance 1 no pueden ser seleccionadas como objetivo de ataques si en vez de eso el atacante pudiese seleccionarte a tí como objetivo."""
ship: "Ala-X"
"Luke Skywalker":
text: """Cuando te defiendas en combate puedes cambiar 1 de tus resultados %FOCUS% por un resultado %EVADE%."""
ship: "Ala-X"
"Gray Squadron Pilot":
name: "Piloto del escuadrón Gris"
ship: "Ala-Y"
'"Dutch" Vander':
text: """Después de que fijes un blanco, elige otra nave aliada que tengas a alcance 1-2. La nave elegida podrá fijar un blanco inmediatamente."""
ship: "Ala-Y"
"Horton Salm":
text: """Cuando ataques a alcance 2-3, puedes volver a lanzar cualesquier dados en los que hayas sacado caras vacías."""
ship: "Ala-Y"
"Gold Squadron Pilot":
name: "Piloto del escuadrón Oro"
ship: "Ala-Y"
"Academy Pilot":
name: "Piloto de la Academia"
ship: "Caza TIE"
"Obsidian Squadron Pilot":
name: "Piloto del escuadrón Obsidiana"
ship: "Caza TIE"
"Black Squadron Pilot":
name: "Piloto del escuadrón Negro"
ship: "Caza TIE"
'"Winged Gundark"':
name: '"Gundark Alado"'
text: """Cuando ataques a alcance 1, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%"""
ship: "Caza TIE"
'"Night Beast"':
name: '"Bestia Nocturna"'
text: """Después de que ejecutes una maniobra verde, puedes realizar una acción gratuita de Concentración"""
ship: "Caza TIE"
'"Backstabber"':
name: '"Asesino Furtivo"'
text: """Cuando ataques desde fuera del arco de fuego del defensor, tira 1 dado de ataque adicional."""
ship: "Caza TIE"
'"Dark Curse"':
name: '"Maldición Oscura"'
text: """Cuando te defiendas en combate, las naves que te ataquen no podrán gastar fichas de Concentración ni volver a tirar dados de ataque."""
ship: "Caza TIE"
'"Mauler Mithel"':
name: '"Mutilador Mithel"'
text: """Si atacas a alcance 1, tira 1 dado de ataque adicional."""
ship: "Caza TIE"
'"Howlrunner"':
name: '"Aullador Veloz"'
text: """Cuando otra nave aliada que tengas a alcance 1 ataque con su armamento principal, podrá volver a tirar 1 dado de ataque."""
ship: "Caza TIE"
"Tempest Squadron Pilot":
name: "Piloto del escuadrón Tempestad"
ship: "TIE Avanzado"
"Storm Squadron Pilot":
name: "Piloto del escuadrón Tormenta"
ship: "TIE Avanzado"
"Maarek Stele":
text: """Cuando tu ataque inflija una carta de Daño boca arriba al defensor, en vez de eso roba 3 cartas de Daño, elige 1 de ellas a tu elección y luego descarta las otras."""
ship: "TIE Avanzado"
"Darth Vader":
text: """Puedes llevar a cabo dos acciones durante tu paso de acción."""
ship: "TIE Avanzado"
"Alpha Squadron Pilot":
name: "Piloto del escuadrón Alfa"
ship: "Interceptor TIE"
"Avenger Squadron Pilot":
name: "Piloto del escuadrón Vengador"
ship: "Interceptor TIE"
"Saber Squadron Pilot":
name: "Piloto del escuadrón Sable"
ship: "Interceptor TIE"
"\"Fel's Wrath\"":
name: '"Ira de Fel"'
ship: "Interceptor TIE"
text: """Cuando tengas asignadas tantas cartas de Daño como tu Casco o más, no serás destruido hasta el final de la fase de Combate."""
"Turr Phennir":
ship: "Interceptor TIE"
text: """Después de que efectúes un ataque, puedes llevar a cabo una acción gratuita de impulso o tonel volado."""
"Soontir Fel":
ship: "Interceptor TIE"
text: """Cuando recibas una ficha de Tensión, puedes asignar 1 ficha de Concentración a tu nave."""
"Tycho Celchu":
text: """Puedes realizar acciones incluso aunque tengas fichas de Tensión."""
ship: "Ala-A"
"Arvel Crynyd":
text: """Puedes designar como objetivo de tu ataque a una nave enemiga que esté dentro de tu arco de ataque y en contacto contigo."""
ship: "Ala-A"
"Green Squadron Pilot":
name: "Piloto del escuadrón Verde"
ship: "Ala-A"
"Prototype Pilot":
name: "Piloto de pruebas"
ship: "Ala-A"
"Outer Rim Smuggler":
name: "Contrabandista del Borde Exterior"
"Chewbacca":
text: """Cuando recibas una carta de Daño boca arriba, ponla boca abajo inmediatamente sin resolver su texto de reglas."""
"Lando Calrissian":
text: """Después de que ejecutes una maniobra verde, elige otra nave aliada que tengas a alcance 1. Esa nave podrá realizar una acción gratuita de las indicadas en su barra de acciones."""
"Han Solo":
text: """Cuando ataques, puedes volver a tirar todos tus dados. Si decides hacerlo, debes volver a tirar tantos como te sea posible."""
"Bounty Hunter":
name: "Cazarrecompensas"
"Kath Scarlet":
text: """Cuando ataques, el defensor recibe 1 ficha de Tensión si anula al menos 1 resultado %CRIT%."""
"Boba Fett":
text: """Cuando realices una maniobra de inclinación (%BANKLEFT% o %BANKRIGHT%), puedes girar tu selector de maniobras para escoger la otra maniobra de inclinación de la misma velocidad."""
"Krassis Trelix":
text: """Cuando ataques con un armamento secundario, puedes volver a tirar 1 dado de ataque."""
"Ten Numb":
text: """Cuando atacas, 1 de tus resultados %CRIT% no puede ser anulado por los dados de defensa."""
ship: "Ala-B"
"Ibtisam":
text: """Cuando atacas o te defiendes, si tienes al menos 1 ficha de Tensión, puedes volver a tirar 1 de tus dados."""
ship: "Ala-B"
"Dagger Squadron Pilot":
name: "Piloto del escuadrón Daga"
ship: "Ala-B"
"Blue Squadron Pilot":
name: "Piloto del escuadrón Azul"
ship: "Ala-B"
"Rebel Operative":
name: "Agente Rebelde"
ship: "HWK-290"
"Roark Garnet":
text: """Al comienzo de la fase de Combate, elige otra nave aliada que tengas a alcance 1-3. Hasta el final de la fase, se considera que el piloto de esa nave tiene habilidad 12."""
ship: "HWK-290"
"Kyle Katarn":
text: """Al comienzo de la fase de Combate, puedes asignar 1 de tus fichas de Concentración a otra nave aliada que tengas a alcance 1-3."""
ship: "HWK-290"
"Jan Ors":
text: """Cuando otra nave aliada que tengas a alcance 1-3 efectúe un ataque, si no tienes fichas de Tensión puedes recibir 1 ficha de Tensión para que esa nave tire 1 dado de ataque adicional."""
ship: "HWK-290"
"Scimitar Squadron Pilot":
name: "Piloto del escuadrón Cimitarra"
ship: "Bombardero TIE"
"Gamma Squadron Pilot":
name: "Piloto del escuadrón Gamma"
ship: "Bombardero TIE"
"Gamma Squadron Veteran":
name: "Veterano del escuadrón Gamma"
ship: "Bombardero TIE"
"Captain Jonus":
name: "Capitán Jonus"
ship: "Bombardero TIE"
text: """Cuando otra nave aliada que tengas a alcance 1 ataque con un sistema de armamento secundario, puede volver a tirar un máximo de 2 dados de ataque."""
"Major Rhymer":
name: "Comandante Rhymer"
ship: "Bombardero TIE"
text: """Cuando atacas con un sistema de armamento secundario, puedes incrementar o reducir en 1 el alcance del arma (hasta un límite de alcance comprendido entre 1 y 3)."""
"Omicron Group Pilot":
name: "Piloto del grupo Ómicron"
ship: "Lanzadera clase Lambda"
"Captain Kagi":
name: "Capitán Kagi"
text: """Cuando una nave enemiga fije un blanco, deberá fijar tu nave como blanco (si es posible)."""
ship: "Lanzadera clase Lambda"
"Colonel Jendon":
name: "Coronel Jendon"
text: """Al comienzo de la fase de Combate, puedes asignar 1 de tus fichas azules de Blanco Fijado a una nave aliada que tengas a alcance 1 si no tiene ya una ficha azul de Blanco Fijado."""
ship: "Lanzadera clase Lambda"
"Captain Yorr":
name: "Capitán Yorr"
text: """Cuando otra nave aliada que tengas a alcance 1-2 vaya a recibir una ficha de Tensión, si tienes 2 fichas de Tensión o menos puedes recibirla tú en su lugar."""
ship: "Lanzadera clase Lambda"
"Lieutenant Lorrir":
ship: "Interceptor TIE"
text: """Cuando realices una acción de tonel volado, puedes recibir 1 ficha de Tensión para utilizar la plantilla (%BANKLEFT% 1) o la de (%BANKRIGHT% 1) en vez de la plantilla de (%STRAIGHT% 1)."""
"Royal Guard Pilot":
name: "Piloto de la Guardia Real"
ship: "Interceptor TIE"
"Tetran Cowall":
ship: "Interceptor TIE"
text: """Cuando reveles una maniobra %UTURN%, puedes ejecutarla como si su velocidad fuese de 1, 3 ó 5."""
"Kir Kanos":
ship: "Interceptor TIE"
text: """Cuando ataques desde alcance 2-3, puedes gastar 1 ficha de Evasión para añadir 1 resultado %HIT% a tu tirada."""
"Carnor Jax":
ship: "Interceptor TIE"
text: """Las naves enemigas que tengas a alcance 1 no pueden realizar acciones de Concentración o Evasión, y tampoco pueden gastar fichas de Concentración ni de Evasión."""
"GR-75 Medium Transport":
name: "Transporte mediano GR-75"
ship: "Transporte mediano GR-75"
"Bandit Squadron Pilot":
name: "Piloto del escuadrón Bandido"
ship: "Z-95 Cazacabezas"
"Tala Squadron Pilot":
name: "Piloto del escuadrón Tala"
ship: "Z-95 Cazacabezas"
"Lieutenant Blount":
name: "Teniente Blount"
text: """Cuando ataques, el defensor es alcanzado por tu ataque, incluso aunque no sufra ningún daño."""
ship: "Z-95 Cazacabezas"
"Airen Cracken":
name: "Airen Cracken"
text: """Después de que realices un ataque, puedes elegir otra nave aliada a alcance 1. Esa nave puede llevar a cabo 1 acción gratuita."""
ship: "Z-95 Cazacabezas"
"Delta Squadron Pilot":
name: "Piloto del escuadrón Delta"
ship: "Defensor TIE"
"Onyx Squadron Pilot":
name: "Piloto del escuadrón Ónice"
ship: "Defensor TIE"
"Colonel Vessery":
name: "Coronel Vessery"
text: """Cuando ataques, inmediatamente después de tirar los dados de ataque puedes fijar al defensor como blanco si éste ya tiene asignada una ficha de Blanco Fijado."""
ship: "Defensor TIE"
"Rexler Brath":
text: """Después de que efectúes un ataque que inflinja al menos 1 carta de Daño al defensor, puedes gastar 1 ficha de Concentración para poner esas cartas boca arriba."""
ship: "Defensor TIE"
"Knave Squadron Pilot":
name: "Piloto del escuadrón Canalla"
ship: "Ala-E"
"Blackmoon Squadron Pilot":
name: "Piloto del escuadrón Luna Negra"
ship: "Ala-E"
"Etahn A'baht":
text: """Cuando una nave neemiga situada dentro de tu arco de fuego a alcance 1-3 se defienda, el atacante puede cambiar 1 de sus resultados %HIT% por 1 resultado %CRIT%."""
ship: "Ala-E"
"Corran Horn":
text: """Puedes efectuar 1 ataque al comienzo de la fase Final, pero si lo haces no podrás atacar en la ronda siguiente."""
ship: "Ala-E"
"Sigma Squadron Pilot":
name: "Piloto del escuadrón Sigma"
ship: "TIE Fantasma"
"Shadow Squadron Pilot":
name: "Piloto del escuadrón Sombra"
ship: "TIE Fantasma"
'"Echo"':
name: '"Eco"'
text: """Cuando desactives tu camuflaje, debes usar la plantilla de maniobra (%BANKLEFT% 2) o la de (%BANKRIGHT% 2) en lugar de la plantilla (%STRAIGHT% 2)."""
ship: "TIE Fantasma"
'"Whisper"':
name: '"Susurro"'
text: """Después de que efectúes un ataque que impacte, puedes asignar una ficha de Concentración a tu nave."""
ship: "TIE Fantasma"
"CR90 Corvette (Fore)":
name: "Corbeta CR90 (Proa)"
ship: "Corbeta CR90 (Proa)"
text: """Cuando ataques con tu armamento principal, puedes gastar 1 de Energía para tirar 1 dado de ataque adicional."""
"CR90 Corvette (Aft)":
name: "Corbeta CR90 (Popa)"
ship: "Corbeta CR90 (Popa)"
"Wes Janson":
text: """Después de que efectúes un ataque, puedes eliminar 1 ficha de Concentración, Evasión o Blanco Fijado (azul) del defensor."""
ship: "Ala-X"
"Jek Porkins":
text: """Cuando recibas una ficha de Tensión, puedes descartarla y tirar 1 dado de ataque. Si sacas %HIT%, esta nave recibe 1 carta de Daño boca abajo."""
ship: "Ala-X"
'"Hobbie" Klivian':
text: """Cuando fijes un blanco o gastes una ficha de Blanco Fijado, puedes quitar 1 ficha de Tensión de tu nave."""
ship: "Ala-X"
"Tarn Mison":
text: """Cuando una nave enemiga te declare como objetivo de un ataque, puedes fijar esa nave como blanco."""
ship: "Ala-X"
"Jake Farrell":
text: """Después de que realices una acción de Concentración o te asignen una ficha de Concentración, puedes efectuar una acción gratuita de impulso o tonel volado."""
ship: "Ala-A"
"Gemmer Sojan":
text: """Mientras te encuentres a alcance 1 de al menos 1 nave enemiga, tu Agilidad aumenta en 1."""
ship: "Ala-A"
"Keyan Farlander":
text: """Cuando ataques, puedes quitarte 1 ficha de Tensión para cambiar todos tus resultados %FOCUS% por %HIT%."""
ship: "Ala-B"
"Nera Dantels":
text: """Puedes efectuar ataques con armamentos secundarios %TORPEDO% contra naves enemigas fuera de tu arco de fuego."""
ship: "Ala-B"
# "CR90 Corvette (Crippled Aft)":
# name: "CR90 Corvette (Crippled Aft)"
# ship: "Corbeta CR90 (Popa)"
# text: """No puedes seleccionar ni ejecutar maniobras (%STRAIGHT% 4), (%BANKLEFT% 2), o (%BANKRIGHT% 2)."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90 Corvette (Crippled Fore)"
# ship: "Corbeta CR90 (Proa)"
"Wild Space Fringer":
name: "Fronterizo del Espacio Salvaje"
ship: "YT-2400"
"Dash Rendar":
text: """Puedes ignorar obstáculos durante la fase de Activación y al realizar acciones."""
'"Leebo"':
text: """Cuando recibas una carta de Daño boca arriba, roba 1 carta de Daño adicional, resuelve 1 de ellas a tu elección y descarta la otra."""
"Eaden Vrill":
text: """Si efectúas un ataque con un armamento principal contra una nave que tenga fichas de Tensión, tiras 1 dado de ataque adicional."""
"Patrol Leader":
name: "Jefe de Patrulla"
ship: "VT-49 Diezmador"
"Rear Admiral Chiraneau":
name: "Contralmirante Chiraneau"
text: """Cuando atacas a alcance 1-2, puedes cambiar 1 de tus resultados de %FOCUS% por un resultado %CRIT%."""
ship: "VT-49 Diezmador"
"Commander Kenkirk":
ship: "VT-49 Diezmador"
name: "Comandante Kenkirk"
text: """Si no te quedan escudos y tienes asignada al menos 1 carta de Daño, tu Agilidad aumenta en 1."""
"Captain Oicunn":
name: "Capitán Oicunn"
text: """Después de ejecutar un maniobra, toda nave enemiga con la que estés en contacto sufre 1 daño."""
ship: "VT-49 Diezmador"
"Black Sun Enforcer":
name: "Ejecutor del Sol Negro"
ship: "Víbora Estelar"
"Black Sun Vigo":
name: "Vigo del Sol Negro"
ship: "Víbora Estelar"
"Prince Xizor":
name: "Príncipe Xizor"
text: """Cuando te defiendas, una nave aliada que tengas a alcance 1 puede sufrir en tu lugar 1 resultado %HIT% o %CRIT% no anulado."""
ship: "Víbora Estelar"
"Guri":
text: """Al comienzo de la fase de Combate, si tienes alguna nave enemiga a alcance 1 puedes asignar 1 ficha de Concentración a tu nave."""
ship: "Víbora Estelar"
"Cartel Spacer":
name: "Agente del Cártel"
ship: "Interceptor M3-A"
"Tansarii Point Veteran":
name: "Veterano de Punto Tansarii"
ship: "Interceptor M3-A"
"Serissu":
text: """Cuando otra nave aliada situada a alcance 1 se defienda, puede volver a tirar 1 dado de defensa."""
ship: "Interceptor M3-A"
"Laetin A'shera":
text: """Después de que te hayas defendido de un ataque, si el ataque no impactó, puedes asignar 1 ficha de Evasión a tu nave."""
ship: "Interceptor M3-A"
"IG-88A":
text: """Después de que efectúes un ataque que destruya al defensor, puedes recuperar 1 ficha de Escudos."""
ship: "Agresor"
"IG-88B":
text: """Una vez por ronda, después de que efectúes un ataque y lo falles, puedes efectuar un ataque con un sistema de armamento secundario %CANNON% que tengas equipado."""
ship: "Agresor"
"IG-88C":
text: """Después de que realices una acción de impulso, puedes llevar a cabo una acción gratuita de Evasión."""
ship: "Agresor"
"IG-88D":
text: """Puedes ejecutar la maniobra (%SLOOPLEFT% 3) o (%SLOOPRIGHT% 3) utilizando la plantilla (%TURNLEFT% 3) o (%TURNRIGHT% 3) correspondiente."""
ship: "Agresor"
"Mandalorian Mercenary":
name: "Mercenario Mandaloriano"
"Boba Fett (Scum)":
text: """Cuando ataques o te defiendas, puedes volver a tirar 1 de tus dados por cada nave enemiga que tengas a alcance 1."""
"Kath Scarlet (Scum)":
text: """Cuando ataques una nave que esté dentro de tu arco de fuego auxiliar, tira 1 dado de ataque adicional."""
"Emon Azzameen":
text: """Cuando sueltes una bomba, puedes utilizar la plantilla de maniobra [%TURNLEFT% 3], [%STRAIGHT% 3] o [%TURNRIGHT% 3] en vez de la plantilla de [%STRAIGHT% 1]."""
"Kavil":
ship: "Ala-Y"
text: """Cuando ataques una nave que esté fuera de tu arco de fuego, tira 1 dado de ataque adicional."""
"Drea Renthal":
ship: "Ala-Y"
text: """Después de gastar una ficha de Blanco Fijado, puedes recibir 1 ficha de Tensión para fijar un blanco."""
"Syndicate Thug":
name: "Esbirro del sindicato"
ship: "Ala-Y"
"Hired Gun":
name: "Piloto de fortuna"
ship: "Ala-Y"
"Spice Runner":
name: "Traficante de Especia"
ship: "HWK-290"
"Dace Bonearm":
text: """Cuando una nave enemiga a alcance 1-3 reciba como mínimo 1 ficha de iones, si no tienes fichas de Tensión puedes recibir 1 ficha de Tensión para que esa nave sufra 1 de daño."""
ship: "HWK-290"
"Palob Godalhi":
text: """Al comienzo de la fase de Combate, puedes quitar 1 ficha de Concentración o Evasión de una nave enemiga a alcance 1-2 y asignar esa ficha a tu nave."""
"Torkil Mux":
text: """Al final de la fase de Activación, elige 1 nave enemiga a alcance 1-2. Hasta el final de la fase de Combate, se considera que el piloto de esa nave tiene Habilidad 0."""
"Binayre Pirate":
name: "Pirata Binayre"
ship: "Z-95 Cazacabezas"
"Black Sun Soldier":
name: "Sicario del Sol Negro"
ship: "Z-95 Cazacabezas"
"N'Dru Suhlak":
text: """Cuando ataques, si no tienes ninguna otra nave aliada a alcance 1-2, tira 1 dado de ataque adicional."""
ship: "Z-95 Cazacabezas"
"Kaa'to Leeachos":
text: """Al comienzo de la fase de Combate, puedes quitar 1 ficha de Concentración o Evasión de otra nave aliada que tengas a alcance 1-2 y asignar esa ficha a tu nave."""
ship: "Z-95 Cazacabezas"
"Commander Alozen":
name: "Comandante Alozen"
ship: "TIE Avanzado"
text: """Al comienzo de la fase de Combate, puedes fijar como blanco una nave enemiga que tengas a alcance 1."""
"Juno Eclipse":
ship: "TIE Avanzado"
text: """Cuando reveles tu maniobra, puedes incrementar o reducir en 1 la velocidad de la maniobra (hasta un mínimo de 1)."""
"Zertik Strom":
ship: "TIE Avanzado"
text: """Las naves enemigas que tengas a alcance 1 no pueden aplicar su modificador al combate por alcance cuando ataquen."""
"Lieutenant Colzet":
name: "Teniente Colzet"
ship: "TIE Avanzado"
text: """Al comienzo de la fase Final, puedes gastar una de tus fichas de Blanco fijado asignadas a una nave enemiga para seleccionar al azar y poner boca arriba 1 carta de Daño que esa nave tenga asignada boca abajo."""
"Latts Razzi":
text: """Cuando una nave aliada declare un ataque, puedes gastar una ficha de Blanco Fijado que hayas asignado al defensor para reducir su Agilidad en 1 contra el ataque declarado."""
"Miranda Doni":
ship: 'Ala-K'
text: """Una vez por ronda, cuando ataques, puedes elegir entre gastar 1 de Escudos para tirar 1 dado de ataque adicional <strong>o bien</strong> tirar 1 dado de ataque menos para recuperar 1 de Escudos."""
"Esege Tuketu":
ship: 'Ala-K'
text: """Cuando otra nave aliada que tengas a alcance 1-2 esté atacando, puede usar tus fichas de Concentración."""
"Guardian Squadron Pilot":
name: "Piloto del Escuadrón Guardián"
ship: 'Ala-K'
"Warden Squadron Pilot":
name: "Piloto del Escuadrón Custodio"
ship: 'Ala-K'
'"Redline"':
name: '"Velocidad Terminal"'
ship: 'Castigador TIE'
text: """Puedes mantener 2 blancos fijados sobre una misma nave. Cuando fijes un blanco, puedes fijar la misma nave como blanco por segunda vez."""
'"Deathrain"':
name: '"Lluvia de Muerte"'
ship: 'Castigador TIE'
text: """Cuando sueltes una bomba, puedes usar los salientes frontales de la peana de tu nave. Puedes realizar una acción gratuita de tonel volado después de soltar una bomba."""
'Black Eight Squadron Pilot':
name: "Piloto del Escuadrón Ocho Negro"
ship: 'Castigador TIE'
'Cutlass Squadron Pilot':
name: "Piloto del Escuadrón Alfanje"
ship: 'Castigador TIE'
"Moralo Eval":
text: """Puedes efectuar ataques con sistemas de armamento secundarios %CANNON% contra naves que estén dentro de tu arco de fuego auxiliar."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"Scourge"':
name: "Azote"
ship: "Caza TIE"
text: """Cuando ataques a un defensor que tiene 1 o más cartas de Daño, tira 1 dado de ataque adicional."""
"The Inquisitor":
name: "El Inquisidor"
ship: "Prototipo de TIE Avanzado"
text: """Cuando ataques con tu armamento principal a alcance 2-3, el alcance del ataque se considera 1."""
"Zuckuss":
ship: "Caza Estelar G-1A"
text: """Cuando ataques, puedes tirar 1 dado de ataque adicional. Si decides hacerlo, el defensor tira 1 dado de defensa adicional."""
"Ruthless Freelancer":
name: "Mercenario Despiadado"
ship: "Caza Estelar G-1A"
"Gand Findsman":
name: "Buscador Gandiano"
ship: "Caza Estelar G-1A"
"Dengar":
ship: "Saltador Maestro 5000"
text: """Una vez por ronda, después de que te defiendas, si el atacante está dentro de tu arco de fuego, puedes efectuar un ataque contra esa nave."""
"Talonbane Cobra":
ship: "Caza Kihraxz"
text: """Cuando ataques o te defiendas, duplica el efecto de tus bonificaciones al combate por alcance."""
"Graz the Hunter":
name: "Graz el Cazador"
ship: "Caza Kihraxz"
text: """Cuando te defiendas, tira 1 dado de defensa adicional si el atacante está situado dentro de tu arco de fuego."""
"Black Sun Ace":
name: "As del Sol Negro"
ship: "Caza Kihraxz"
"Cartel Marauder":
name: "Salteador del Cártel"
ship: "Caza Kihraxz"
"Trandoshan Slaver":
name: "Esclavista Trandoshano"
ship: "YV-666"
"Bossk":
ship: "YV-666"
text: """Cuando realices un ataque con éxito, antes de inflingir el daño puedes anular 1 de tus resultados %CRIT% para añadir 2 resultados %HIT%."""
# T-70
"Poe Dameron":
ship: "T-70 Ala-X"
text: """Cuando ataques o te defiendas, si tienes una ficha de Concentración, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%."""
'"Blue Ace"':
name: '"As Azul"'
ship: "T-70 Ala-X"
text: """Cuando realices una acción de impulso, puedes utilizar la plantilla de maniobra (%TURNLEFT% 1) o (%TURNRIGHT% 1)."""
"Red Squadron Veteran":
name: "Veterano del Esc. Rojo"
ship: "T-70 Ala-X"
"Blue Squadron Novice":
name: "Novato del Esc. Azul"
ship: "T-70 Ala-X"
'"Red Ace"':
name: "As Rojo"
ship: "T-70 Ala-X"
text: '''La primera vez que quites una ficha de Escudos de tu nave en cada ronda, asigna 1 ficha de Evasión a tu nave.'''
# TIE/fo
'"Omega Ace"':
name: '"As Omega"'
ship: "Caza TIE/fo"
text: """Cuando ataques a un defensor que has fijado como blanco, puedes gastar las fichas de Blanco Fijado y una ficha de Concentración para cambiar todos tus resultados de dados por resultados %CRIT%."""
'"Epsilon Leader"':
name: '"Jefe Epsilon"'
ship: "Caza TIE/fo"
text: """Al comienzo de la fase de Combate, retira 1 ficha de Tensión de cada nave aliada que tengas a alcance 1."""
'"Zeta Ace"':
name: '"As Zeta"'
ship: "Caza TIE/fo"
text: """Cuando realices una acción de tonel volado, puedes utilizar la plantilla de maniobra (%STRAIGHT% 2) en vez de la plantilla (%STRAIGHT% 1)."""
"Omega Squadron Pilot":
name: "Piloto del Esc. Omega"
ship: "Caza TIE/fo"
"Zeta Squadron Pilot":
name: "Piloto del Esc. Zeta"
ship: "Caza TIE/fo"
"Epsilon Squadron Pilot":
name: "Piloto del Esc. Epsilon"
ship: "Caza TIE/fo"
'"Omega Leader"':
name: "Jefe Omega"
ship: "Caza TIE/fo"
text: '''Las naves enemigas que tienes fijadas como blanco no pueden modificar ningún dado cuando te atacan o se defienden de tus ataques.'''
'Hera Syndulla':
text: '''Cuando reveles una maniobra verde o roja, puedes girar tu selector de maniobras para escoger otra maniobra del mismo color.'''
'"Youngster"':
name: "Pipiolo"
ship: "Caza TIE"
text: """Los Cazas TIE aliados que tengas a alcance 1-3 pueden realizar la acción de tu carta de Mejora %ELITE% equipada."""
'"Wampa"':
ship: "Caza TIE"
text: """Cuando ataques, al comienzo del paso "Comparar los resultados", puedes anular todos los resultados de los dados. Si anulas al menos un resultado %CRIT%, inflinge 1 carta de Daño boca abajo al defensor."""
'"Chaser"':
name: "Perseguidor"
ship: "Caza TIE"
text: """Cuando otra nave aliada que tengas a alcance 1 gaste una ficha de Concentración, asigna 1 ficha de Concentración a tu nave."""
'Ezra Bridger':
ship: "Lanzadera de Ataque"
text: """Cuando te defiendas, si estás bajo tensión, puedes cambiar hasta 2 de tus resultados %FOCUS% por resultados %EVADE%."""
'"Zeta Leader"':
name: "Jefe Zeta"
text: '''Cuando ataques, si no estás bajo tensión, puedes recibir 1 ficha de Tensión para tirar 1 dado de ataque adicional.'''
ship: "Caza TIE/fo"
'"Epsilon Ace"':
name: "As Epsilon"
text: '''Mientras no tengas ninguna carta de Daño asignada, se considera que tienes Habilidad 12.'''
ship: "Caza TIE/fo"
"Kanan Jarrus":
text: """Cuando una nave enemiga que tengas a alcance 1-2 efectúe un ataque, puedes gastar una ficha de Concentración. Si decides hacerlo, el atacante tira 1 dado de ataque menos."""
'"Chopper"':
text: """Al comienzo de la fase de Combate, toda nave enemiga con la que estés en contacto recibe 1 ficha de Tensión."""
'Hera Syndulla (Attack Shuttle)':
name: "Hera Syndulla (Lanzadera de Ataque)"
ship: "Lanzadera de Ataque"
text: """Cuando reveles una maniobra verde o roja, puedes girar tu selector de maniobras para escoger otra maniobra del mismo color."""
'Sabine Wren':
ship: "Lanzadera de Ataque"
text: """Inmediatamente antes de revelar tu maniobra, puedes realizar una acción gratuita de impulso o tonel volado."""
'"Zeb" Orrelios':
ship: "Lanzadera de Ataque"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
"Lothal Rebel":
name: "Rebelde de Lothal"
ship: "VCX-100"
'Tomax Bren':
text: '''Una vez por ronda, después de que te descartes de una carta de Mejora %ELITE%, dale la vuelta a esa carta para ponerla boca arriba.'''
ship: "Bombardero TIE"
'Ello Asty':
text: '''Mientras no estés bajo tensión, puedes ejecutar tus maniobras %TROLLLEFT% y %TROLLRIGHT% como maniobras blancas.'''
ship: "T-70 Ala-X"
"Valen Rudor":
text: """Después de que te defiendas, puedes ralizar una acción gratuita."""
ship: "Prototipo de TIE Avanzado"
"4-LOM":
ship: "Caza Estelar G-1A"
text: """Al comienzo de la fase Final, puedes asignar 1 de tus fichas de Tensión a otra nave que tengas a alcance 1."""
"Tel Trevura":
ship: "Saltador Maestro 5000"
text: """La primrea vez que seas destruido, en vez de eso anula todo el daño restante, descarta todas tus cartas de Daño e inflinge 4 cartas de Daño boca abajo a esta nave."""
"Manaroo":
ship: "Saltador Maestro 5000"
text: """Al comienzo de la fase de Combate, puedes asignar a otra nave aliada a alcance 1 todas las fichas de Concentración, Evasión y Blanco Fijado que tengas asignadas."""
"Contracted Scout":
name: "Explorador Contratado"
ship: "Saltador Maestro 5000"
'"Deathfire"':
name: "Muerte Ígnea"
text: '''Cuando reveles tu selector de maniobras o después de que realices una acción, puedes realizar una acción de carta de Mejora %BOMB% como acción gratuita.'''
ship: "Bombardero TIE"
"Sienar Test Pilot":
name: "Piloto de pruebas de Sienar"
ship: "Prototipo de TIE Avanzado"
"Baron of the Empire":
name: "Barón del Imperio"
ship: "Prototipo de TIE Avanzado"
"Maarek Stele (TIE Defender)":
name: "Maarek Stele (Defensor TIE)"
text: """Cuando tu ataque inflija una carta de Daño boca arriba al defensor, en vez de eso roba 3 cartas de Daño, elige 1 de ellas a tu elección y luego descarta las otras."""
ship: "Defensor TIE"
"Countess Ryad":
name: "Condesa Ryad"
text: """Cuando reveles una maniobra %STRAIGHT%, puedes considerarla como una maniobra %KTURN%."""
ship: "Defensor TIE"
"Glaive Squadron Pilot":
name: "Piloto del escuadrón Guja"
ship: "Defensor TIE"
"Poe Dameron (PS9)":
text: """Cuando ataques o te defiendas, si tienes una ficha de Concentración, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%."""
ship: "T-70 Ala-X"
"Resistance Sympathizer":
name: "Simpatizante de la Resistencia"
ship: "YT-1300"
"Rey":
text: """Cuando ataques o te defiendas, si la nave enemiga está dentro de tu arco de fuego, puedes volver a tirar hasta 2 dados en los que hayas sacado caras vacías."""
'Han Solo (TFA)':
text: '''En el momento de desplegarte durante la preparación de la partida, se te puede colocar en cualquier parte de la zona de juego que esté más allá de alcance 3 de las naves enemigas.'''
'Chewbacca (TFA)':
text: '''Después de que otra nave aliada que tengas a alcance 1-3 sea destruida (pero no hay aabandonado el campo de batalla), puedes efectuar un ataque.'''
'Norra Wexley':
ship: "ARC-170"
text: '''Cuando ataques o te defiendas, puedes gastar una ficha de Blanco fijado que tengas sobre la nave enemiga para añadir 1 resultado %FOCUS% a tu tirada.'''
'Shara Bey':
ship: "ARC-170"
text: '''Cuando otra nave aliada que tengas a alcance 1-2 esté atacando, puede usar tus fichas azules de Blanco fijado como si fuesen suyas.'''
'Thane Kyrell':
ship: "ARC-170"
text: '''Después de que una nave enemiga que tengas dentro de tu arco de fuego a alcance 1-3 ataque a otra nave aliada, puedes realizar una acción gratuita.'''
'Braylen Stramm':
ship: "ARC-170"
text: '''Después de que ejecutes una maniobra, puedes tirar 1 dado de ataque. Si sacas %HIT% o %CRIT%, quita 1 ficha de Tensión de tu nave.'''
'"Quickdraw"':
name: "Centella"
ship: "Caza TIE/sf"
text: '''Una vez por ronda, cuando pierdas una ficha de Escudos, puedes realizar un ataque de armamento principal.'''
'"Backdraft"':
name: "Llamarada"
ship: "Caza TIE/sf"
text: '''Cuando ataques a una nave que esté dentro de tu arco de fuego auxiliar, puedes añadir 1 resultado %CRIT%.'''
'Omega Specialist':
name: "Especialista del Escuadrón Omega"
ship: "Caza TIE/sf"
'Zeta Specialist':
name: "Especialista del Escuadrón Zeta"
ship: "Caza TIE/sf"
'Fenn Rau':
ship: "Caza Estelar del Protectorado"
text: '''Cuando ataques o te defiendas, si tienes la nave enemiga a alcance 1, puedes tirar 1 dado adicional.'''
'Old Teroch':
name: "Viejo Teroch"
ship: "Caza Estelar del Protectorado"
text: '''Al comienzo de la fase de Combate, puedes elegir 1 nave enemiga que tengas a alcance 1. Si estás dentro de su arco de fuego, esa nave descarta todas sus fichas de Concentración y Evasión.'''
'Kad Solus':
ship: "Caza Estelar del Protectorado"
text: '''Después de que ejecutes una maniobra roja, asigna 2 fichas de Concentración a tu nave.'''
'Concord Dawn Ace':
name: "As de Concord Dawn"
ship: "Caza Estelar del Protectorado"
'Concord Dawn Veteran':
name: "Veterano de Concord Dawn"
ship: "Caza Estelar del Protectorado"
'Zealous Recruit':
name: "Recluta entusiasta"
ship: "Caza Estelar del Protectorado"
'Ketsu Onyo':
ship: "Nave de persecución clase Lancero"
text: '''Al comienzo de la fase de Combate, puedes elegir una nave que tengas a alcance 1. Si esa nave está dentro de tus arcos de fuego normal <strong>y</strong> móvil, asígnale 1 ficha de Campo de tracción.'''
'Asajj Ventress':
ship: "Nave de persecución clase Lancero"
text: '''Al comienzo de la fase de Combate, puedes elegir una nave que tengas a alcance 1-2. Si esa nave está dentro de tu arco de fuego móvil, asígnale 1 ficha de Tensión.'''
'Sabine Wren (Scum)':
ship: "Nave de persecución clase Lancero"
text: '''Cuando te defiendas contra una nave enemiga que tengas dentro de tu arco de fuego móvil a alcance 1-2, puedes añadir 1 resultado %FOCUS% a tu tirada.'''
'Shadowport Hunter':
name: "Cazador de puerto clandestino"
ship: "Nave de persecución clase Lancero"
'Sabine Wren (TIE Fighter)':
ship: "Caza TIE"
text: '''Inmediatametne antes de revelar tu maniobra, puedes realizar una acción gratuita de impulso o tonel volado.'''
'"Zeb" Orrelios (TIE Fighter)':
ship: "Caza TIE"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
'Kylo Ren':
ship: "Lanzadera clase Ípsilon"
text: '''La primera vez que seas impactado por un ataque en cada ronda, asigna la carta de Estad "Yo te mostraré el Lado Oscuro" al atacante.'''
'Unkar Plutt':
ship: "Saltador Quad"
text: '''Al final de la fase de Activación, <strong>debes</strong> asignar una ficha de Campo de tracción a toda nave con la que estés en contacto.'''
'Cassian Andor':
ship: "Ala-U"
text: '''Al comienzo de la fase de Activación, puedes quitar 1 ficha de Tensión de 1 otra nave aliada que tengas a alcance 1-2.'''
'Bodhi Rook':
ship: "Ala-U"
text: '''Cuando una nave aliada fije un blanco, esa nave puede fijarlo sobre una nave enemiga que esté situada a alcance 1-3 de cualquier nave aliada.'''
'Heff Tobber':
ship: "Ala-U"
text: '''Después de que una nave enemiga ejecute una maniobra que la haga solaparse con tu nave, puedes realizar una acción gratuita.'''
'''"Duchess"''':
ship: "Fustigador TIE"
name: '"Duquesa"'
text: '''Cuando tengas equipada la carta de Mejora "Alreones adaptativos", puedes elegir ignorar su capacidad de carta.'''
'''"Pure Sabacc"''':
ship: "Fustigador TIE"
name: '"Sabacc Puro"'
text: '''Cuando ataques, si tienes 1 o menos cartas de Daño, tira 1 dado de ataque adicional.'''
'''"Countdown"''':
ship: "Fustigador TIE"
name: '"Cuenta Atrás"'
text: '''Cuando te defiendas, si no estás bajo tensión, durante el paso "Comparar los resultados", puedes sufrir 1 punto de daño para anular <strong>todos</strong> los resultados de los dados. Si lo haces, recibes 1 ficha de Tensión.'''
'Nien Nunb':
ship: "T-70 Ala-X"
text: '''Cuando recibas una ficha de Tensión, si hay alguna nave enemiga dentro de tu arco de fuego a alcance 1, puedes descartar esa ficha de Tensión.'''
'"Snap" Wexley':
ship: "T-70 Ala-X"
text: '''Después de que ejecutes una maniobra de velocidad 2, 3 ó 4, si no estás en contacto con ninguna nave, puedes realizar una acción gratuita de impulso.'''
'Jess Pava':
ship: "T-70 Ala-X"
text: '''Cuando ataques o te defiendas, puedes volver a tirar 1 de tus dados por cada otra nave aliada que tengas a Alcance 1.'''
'Ahsoka Tano':
ship: "Caza TIE"
text: '''Al comienzo de la fase de Combate, puedes gastar 1 ficha de Concentración para elegir una nave aliada que tengas a alcance 1. Esa nave puede realizar 1 acción gratuita.'''
'Captain Rex':
ship: "Caza TIE"
name: "Capitán Rex"
text: '''Después de que efectúes un ataque, asigna la carta de Estado "Fuego de supresión" al defensor.'''
'Major Stridan':
ship: "Lanzadera clase Ípsilon"
name: "Mayor Stridan"
text: '''A efectos de tus acciones y cartas de Mejora, puedes considerar las naves aliadas que tengas a alcance 2-3 como si estuvieran a alcance 1.'''
'Lieutenant Dormitz':
ship: "Lanzadera clase Ípsilon"
name: "Teniente Dormitz"
text: '''Durante la preparación de la partida, las naves aliadas pueden ser colocadas en cualquier lugar de la zona de juego que esté situado a alcance 1-2 de ti.'''
'Constable Zuvio':
ship: "Saltador Quad"
name: "Alguacil Zuvio"
text: '''Cuando reveles una maniobra de retroceso, puedes soltar una bomba usando los salientes de la parte frontal de tu peana (incluso una bomba con el encabezado "<strong>Acción:</strong>").'''
'Sarco Plank':
ship: "Saltador Quad"
text: '''Cuando te defiendas, en vez de usar tu valor de Agilidad, puedes tirar tantos dados de defensa como la velocidad de la maniobra que has ejecutado en esta ronda.'''
"Blue Squadron Pathfinder":
name: "Infiltrador del Escuadrón Azul"
ship: "Ala-U"
"Black Squadron Scout":
name: "Explorador del Escuadrón Negro"
ship: "Fustigador TIE"
"Scarif Defender":
name: "Defensor de Scarif"
ship: "Fustigador TIE"
"Imperial Trainee":
name: "Cadete Imperial"
ship: "Fustigador TIE"
"Starkiller Base Pilot":
ship: "Lanzadera clase Ípsilon"
name: "Piloto de la base Starkiller"
"Jakku Gunrunner":
ship: "Saltador Quad"
name: "Traficante de armas de Jakku"
'Genesis Red':
ship: "Interceptor M3-A"
text: '''Después de que fijes un blanco, asigna fichas de Concentración y fichas de Evasión a tu nave hasta que tengas tantas fichas de cada tipo como la nave que has fijado.'''
'Quinn Jast':
ship: "Interceptor M3-A"
text: '''Al comienzo de la fase de Combate, puedes recibir una ficha de Armas inutilizadas para poner boca arriba una de tus cartas de Mejora %TORPEDO% o %MISSILE% descartadas.'''
'Inaldra':
ship: "Interceptor M3-A"
text: '''Cuando ataques o te defiendas, puedes gastar 1 ficha de Escudos para volver a tirar cualquier cantidad de tus dados.'''
'Sunny Bounder':
ship: "Interceptor M3-A"
text: '''Una vez por ronda, después de que tires o vuelvas a tirar los dados, si has sacado el mismo resultado en cada uno de tus dados, puedes añadir 1 más de esos resultados a la tirada.'''
'C-ROC Cruiser':
ship: "Crucero C-ROC"
name: "Crucero C-ROC"
'Lieutenant Kestal':
ship: "TIE Agresor"
text: '''Cuando ataques, puedes gastar 1 ficha de Concentración para anular todos los resultados %FOCUS% y de cara vacía del defensor.'''
'"Double Edge"':
ship: "TIE Agresor"
name: "Doble Filo"
text: '''Una vez por ronda, después de que efectúes un ataque con un armamento secundario que no impacte, puedes efectuar un ataque con un arma diferente.'''
'Onyx Squadron Escort':
ship: "TIE Agresor"
name: "Escolta del Escuadrón Ónice"
'Sienar Specialist':
ship: "TIE Agresor"
name: "Especialista de Sienar"
'Viktor Hel':
ship: "Caza Kihraxz"
text: '''Después de que te defiendas, si la tirada que realizaste no consistió exactamente en 2 dados de defensa, el atacante recibe 1 ficha de Tensión.'''
'Lowhhrick':
ship: "Cañonera Auzituck"
text: '''Cuando otra nave aliada que tengas a alcance 1 se esté defendiendo, puedes gastar 1 ficha de Refuerzo. Si lo haces, el defensor añade 1 resultado %EVADE%.'''
'Wullffwarro':
ship: "Cañonera Auzituck"
text: '''Cuando ataques, si no tienes ninguna ficha de Escudos y tienes asignada como mínimo 1 carta de Daño, tira 1 dado de ataque adicional.'''
'Wookiee Liberator':
name: "Libertador wookie"
ship: "Cañonera Auzituck"
'Kashyyyk Defender':
name: "Defensor de Kashyyyk"
ship: "Cañonera Auzituck"
'Captain Nym (Scum)':
name: "Capitán Nym (Scum)"
ship: "Bombardero Scurrg H-6"
text: '''Puedes ignorar las bombas aliadas. Cuando una nave aliada se está defendiendo, si el atacante mide el alcance a través de una ficha de Bomba aliada, el defensor puede añadir 1 resultado%EVADE%.'''
'Captain Nym (Rebel)':
name: "Capitán Nym (Rebelde)"
ship: "Bombardero Scurrg H-6"
text: '''Una vez por ronda, puedes impedir que una bomba aliada detone.'''
'Lok Revenant':
name: "Aparecido de Lok"
ship: "Bombardero Scurrg H-6"
'Karthakk Pirate':
name: "Pirata de Karthakk"
ship: "Bombardero Scurrg H-6"
'Sol Sixxa':
ship: "Bombardero Scurrg H-6"
text: '''Cuando sueltes una bomba, puedes utilizar la plantilla de maniobra (%TURNLEFT% 1) o (%TURNRIGHT% 1) en vez de la plantilla de (%STRAIGHT% 1).'''
'Dalan Oberos':
ship: 'Víbora Estelar'
text: '''Si no estás bajo tensión, cuando reveles una maniobra de giro, inclinación o giro de Segnor, puedes ejecutarla como si fuera una maniobra roja de giro Tallon con la misma dirección (izquierda o derecha) utilizando la plantilla de maniobra revelada originalmente.'''
'Thweek':
ship: 'Víbora Estelar'
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", puedes elegir 1 nave enemiga y asignarle la carta de Estado "Vigilado" o "Imitado".'''
'Black Sun Assassin':
name: "Asesino del Sol Negro"
ship: 'Víbora Estelar'
'Captain Jostero':
name: "Capitán Jostero"
ship: "Caza Kihraxz"
text: '''Una vez por ronda, después de que una nave enemiga que no se está defendiendo contra un ataque sufra daño normal o daño crítico, puedes efectuar un ataque contra esa nave.'''
'Major Vynder':
ship: "Ala Estelar clase Alfa"
name: "Mayor Vynder"
text: '''Cuando te defiendas, si tienes asignada una ficha de Armas bloqueadas, tira 1 dado de defensa adicional.'''
'Nu Squadron Pilot':
name: "Piloto del Escuadrón Nu"
ship: "Ala Estelar clase Alfa"
'Rho Squadron Veteran':
name: "Veterano del Escuadrón Rho"
ship: "Ala Estelar clase Alfa"
'Lieutenant Karsabi':
ship: "Ala Estelar clase Alfa"
name: "Teniente Karsabi"
text: '''Cuando recibas una ficha de Armas bloqueadas, si no estás bajo tensión, puedes recibir 1 ficha de Tensión para retirar esa ficha de Armas bloqueadas.'''
'Cartel Brute':
name: "Secuaz del Cártel"
ship: "Caza M12-L Kimogila"
'Cartel Executioner':
name: "Verdugo del Cártel"
ship: "Caza M12-L Kimogila"
'Torani Kulda':
ship: "Caza M12-L Kimogila"
text: '''Después de que efectúes un ataque, toda nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego centrado debe elegir entre sufrir 1 daño o retirar todas sus fichas de Concrentración y Evasión.'''
'Dalan Oberos (Kimogila)':
ship: "Caza M12-L Kimogila"
text: '''Al comienzo de la fase de Combate, puedes fijar como blanco una nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego centrado.'''
'Fenn Rau (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando una nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego pase a ser la nave activa durante la fase de Combate, si no estás bajo tensión, puedes recibir 1 ficha de Tensión. Si lo haces, esa nave no podrá gastar fichas para modificar sus dados cuando ataque en esta ronda.'''
'Ezra Bridger (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: """Cuando te defiendas, si estás bajo tensión, puedes cambiar hasta 2 de tus resultados %FOCUS% por resultados %EVADE%."""
'"Zeb" Orrelios (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
'AP-5':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando realices la acción de coordinación, después de que elijas a una nave aliada y antes de que esa nave realice su acción gratuita, puedes recibir 2 fichas de Tensión para quitarle 1 ficha de Tensión a esa nave.'''
'Crimson Squadron Pilot':
name: "Piloto del Escuadrón Carmesí"
ship: "Bombardero B/SF-17"
'"Crimson Leader"':
name: '"Jefe Carmesí"'
ship: "Bombardero B/SF-17"
text: '''Cuando ataques, si el defensor está situado dentro de tu arco de fuego, puedes gastar 1 resultado %HIT% o %CRIT% para asignar el estado "Estremecido" al defensor.'''
'"Crimson Specialist"':
name: '"Especialista Carmesí"'
ship: "Bombardero B/SF-17"
text: '''Cuando coloques una ficha de Bomba que has soltado después de revelar tu selector de maniobras, puedes colocarla en cualquier lugar de la zona de juego donde quede en contacto con tu nave.'''
'"Cobalt Leader"':
name: '"Jefe Cobalto"'
ship: "Bombardero B/SF-17"
text: '''Cuando ataques, si el defensor está situado a alcance 1 de una ficha de Bomba, el defensor tira 1 dado de defensa menos (hasta un mínimo de 0).'''
'Sienar-Jaemus Analyst':
name: "Analista de Sienar-Jaemus"
ship: "Silenciador TIE"
'First Order Test Pilot':
name: "Piloto de pruebas de la Primera Orden"
ship: "Silenciador TIE"
'Kylo Ren (TIE Silencer)':
name: "Kylo Ren (Silenciador TIE)"
ship: "Silenciador TIE"
text: '''La primera vez que seas impactado por un ataque en cada ronda, asigna la carta de Estado "Yo te mostraré el Lado Oscuro" al atacante.'''
'Test Pilot "Blackout"':
name: 'Piloto de pruebas "Apagón"'
ship: "Silenciador TIE"
text: '''Cuando ataques, si el ataque está obstruido, el defensor tira 2 dados de defensa menos (hasta un mínimo de 0).'''
'Partisan Renegade':
name: "Insurgente de los Partisanos"
ship: "Ala-U"
'Cavern Angels Zealot':
name: "Fanático de los Ángeles Cavernarios"
ship: "Ala-X"
'Kullbee Sperado':
ship: "Ala-X"
text: '''Después de que realices una acción de impulso o de tonel volado, puedes darle la vuelta a la carta de Mejora "Alas móviles" que tengas equipada en tu nave.'''
'Major Vermeil':
name: "Mayor Vermeil"
ship: "Segador TIE"
text: '''Cuando ataques, si el defensor no tiene asignada ninguna ficha de Concentración ni de Evasión, puedes cambiar 1 de tus resultados %FOCUS% o de cara vacía por un resultado %HIT%.'''
'"Vizier"':
name: '"Visir"'
text: '''Después de que una nave aliada ejecute una maniobra con una velocidad de 1, si esa nave está situada a alcance 1 de ti y no se ha solapado con ninguna nave, puedes asignarle 1 de tus fichas de Concentración o Evasión.'''
ship: "Segador TIE"
'Captain Feroph':
name: 'Capitán Feroph'
ship: "Segador TIE"
text: '''Cuando te defiendas, si el atacante está interferido, añade 1 resultado %EVADE% a tu tirada.'''
'Scarif Base Pilot':
name: "Piloto de la base de Scarif"
ship: "Segador TIE"
'Leevan Tenza':
ship: "Ala-X"
text: '''Después de que realices una acción de impulso, puedes recibir 1 ficha de Tensión para recibir 1 ficha de Evasión.'''
'Saw Gerrera':
ship: "Ala-U"
text: '''Cuando una nave aliada que tengas a alcance 1-2 efectúe un ataque, si esa nave está bajo tensión o tiene asignada por lo menos 1 carta de Daño, puede volver a tirar 1 dado de ataque.'''
'Benthic Two-Tubes':
name: "Benthic Dos Tubos"
ship: "Ala-U"
text: '''Después de que realices una acción de concentración, puedes retirar 1 de tus fichas de Concentración para asignarla a una nave aliada que tengas a alcance 1-2.'''
'Magva Yarro':
ship: "Ala-U"
text: '''Cuando otra nave aliada que tengas a alcance 1-2 se defienda, el atacante no puede volver a tirar más de 1 dado de ataque.'''
'Edrio Two-Tubes':
name: "Edrio Dos Tubos"
ship: "Ala-X"
text: '''Cuando te conviertas en la nave activa durante la fase de Activación, si tienes asignadas 1 o más fichas de Concentración, puedes realizar una acción gratuita.'''
upgrade_translations =
"Ion Cannon Turret":
name: "Torreta de cañones de iones"
text: """<strong>Ataque:</strong> Ataca 1 nave (aunque esté fuera de tu arco de fuego).<br /><br />Si este ataque impacta, el defensor sufre 1 punto de daño y recibe 1 ficha de Iones. Después se anulan todos los resultados de los dados."""
"Proton Torpedoes":
name: "Torpedos de protones"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
"R2 Astromech":
name: "Droide Astromecánico R2"
text: """Puedes ejecutar todas las maniobras de velocidad 1 y 2 como maniobras verdes."""
"R2-D2":
text: """Después de que ejecutes una maniobra verde, puedes recuperar 1 ficha de Escudos (pero no puedes tener más fichas que tu valor de Escudos)."""
"R2-F2":
text: """<strong>Acción:</strong> Tu valor de agilidad aumenta en 1 hasta el final de esta ronda de juego."""
"R5-D8":
text: """<strong>Acción:</strong> Tira 1 dado de defensa.<br /><br />Si sacas %EVADE% o %FOCUS%, descarta 1 carta de Daño que tengas boca abajo."""
"R5-K6":
text: """Después de gastar tu ficha de Blanco Fijado, tira 1 dado de defensa.<br /><br />Si sacas un resultado %EVADE% puedes volver a fijar la misma nave como blanco inmediatamente. No puedes gastar esta nueva ficha de Blanco Fijado durante este ataque."""
"R5 Astromech":
name: "Droide Astromecánico R5"
text: """Durante la fase Final, puedes elegir 1 de las cartas de Daño con el atributo <strong>Nave</strong> que tengas boca arriba, darle la vuelta y dejarla boca abajo."""
"Determination":
name: "Determinación"
text: """Cuando se te asigne una carta de Daño boca arriba que tenga el atributo <strong>Piloto</strong>, descártala inmediatamente sin resolver su efecto."""
"Swarm Tactics":
name: "Táctica de Enjambre"
text: """Al principio de la fase de Combate, elige 1 nave aliada que tengas a alcance 1.<br /><br />Hasta el final de esta fase, se considera que el valor de Habilidad de la nave elejida es igual que el tuyo."""
"Squad Leader":
name: "Jefe de Escuadrón"
text: """<strong>Acción:</strong> Elije una nave a alcance 1-2 cuyo pilioto tenga una Habilidad más baja que la tuya.<br /><br />La nave elegida puede llevar a cabo 1 acción gratuita de inmediato."""
"Expert Handling":
name: "Pericia"
text: """<strong>Acción:</strong> Realiza una acción gratuita de tonel volado. Si no tienes el icono de acción %BARRELROLL%, recibes una ficha de Tensión.<br /><br />Después puedes descartar 1 ficha enemiga de Blanco Fijado que esté asignada a tu nave."""
"Marksmanship":
name: "Puntería"
text: """<strong>Acción:</strong> Cuando ataques en esta ronda puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT% y tus demás resultados %FOCUS% por resultados %HIT%."""
"Concussion Missiles":
name: "Misiles de Impacto"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Puedes cambiar 1 resultado de cara vacía por un resultado %HIT%."""
"Cluster Missiles":
name: "Misiles de Racimo"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque <strong>dos veces</strong>."""
"Daredevil":
name: "Temerario"
text: """<strong>Acción:</strong> Ejecuta una maniobra blanca (%TURNLEFT% 1) o (%TURNRIGHT% 1) y luego recibe 1 ficha de Tensión.<br /><br />Después, si no tienes el ícono de acción %BOOST%, tira 2 dados de ataque y sufre todos los daños normales (%HIT%) y críticos (%CRIT%) obtenidos."""
"Elusiveness":
name: "Escurridizo"
text: """Cuando te defiendas en combate, puedes recibir 1 ficha de Tensión para elegir 1 dado de ataque. El atacante deberá volver a lanzar ese dado.<br /><br />No puedes usar esta habilidad si ya tienes una ficha de Tensión."""
"Homing Missiles":
name: "Misiles Rastreadores"
text: """<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque.<br /><br />El defensor no puede gastar fichas de evasión durante este ataque."""
"Push the Limit":
name: "Máximo Esfuerzo"
text: """Una vez por ronda, después de que realices una acción podras realizar a cabo 1 acción gratuita de entre las que figuren en tu barra de acciones.<br /><br />Después recibes 1 ficha de Tensión."""
"Deadeye":
name: "Certero"
text: """%SMALLSHIPONLY%%LINEBREAK%Puedes tratar la expresión <strong>"Ataque (blanco fijado)"</strong> como si dijera <strong>"Ataque (concentración)"</strong>.<br /><br />Cuando un ataque te obligue a gastar una ficha de Blanco Fijado, puedes gastar una ficha de Concentración en su lugar."""
"Expose":
name: "Expuesto"
text: """<strong>Acción:</strong> Hasta el final de la ronda, el valor de tu armamento principal se incrementa en 1 y tu Agilidad se reduce en 1."""
"Gunner":
name: "Artillero"
text: """Después de que efectúes un ataque y lo falles, puedes realizar inmediatamente un ataque con tu armamento principal. No podrás realizar ningún otro ataque en esta misma ronda."""
"Ion Cannon":
name: "Cañón de Iones"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Si este ataque impacta, el defensor sufre 1 de daño y recibe 1 ficha de Iones. Después se anulan <b>todos</b> los resultados de los dados."""
"Heavy Laser Cannon":
name: "Cañón Láser Pesado"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Inmediatamente después de lanzar los dados de ataque, debes cambiar todos tus resultados %CRIT% por resultados %HIT%."""
"Seismic Charges":
name: "Cargas Sísmicas"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Carga Sísmica.<br /><br />Esta ficha se <strong>detona</strong> al final de la fase de Activación."""
"Mercenary Copilot":
name: "Copiloto Mercenario"
text: """Cuando ataques a alcance 3, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%."""
"Assault Missiles":
name: "Misiles de Asalto"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta al objetivo, toda otra nave que haya a alcance 1 del defensor sufre 1 daño."""
"Veteran Instincts":
name: "Instinto de Veterano"
text: """La Habilidad de tu piloto se incrementa en 2."""
"Proximity Mines":
name: "Minas de Proximidad"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Mina de Proximidad.<br /><br />Cuando la peana o la plantilla de maniobra de una nave se solape con esta ficha, ésta se <strong>detona</strong>.<br /><br /><strong>Ficha de Mina de proximidad:</strong> Cuando se detona una de estas fichas de Bomba, la nave que la haya atravesado o solapado tira 3 dados de ataque y sufre todo el daño (%HIT%) y daño crítico (%CRIT%) obtenido en la tirada. Después se descarta esta ficha."""
"Weapons Engineer":
name: "Ingeniero de Armamento"
text: """Puedes tener 2 Blancos Fijados a la vez (pero sólo 1 para cada nave enemiga).<br /><br />Cuando fijes un blanco, puedes fijar como blanco a dos naves distintas."""
"Draw Their Fire":
name: "Atraer su fuego"
text: """Cuando una nave aliada que tengas a alcance 1 sea alcanzada por un ataque, puedes sufrir tú 1 de sus resultados %CRIT% no anulados en vez de la nave objetivo."""
"Luke Skywalker":
text: """Después de que efectúes un ataque y lo falles, puedes realizar inmediatamente un ataque con tu armamento principal. Puedes cambiar 1 resultado %FOCUS% por 1 resultado %HIT%. No podrás realizar ningún otro ataque en esta misma ronda."""
"Nien Nunb":
text: """Todas las maniobras %STRAIGHT% se consideran verdes para ti."""
"Chewbacca":
text: """Cuando recibas una carta de Daño, puedes descartarla de inmediato y recuperar 1 de Escudos.<br /><br />Luego descarta esta carta de Mejora."""
"Advanced Proton Torpedoes":
name: "Torpedos de protones avanzados"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque. Puedes cambiar hasta 3 resultados de caras vacías por resultados %FOCUS%."""
"Autoblaster":
name: "Cañón Blaster Automático"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Tus resultados %HIT% no pueden ser anulados por los dados de defensa.<br /><br />El defensor puede anular tus resultados %CRIT% antes que los %HIT%."""
"Fire-Control System":
name: "Sistema de Control de Disparo"
text: """Después de que efectúes un ataque, puedes fijar al defensor como blanco."""
"Blaster Turret":
name: "Torreta Bláster"
text: """<strong>Ataque (Concentración):</strong> Gasta 1 ficha de Concentración para efectuar este ataque contra una nave (aunque esté fuera de tu arco de fuego)."""
"Recon Specialist":
name: "Especialista en Reconocimiento"
text: """Cuando realices una acción de Concentración, asigna 1 ficha de Concentración adicional a tu nave."""
"Saboteur":
name: "Saboteador"
text: """<strong>Acción:</strong> Elige 1 nave enemiga que tengas a alcance 1 y tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, elige al azar 1 carta de Daño que esa nave tenga asignada boca abajo, dale la vuelta y resuélvela."""
"Intelligence Agent":
name: "Agente del Servicio de Inteligencia"
text: """Al comienzo de la fase de Activación, elige 1 nave enemiga que tengas a alcance 1-2. Puedes mirar el selector de maniobras de esa nave."""
"Proton Bombs":
name: "Bombas de Protones"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Bombas de Protones.<br /><br />Esta ficha se <strong>detona</strong> al final de la fase de Activación."""
"Adrenaline Rush":
name: "Descarga de Adrenalina"
text: """Cuando reveles una maniobra roja, puedes descartar esta carta para tratarla como si fuera una maniobra blanca hasta el final de la fase de Activación."""
"Advanced Sensors":
name: "Sensores Avanzados"
text: """Inmediatamente antes de que reveles tu maniobra, puedes realizar 1 acción gratuita.<br /><br />Si utilizas esta capacidad, debes omitir tu paso de "Realizar una acción" durante esta ronda."""
"Sensor Jammer":
name: "Emisor de Interferencias"
text: """Cuando te defiendas, puedes cambiar 1 de los resultados %HIT% por uno %FOCUS%.<br /><br />El atacante no puede volver a lanzar el dado cuyo resultado hayas cambiado."""
"Darth Vader":
text: """Después de que ataques a una nave enemiga, puedes sufrir 2 de daño para que esa nave reciba 1 de daño crítico."""
"Rebel Captive":
name: "Prisionero Rebelde"
text: """Una vez por ronda, la primera nave que te declare como objetivo de un ataque recibe inmediatamente 1 ficha de Tensión."""
"Flight Instructor":
name: "Instructor de Vuelo"
text: """Cuando te defiendas, puedes volver a tirar 1 dado en el que hayas sacado %FOCUS%. Si la Habilidad del piloto atacante es de 2 o menos, puedes volver a tirar 1 dado en el que hayas sacado una cara vacía."""
"Navigator":
name: "Oficial de Navegación"
text: """Cuando reveles una maniobra, puedes rotar el selector para escoger otra maniobra que tenga la misma dirección.<br /><br />Si tienes alguna ficha de Tensión, no puedes rotar el selector para escoger una maniobra roja."""
"Opportunist":
name: "Oportunista"
text: """Cuando ataques, si el defensor no tiene fichas de Concentración o de Evasión, puedes recibir 1 ficha de Tensión para tirar 1 dado de ataque adicional.<br /><br />No puedes utilizar esta capacidad si tienes fichas de Tensión."""
"Comms Booster":
name: "Amplificador de Comunicaciones"
text: """<strong>Energía:</strong> Gasta 1 de Energía para descartar todas las fichas de Tensión de una nave aliada que tengas a alcance at Range 1-3. Luego asigna 1 ficha de Concentración a esa nave."""
"Slicer Tools":
name: "Sistemas de Guerra Electrónica"
text: """<strong>Acción:</strong> Elige 1 o mas naves enemigas situadas a alcance 1-3 y que tengan fichas de Tensión. Por cada nave elegida, puedes gastar 1 de Energía para que esa nave sufra 1 daño."""
"Shield Projector":
name: "Proyector de Escudos"
text: """Cuando una nave enemiga pase a ser la nave activa durante la fase de Combate, puedes gastar 3 de Energía para obligar a esa nave a atacarte (si puede) hasta el final de la fase."""
"Ion Pulse Missiles":
name: "Misiles de Pulso Iónico"
text: """<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta, el defensor sufre 1 daño y recibe 2 fichas de Iones. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Wingman":
name: "Nave de Escolta"
text: """Al comienzo de la fase de Combate, quita 1 ficha de tensión de otra nave aliada que tengas a alcance 1."""
"Decoy":
name: "Señuelo"
text: """Al comienzo de la fase de Combate, puedes elegir 1 nave aliada que tengas a alcance 1-2. Intercambia tu Habilidad de piloto por la Habilidad de piloto de esa nave hasta el final de la fase."""
"Outmaneuver":
name: "Superioridad Táctica"
text: """Cuando ataques a una nave situada dentro de tu arco de fuego, si tú no estás dentro del arco de fuego de esa nave, su Agilidad se reduce en 1 (hasta un mínimo de 0)."""
"Predator":
name: "Depredador"
text: """Cuando ataques, puedes volver a tirar 1 dado de ataque. Si la Habilidad del piloto defensor es 2 o menor, en vez de eso puedes volver a tirar hasta 2 dados de ataque."""
"Flechette Torpedoes":
name: "Torpedos de Fragmentación"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Después de que realices este ataque, el defensor recibe 1 ficha de Tensión si su Casco es de 4 o inferior."""
"R7 Astromech":
name: "Droide Astromecánico R7"
text: """Una vez por ronda cuando te defiendas, si tienes al atacante fijado como blanco, puedes gastar esa ficha de Blanco Fijado para elegir algunos o todos sus dados de ataque. El atacante debe volver a tirar los dados que hayas elegido."""
"R7-T1":
name: "R7-T1"
text: """<strong>Acción:</strong> Elije 1 nave enemiga a alcance 1-2. Si te encuentras dentro de su arco de fuego, puedes fijarla como blanco. Después puedes realizar una acción gratuita de impulso."""
"Tactician":
name: "Estratega"
text: """%LIMITED%%LINEBREAK%Después de que efectúes un ataque contra una nave que esté situada dentro de tu arco de fuego a alcance 2, esa nave recibe 1 ficha de Tensión."""
"R2-D2 (Crew)":
name: "R2-D2 (Tripulante)"
text: """Al final de la fase Final, si no tienes Escudos, puedes recuperar 1 de Escudos y tirar 1 dado de ataque. Si sacas %HIT%, pon boca arriba 1 de las cartas de Daño que tengas boca abajo (elegida al azar) y resuélvela."""
"C-3PO":
name: "C-3PO"
text: """Una vez por ronda, antes de que tires 1 o mas dados de defensa, puedes decir en voz alta cuántos resultados %EVADE% crees que vas a sacar. Si aciertas (antes de modificar los dados), añade 1 %EVADE% al resultado."""
"Single Turbolasers":
name: "Batería de Turboláseres"
text: """<strong>Ataque (Energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque. La Agilidad del defensor se duplica contra este ataque. Puedes cambiar 1 de tus resultados de %FOCUS% por 1 resultado de %HIT%."""
"Quad Laser Cannons":
name: "Cañones Láser Cuádruples"
text: """<strong>Ataque (Energía):</strong> Gasta 1 de Energía de esta carta para efectuar este ataque. Si no impacta, puedes gastar inmediatamente 1 de Energía de esta carta para repetir el ataque."""
"Tibanna Gas Supplies":
name: "Suministro de Gas Tibanna"
text: """<strong>Energía:</strong> Puedes descartar esta carta para obtener 3 de Energía."""
"Ionization Reactor":
name: "Reactor de Ionización"
text: """<strong>Energía:</strong> Gasta 5 de Energía de esta carta y descártala para para que todas las demás naves situadas a alcance 1 sufran 1 de daño y reciban 1 ficha de Iones."""
"Engine Booster":
name: "Motor Sobrepotenciado"
text: """Immediatamente antes de revelar tu selector de maniobras, puedes gastar 1 de Energía para ejecutar 1 maniobra blanca de (%STRAIGHT% 1). No puedes usar esta capacidad si al hacerlo te solapas con otra nave."""
"R3-A2":
name: "R3-A2"
text: """Cuando declares al objetivo de tu ataque, si el defensor está dentro de tu arco de fuego, puedes recibir 1 ficha de Tensión para hacer que el defensor reciba 1 ficha de Tensión."""
"R2-D6":
name: "R2-D6"
text: """Tu barra de mejoras gana el icono de mejora %ELITE%.<br /><br />No puedes equiparte esta mejora si ya tienes un icono de mejora %ELITE% o si la Habilidad de de tu piloto es de 2 o menos."""
"Enhanced Scopes":
name: "Radar Mejorado"
text: """La Habilidad de tu piloto se considera 0 durante la fase de Activación."""
"Chardaan Refit":
name: "Reequipado en Chardaan"
ship: "Ala-A"
text: """<span class="card-restriction">Solo Ala-A.</span><br /><br />Esta carta tiene un coste negativo en puntos de escuadrón."""
"Proton Rockets":
name: "Cohetes de Protones"
text: """<strong>Ataque (Concentración):</strong> Descarta esta carta para efectuar este ataque.<br /><br />Puedes tirar tantos dados de ataque adicionales como tu puntuación de Agilidad, hasta un máximo de 3 dados adicionales."""
"Kyle Katarn":
text: """Despues de que quites una ficha de Tensión de tu nave, puedes asiganar una ficha de Concentración a tu nave."""
"Jan Ors":
text: """Una vez por ronda, cuando una nave aliada que tengas a alcance 1-3 realice una accion de Concentración o vaya a recibir una ficha de Concentración, en vez de eso puedes asignarle a esa nave una ficha de Evasión."""
"Toryn Farr":
text: """<strong>Acción:</strong> Gasta cualquier cantidad de Energía para elegir ese mismo número de naves enemigas que tengas a alcance 1-2. Descarta todas las fichas de Concentración, Evasión y Blanco Fijado (azules) de las naves elegidas."""
# TODO Check card formatting
"R4-D6":
name: "R4-D6"
text: """Cuando seas alcanzado por un ataque y haya al menos 3 resultados %HIT% sin anular, puedes anular todos los que quieras hasta que solo queden 2. Recibes 1 ficha de Tensión por cada resultado que anules de este modo."""
"R5-P9":
name: "R5-P9"
text: """Al final de la fase de Combate, puedes gastar 1 de tus fichas de Concentración para recuperar 1 ficha de Escudos (hasta un máximo igual a tu puntuación de Escudos)."""
"WED-15 Repair Droid":
name: "Droide de Reparaciones WED-15"
text: """<strong>Acción:</strong> Gasta 1 de Energia para descartar 1 carta de Daño que tengas boca abajo, o bien gasta 3 de Energía para descartar 1 carta de Daño que tengas boca arriba."""
"Carlist Rieekan":
name: "Carlist Rieekan"
text: """Al pincipio de la fase de Activación, puedes descartar esta carta para que la Habilidad de todas tus naves se considere 12 hasta el final de la fase."""
"Jan Dodonna":
name: "Jan Dodonna"
text: """Cuando otra nave aliada que tengas a alcance 1 efectúe un ataque, podrá cambiar 1 de sus resultados de %HIT% por 1 resultado de %CRIT%."""
"Expanded Cargo Hold":
name: "Bodega de Carga Ampliada"
text: """<span class="card-restriction">Solo GR-75</span><br /><br />Una vez por ronda, cuando tengas que recibir una carta de Daño boca arriba, puedes robar esa carta del mazo de Daño de proa o del mazo de Daño de popa."""
ship: 'Transporte mediano GR-75'
"Backup Shield Generator":
name: "Generador de Escudos Auxiliar"
text: """Al final de cada ronda, puedes gastar 1 de Energía para recuperar 1 de Escudos (hasta el maximo igual a tu puntuación de Escudos)."""
"EM Emitter":
name: "Emisor de señal Electromagnética"
text: """Cuando obstruyas un ataque, el defensor tira 3 dados de defensa adicionales en vez de 1."""
"Frequency Jammer":
name: "Inhibidor de Frecuencias"
text: """Cuando lleves a cabo una acción de intereferencia, elige 1 nave enemiga que no tenga fichas de Tensión y se encuentre a alcance 1 de la nave interferida. La nave elegida recibe una ficha de Tension."""
"Han Solo":
name: "Han Solo"
text: """Cuando ataques, si tienes la defensor fijado como blanco, puedes gastar esa ficha de Blanco Fijado para cambiar todos tus resultados de %FOCUS% por resultados de %HIT%."""
"Leia Organa":
name: "Leia Organa"
text: """Al comienzo de la fase de Activación, puedes descartar esta carta para que todas las naves aliadas que muestren una maniobra roja seleccionada la traten como si fuera una maniobra blanca hasta el final de la fase."""
"Raymus Antilles":
name: "Raymus Antilles"
text: """Al comiuenzo de la fase de Activación, elige 1 nave enemiga que tengas a alcance 1-3. Puedes mirar su selector de maniobras. Si ha seleccionado una maniobra blanca, adjudica 1 ficha de Tensión a esa nave."""
"Gunnery Team":
name: "Dotación de Artillería"
text: """Una vez por ronda, cuando ataques con un armamento secudario, puedes gastar 1 de Energía para cambiar 1 cara de dado vacía por 1 resultado de %HIT%."""
"Sensor Team":
name: "Equipo de Control de Sensores"
text: """Cuando fijes un blanco, puedes fijar como blanco una nave enemiga a alcance 1-5 (en lugar de 1-3)."""
"Engineering Team":
name: "Equipo de Ingeniería"
text: """Durante la fase de Activación, si enseñas una maniobra %STRAIGHT%, recibes 1 de Energía adicional durante el paso de "Obtener Energía"."""
"Lando Calrissian":
name: "Lando Calrissian"
text: """<strong>Acción:</strong> Tira 2 dados de defensa. Por cada %FOCUS% que saques, asigna 1 ficha de Concentración a tu nave. Por cada resultado de %EVADE% que saques, asigna 1 ficha de Evasión a tu nave."""
"Mara Jade":
name: "Mara Jade"
text: """Al final de la fase de Combate, toda nave enemiga situada a alcance 1 que no tenga 1 ficha de Tensión recibe 1 ficha de Tensión."""
"Fleet Officer":
name: "Oficial de la Flota"
text: """<strong>Acción:</strong> Elige un máximo de 2 naves aliadas que tengas a alcance 1-2 y asigna 1 ficha de Concentración a cada una de ellas. Luego recibes 1 ficha de Tensión."""
"Lone Wolf":
name: "Lobo solitario"
text: """Cuando ataques o defiendas, si no tienes ninguna otra nave aliada a alcance 1-2, pues volver a tirar 1 dado en el que hayas sacado una cara vacía."""
"Stay On Target":
name: "Seguir al Objetivo"
text: """Cuando reveles una maniobra, puedes girar tu selector para escoger otra maniobra que tenga la misma velocidad.<br /><br />Tu maniobra se considera roja."""
"Dash Rendar":
text: """Puedes efectuar ataques mientras estés solapado con un obstáculo.<br /><br />Tus ataques no pueden ser obstruidos."""
'"Leebo"':
text: """<strong>Acción:</strong> Realiza una acción gratuita de Impulso. Después recibes 1 marcador de Iones."""
"Ruthlessness":
name: "Crueldad"
text: """Después de que efectúes un ataque que impacte, <strong>debes</strong> elegir otra nave situada a alcance 1 del defensor (exceptuando la tuya). Esa nave sufre 1 daño."""
"Intimidation":
name: "Intimidación"
text: """Mientras estes en contacto con una nave enemiga, la Agilidad de esa nave se reduce en 1."""
"Ysanne Isard":
text: """Al comienzo de la fase de Combate, si no te quedan Escudos y tu nave tiene asignada al menos 1 carta de Daño, puedes realizar una acción gratuita de Evasión."""
"Moff Jerjerrod":
text: """Cuando recibas una carta de Daño boca arriba, puedes descartar esta carta de Mejora u otra carta de %CREW% para poner boca abajo esa carta de Daño sin resolver su efecto."""
"Ion Torpedoes":
name: "Torpedos de Iones"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta, el defensor y toda nave que esté a alcance 1 reciben 1 ficha de Iones cada una."""
"Bomb Loadout":
name: "Compartimento de Bombas"
text: """<span class="card-restriction">Solo ala-Y.</span><br /><br />Tu barra de mejoras gana el icono %BOMB%."""
ship: "Ala-Y"
"Bodyguard":
name: "Guardaespaldas"
text: """%SCUMONLY%<br /><br />Al principio de la fase de Combate, puedes gastar 1 ficha de Concentración para elegir 1 nave aliada situada a alcance 1 cuyo piloto tenga una Habilidad más alta que la tuya. Hasta el final de la ronda, la puntuación de Agilidad de esa nave se incrementa en 1."""
"Calculation":
name: "Planificación"
text: """Cuando ataques, puedes gastar 1 ficha de Concentración para cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
"Accuracy Corrector":
name: "Corrector de Puntería"
text: """Cuando ataques, durante el paso "Modificar la tirada de ataque", puedes anular los resultados de todos tus dados. Después puedes añadir 2 resultados %HIT% a tu tirada.<br /><br />Si decides hacerlo, no podrás volver a modificar tus dados durante este ataque."""
"Inertial Dampeners":
name: "Amortiguadores de Inercia"
text: """Cuando reveles tu maniobra, puedes descartar esta carta para ejecutar en su lugar una maniobra blanca [0%STOP%]. Después recibes 1 ficha de Tensión."""
"Flechette Cannon":
name: "Cañón de Fragmentación"
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, el defensor sufre 1 de daño y, si no tiene asignada ninguna ficha de Tensión, recibe también 1 ficha de Tensión. Después se anulan <strong>todos</strong> los resultados de los dados."""
'"Mangler" Cannon':
name: 'Cañón "Mutilador"'
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Durante este ataque, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%."""
"Dead Man's Switch":
name: "Dispositivo de Represalia"
text: """Cuando seas destruido, toda nave que tengas a alcance 1 sufre 1 daño."""
"Feedback Array":
name: "Transmisor de Sobrecargas"
text: """Durante la fase de Combate, en vez de efectuar ataques, puedes recibir 1 ficha de Iones y sufrir 1 daño para elegir 1 nave enemiga a alcance 1. Esa nave sufre 1 daño."""
'"Hot Shot" Blaster':
name: "Cañón Bláster Desechable"
text: """<strong>Ataque:</strong> Descarta esta carta para atacar a 1 nave (aunque esté fuera de tu arco de fuego)."""
"Greedo":
text: """%SCUMONLY%<br /><br />La primera vez que ataques cada ronda y la primera vez que te defiendas cada ronda, la primera carta de Daño inflingida será asignada boca arriba."""
"Outlaw Tech":
name: "Técnico Clandestino"
text: """%SCUMONLY%<br /><br />Después de que ejecutes una maniobra roja, puedes asignar 1 ficha de Concentración a tu nave."""
"K4 Security Droid":
name: "Droide de Seguridad K4"
text: """%SCUMONLY%<br /><br />Después de que ejecutes una maniobra verde, puedes fijar un blanco."""
"Salvaged Astromech":
name: "Droide Astromecánico Remendado"
text: """Cuando recibas una carta de Daño boca arriba con el atributo <strong>Nave</strong>, puedes descartarla de inmediato (antes de resolver sus efectos).<br /><br />Luego descarta esta carta de Mejora."""
'"Genius"':
name: '"Genio"'
text: """Si estás equipado con una bomba que puede soltarse cuando revelas tu selector de maniobras, puedes elegir soltar la bomba <strong>después</strong> de ejecutar tu maniobra."""
"Unhinged Astromech":
name: "Droide Astromecánico Desquiciado"
text: """Puedes ejecutar todas las maniobras de velocidad 3 como maniobras verdes."""
"R4 Agromech":
name: "Droide Agromecánico R4"
text: """Cuando ataques, después de gastar una ficha de Concentración puedes fijar al defensor como blanco."""
"R4-B11":
text: """Cuando ataques, si tienes al defensor fijado como blanco, puedes gastar la ficha de Blanco Fijado para elegir cualquier o todos sus dados de defensa. El defensor debe volver a tirar los dados elegidos."""
"Autoblaster Turret":
name: "Torreta de Bláster Automático"
text: """<strong>Ataque:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).<br /><br />Tus resultados %HIT% no pueden ser anulados por los dados de defensa.<br /><br />El defensor puede anular tus resultados %CRIT% antes que los %HIT%."""
"Advanced Targeting Computer":
ship: "TIE Avanzado"
name: "Computadora de Selección de Blancos Avanzada"
text: """<span class="card-restriction">Solo TIE Avanzado.</span>%LINEBREAK%Cuando ataques con tu armamento principal, si tienes al defensor fijado como blanco, puedes añadir 1 %CRIT% al resultado de tu tirada. Si decides hacerlo, no podrás gastar fichas de Blanco Fijado durante este ataque."""
"Ion Cannon Battery":
name: "Batería de Cañones de Iones"
text: """<strong>Ataque (Energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque. Si este ataque impacta, el defensor sufre 1 de daño crítico y recibe 1 ficha de Iones. Después se anulan <strong>todos<strong> los resultados de los dados."""
"Emperor Palpatine":
name: "Emperador Palpatine"
text: """%IMPERIALONLY%%LINEBREAK%Una vez por ronda, antes de que una nave aliada vaya a tirar dados, puedes decir un resultado de dado. Tras tirarlos, se debe cambiar 1 de los resultados obtenidos por el resultado elegido antes. El resultado de ese dado no podrá volver a ser modificado."""
"Bossk":
text: """%SCUMONLY%%LINEBREAK%Después de que realices un ataque y falles, si no tienes fichas de Tensión <strong>debes</strong> recibir 1 ficha de Tensión. Después asigna 1 ficha de Concentración a tu nave y fija al defensor como blanco."""
"Lightning Reflexes":
name: "Reflejos Rápidos"
text: """%SMALLSHIPONLY%%LINEBREAK%Después de que ejecutes una maniobra blanca o verde en tu selector, puedes descartar esta carta para rotar tu nave 180º. Luego recibes 1 ficha de Tensión <strong>después</strong> del paso de "comprobar Tensión del piloto."""
"Twin Laser Turret":
name: "Torreta Láser Doble"
text: """<strong>Ataque:</strong> Efectúa este ataque <strong>dos veces</strong> (incluso contra una nave situada fuera de tu arco de fuego).<br /><br />Cada vez que este ataque impacte, el defensor sufre 1 de daño. Luego se anulan <strong>todos</strong> los resultados de los dados."""
"Plasma Torpedoes":
name: "Torpedos de Plasma"
text: """<strong>Ataque (Blanco fijado):</strong> Gasta tu ficha de Blanco fijado y descarta esta carta para efectuar este ataque.<br /><br />Si el ataque impacta, después de inflingir daños quita 1 ficha de Escudos del defensor."""
"Ion Bombs":
name: "Bombas de Iones"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Bomba de iones.<br /><br />Esta ficha <strong>detona</strong> al final de la fase de Activación.<br /><br /><strong>Ficha de Bomba de iones:</strong> Cuando se detona esta ficha de Bomba, toda nave que se encuentre a alcance 1 de ella recibe 2 fichas de Iones. Después se descarta esta ficha."""
"Conner Net":
name: "Red Conner"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Red Conner.<br /><br />Esta ficha se <strong>detona</strong> cuando la peana o plantilla de maniobra de una nave se solape con ella.<br /><br /><strong>Ficha de Red Conner:</strong> Cuando es detona esta ficha de Bomba, la nave que la haya atravesado o solapado sufre 1 daño, recibe 2 fichas de Iones y se salta su paso de "Realizar una acción". Después se descarta esta ficha."""
"Bombardier":
name: "Bombardero"
text: """Cuando sueltes una bomba, puedes usar la plantilla (%STRAIGHT% 2) en lugar de la plantilla (%STRAIGHT% 1)."""
"Cluster Mines":
name: "Minas de Racimo"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 conjunto de Minas de racimo.<br /><br />Cada ficha de Mina de racimo se <strong>detona</strong> cuando la peana o plantilla de maniobra de una nave se solapa con ella.<br /><br /><strong>Ficha de Mina de racimo:</strong> Cuando se detona una de estas fichas de Bomba, la nave que la haya atravesado o solapado tira 2 dados de ataque y sufre 1 punto de daño por cada %HIT% o %CRIT% obtenido en la tirada. Después se descarta esta ficha."""
'Crack Shot':
name: "Tiro Certero"
text: '''Cuando ataques a una nave situada dentro de tu arco de fuego, al comienzo del paso "Comparar los resultados", puedes descartar esta carta para anular 1 resultado %EVADE% del defensor.'''
"Advanced Homing Missiles":
name: "Misiles Rastreadores Avanzados"
text: """<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efectuar este ataque.%LINEBREAK%Si el ataque impacta, inflinge 1 carta de Daño boca arriba al defensor. Luego se anulan <strong>todos</strong> los resultados de los dados."""
'Agent Kallus':
name: "Agente Kallus"
text: '''%IMPERIALONLY%%LINEBREAK%Al comienzo de la primera ronda, elige 1 nave enemiga pequeña o grande. Cuando ataques a esa nave o te defiendas de esa nave, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%.'''
'XX-23 S-Thread Tracers':
name: "Hiperrastreadores XX-23"
text: """<strong>Ataque (Concentración):</strong> Descarta esta carta para efectuar este ataque. Si este ataque impacta, toda nave aliada que tengas a alcance 1-2 puede fijar al defensor como blanco. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Tractor Beam":
name: "Proyector de Campo de Tracción"
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, el defensor recibe 1 ficha de Campo de Tracción. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Cloaking Device":
name: "Dispositivo de Camuflaje"
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Acción:</strong> Realiza una acción gratuita de camuflaje.%LINEBREAK%Al final de cada ronda, si estás camuflado, tira 1 dado de ataque. Si sacas %FOCUS%, descarta esta carta y luego elige entre desactivar el camuflaje o retirar tu ficha de Camuflaje."""
"Shield Technician":
name: "Técnico de Escudos"
text: """%HUGESHIPONLY%%LINEBREAK%Cuando lleves a cabo una acción de recuperación, en vez de retirar todas tus fichas de Energía, puedes elegir qué cantidad de fichas de Energía deseas retirar."""
"Grand Moff Tarkin":
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Al comienzo de la fase de Combate, puedes elegir otra nave que tengas a alcance 1-4. Escoge entre retirar 1 ficha de Concentración de la nave elegida o asignarle 1 ficha de Concentración a esa nave."""
"Captain Needa":
name: "Capitán Needa"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Si durante la fase de Activación te solapas con un obstáculo, en vez de recibir 1 carta de Daño boca arriba, tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, sufres 1 de daño."""
"Admiral Ozzel":
name: "Almirante Ozzel"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%<strong>ENERGÍA</strong>: Puedes descartar hasta 3 fichas de Escudos de tu nave. Por cada ficha de Escudos descartada, obtienes 1 de Energía."""
'Glitterstim':
name: "Brillestim"
text: """Al comienzo de la fase de Combate, puedes descartar esta carta y recibir 1 ficha de Tensión. Si lo haces, hasta el final de la ronda, cuando ataques o defiendes puedes cambiar todos tus resultados %FOCUS% por resultados %HIT% o %EVADE%."""
'Extra Munitions':
name: "Munición Adicional"
text: """Cuando te equipas con esta carta, coloca 1 ficha de Munición de artillería sobre cada carta de Mejora %TORPEDO%, %MISSILE% y %BOMB% que tengas equipada. Cuando se te indique que descartes una carta de Mejora, en vez de eso puedes descartar 1 ficha de Munición de artillería que haya encima de esa carta."""
"Weapons Guidance":
name: "Sistema de Guiado de Armas"
text: """Cuando ataques, puedes gastar una ficha de Concentración para cambiar 1 de tus resultados de cara vacia por un resultado %HIT%."""
"BB-8":
text: """Cuando reveles una maniobra verde, puedes realizar una acción gratuita de tonel volado."""
"R5-X3":
text: """Antes de revelar tu maniobra, puedes descartar esta carta para ignorar todos los obstáculos hasta el final de la ronda."""
"Wired":
name: "Enardecido"
text: """Cuando ataques o te defiendas, si estás bajo tensión, puedes volver a tirar 1 o más de tus resultados %FOCUS%."""
'Cool Hand':
name: "Mano Firme"
text: '''Cuando recibas una ficha de Tensión, puedes descartar esta carta para asignar 1 ficha de Concetración o de Evasión a tu nave.'''
'Juke':
name: "Finta"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando ataques, si tienes una ficha de Evasión, puedes cambiar 1 de los resultados %EVADE% del defensor por un resultado %FOCUS%.'''
'Comm Relay':
name: "Repetidor de Comunicaciones"
text: '''No puedes tener más de 1 ficha de Evasión.%LINEBREAK%Durante la fase Final, no retires de tu nave las fichas de Evasión que no hayas usado.'''
'Dual Laser Turret':
text: '''%GOZANTIONLY%%LINEBREAK%<strong>Attack (energy):</strong> Spend 1 energy from this card to perform this attack against 1 ship (even a ship outside your firing arc).'''
'Broadcast Array':
text: '''%GOZANTIONLY%%LINEBREAK%Your action bar gains the %JAM% action icon.'''
'Rear Admiral Chiraneau':
text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Execute a white (%STRAIGHT% 1) maneuver.'''
'Ordnance Experts':
text: '''Once per round, when a friendly ship at Range 1-3 performs an attack with a %TORPEDO% or %MISSILE% secondary weapon, it may change 1 of its blank results to a %HIT% result.'''
'Docking Clamps':
text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%You may attach 4 up to TIE fighters, TIE interceptors, TIE bombers, or TIE Advanced to this ship. All attached ships must have the same ship type.'''
'"Zeb" Orrelios':
text: """%REBELONLY%%LINEBREAK%Las naves enemigas dentro de tu arco de fuego que estén en contacto contigo no se consideran en contacto contigo cuando tú o ellas os activéis durante la fase de Combate."""
'Kanan Jarrus':
text: """%REBELONLY%%LINEBREAK%Una vez por ronda, después de que una nave aliada que tengas a alcance 1-2 ejecute una maniobra blanca, puedes quitar 1 ficha de Tensión de esa nave."""
'Reinforced Deflectors':
name: "Deflectores Reforzados"
text: """%LARGESHIPONLY%%LINEBREAK%Tras defenderte, su durante el ataque has sufrido una combinación de 3 o más puntos de daño normal y crítico, recuperas 1 ficha de Escudos (hast aun máximo igual a tu valor de Escudos)."""
'Dorsal Turret':
name: "Torreta Dorsal"
text: """<strong>Ataque:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).%LINEBREAK%Si el objetivo de este ataque está a alcance 1, tiras 1 dado de ataque adicional."""
'Targeting Astromech':
name: "Droide Astromecánico de Selección de Blancos"
text: '''Después de que ejecutes una maniobra roja, puedes fijar un blanco.'''
'Hera Syndulla':
text: """%REBELONLY%%LINEBREAK%Puedes revelar y ejectuar maniobras rojas incluso aunque estés bajo tensión."""
'Ezra Bridger':
text: """%REBELONLY%%LINEBREAK%Cuando ataques, si estás bajo tensión puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
'Sabine Wren':
text: """%REBELONLY%%LINEBREAK%Tu barra de mejoras gana el icono %BOMB%. Una vez por ronda, antes de retirar una ficha de Bomba aliada, elige 1 nave enemiga situada a Alcance 1 de esa ficha. Esa nave sufre 1 de daño."""
'"Chopper"':
text: """%REBELONLY%%LINEBREAK%Puedes realizar acciones incluso aunque estés bajo tensión.%LINEBREAK%Después de que realices una acción mientras estás bajo tensión, sufres 1 de daño."""
'Construction Droid':
text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%When you perform a recover action, you may spend 1 energy to discard 1 facedown Damage card.'''
'Cluster Bombs':
text: '''After defending, you may discard this card. If you do, each other ship at Range 1 of the defending section rolls 2 attack dice, suffering all damage (%HIT%) and critical damage (%CRIT%) rolled.'''
"Adaptability":
name: "Adaptabilidad"
text: """<span class="card-restriction">Carta dual.</span>%LINEBREAK%<strong>Cara A:</strong> La Habilidad de tu piloto se incrementa en 1.%LINEBREAK%<strong>Cara B:</strong> La habilidad de tu piloto se reduce en 1."""
"Electronic Baffle":
name: "Regulador Electrónico"
text: """Cuando recibas una ficha de Tensión o una ficha de Iones, puedes sufrir 1 de daño para descartar esa ficha."""
"4-LOM":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, durante el paso "Modificar la tirada de ataque" puedes recibir 1 ficha de Iones para elegir 1 de las fichas de Concentración o Evasión del defensor. Esa ficha no se puede gastar durante este ataque."""
"Zuckuss":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, si no estás tensionado, puedes recibir tantas fichas de Tensión como quieras para elegir una cantidad igual de dados de defensa. El defensor debe volver a tirar esos dados."""
'Rage':
name: "Furia"
text: """<strong>Acción:</strong> Asigna 1 ficha de Concentración a tu nave y recibe 2 fichas de Tensión. Hasta el final de la ronda, cuando ataques puedes volver a tirar hasta 3 dados de ataque."""
"Attanni Mindlink":
name: "Enlace Mental Attani"
text: """%SCUMONLY%%LINEBREAK%Cada vez que se te asigne una ficha de Concentración o de Tensión, a todas las demás naves aliadas equipadas con "Enlace Mental Attani" se les debe asignar también una ficha de ese mismo tipo si es que no tienen ya una."""
"Boba Fett":
text: """%SCUMONLY%%LINEBREAK%Después de que efectúes un ataque, si al defensor se le infligió una carta de Daño boca arriba, puedes descartar esta carta para elegir y descartar 1 de las cartas de Mejora del defensor."""
"Dengar":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, puedes volver a tirar 1 dado de ataque. Si el defensor es un piloto único, en vez de eso puedes volver a tirar hasta 2 dados de ataque."""
'"Gonk"':
name: '"Gonk"'
text: """%SCUMONLY%%LINEBREAK%<strong>Acción:</strong> Coloca 1 ficha de Escudos sobre esta carta.%LINEBREAK%<strong>Acción:</strong> Quita 1 ficha de Escudos de esta carta para recupera 1 de Escudos (hast aun máximo igual a tu valor de Escudos)."""
"R5-P8":
text: """Una vez por ronda, después de que te defiendas puedes volver a tirar 1 dado de ataque. Si sacas %HIT%, el atacante sufre 1 de daño. Si sacas %CRIT%, tanto tú como el atacante sufrís 1 de daño."""
'Thermal Detonators':
name: "Detonadores Térmicos"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Detonador térmico.%LINEBREAK%Esta ficha se <strong>detona</strong> al final de la fase de Activación.%LINEBREAK%<strong>Ficha de Detonador Térmico:</strong> Cuando esta bomba detona, cada nave a Alcance 1 de la ficha sufre 1 de daño y recibe 1 ficha de tensión. Después, descarta esta ficha."""
"Overclocked R4":
name: "Droide R4 trucado"
text: """Durante la fase de Combate, cuando gastes una ficha de Concentración puedes recibir 1 ficha de Tensión para asignar 1 ficha de Concentración a tu nave."""
'Systems Officer':
name: "Oficial de Sistemas"
text: '''%IMPERIALONLY%%LINEBREAK%Después de que ejecutes una maniobra verde, elige otra nave aliada que tengas a alcance 1. Esa nave puede fijar un blanco.'''
'Tail Gunner':
name: "Artillero de cola"
text: '''Cuando ataques desde tu arco de fuego auxiliar trasero, la Agilidad del defensor se reduce en 1 (hasta un mínimo de 0).'''
'R3 Astromech':
name: "Droide astromecánico R3"
text: '''Una vez por ronda, cuando ataques con un armamento principal, durante el paso "Modificar la tirada de ataque" puedes anular 1 de tus resultados %FOCUS% para asignar 1 ficha de Evasión a tu nave.'''
'Collision Detector':
name: "Detector de colisiones"
text: '''Cuando realices un impulso, un tonel volado o desactives tu camuflaje, tu nave y plantilla de maniobra se pueden solapar con obstáculos.%LINEBREAK%Cuando hagas una tirada de dados para determinar el daño causado por obstáculos, ignora todos tus resultados %CRIT%.'''
'Sensor Cluster':
name: "Conjunto de sensores"
text: '''Cuando te defiendas, puedes gastar una ficha de Concentración para cambiar 1 de tus resultados de car avacía por 1 resultado %EVADE%.'''
'Fearlessness':
name: "Intrepidez"
text: '''%SCUMONLY%%LINEBREAK%Cuando ataques, si estás dentro del arco de fuego del defensor a alcance 1 y el defensor está dentro de tu arco de fuego, puedes añadir 1 resultado %HIT% a tu tirada.'''
'Ketsu Onyo':
text: '''%SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes elegir 1 nave enemiga que tengas dentro de tu arco de fuego a alcance 1-2. Esa nave no retira sus fichas de Campo de tracción.'''
'Latts Razzi':
text: '''%SCUMONLY%%LINEBREAK%Cuando te defiendas, puedes quitarle al atacante 1 ficha de Tensión para añadir 1 resultado 1 %EVADE% a tu tirada.'''
'IG-88D':
text: '''%SCUMONLY%%LINEBREAK%Tu piloto tiene la misma capacidad especial que cualquier otra nave aliada equipada con la carta de Mejora <em>IG-2000</em> (además de su propia capacidad especial).'''
'Rigged Cargo Chute':
name: "Tolva de evacuación de carga"
text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Cargamento.'''
'Seismic Torpedo':
name: "Torpedo sísmico"
text: '''<strong>Acción:</strong> Descarta esta carta para elegir un obstáculo que tengas a alcance 1-2 y dentro de tu arco de fuego normal. Toda nave situada a alcance 1 del obstáculo tira 1 dado de ataque y sufre cualquier daño (%HIT%) o o daño crítico (%CRIT%) otenido. Luego retira el obstáculo.'''
'Black Market Slicer Tools':
name: "Sistemas ilegales de guerra electrónica"
text: '''<strong>Acción:</strong> Elige una nave enemiga bajo tensión que tengas a alcance 1-2 y tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, quítale 1 ficha de Tensión e inflíngele 1 carta de Daño boca abajo.'''
# Wave X
'Kylo Ren':
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Acción:</strong> Asigna la carta de Estado "Yo re mostraré el Lado Oscuro" a una nave enemiga que tengas a alcance 1-3.'''
'Unkar Plutt':
text: '''%SCUMONLY%%LINEBREAK%Después de que ejecutes una maniobra que te haga solaparte con una nave enemiga, puedes sufrir 1 de daño para realizar 1 acción gratuita.'''
'A Score to Settle':
name: "Una cuenta pendiente"
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", elige 1 nave enemiga y asígnale la carta de Estado "Una deuda por saldar"%LINEBREAK%Cuando ataques a una nave que tiene asignada la carta de Estado "Una deuda por saldar", puedes cambair 1 resultado %FOCUS% por un resultado %CRIT%.'''
'Jyn Erso':
text: '''%REBELONLY%%LINEBREAK%<strong>Acción:</strong> Elige 1 nave aliada que tengas a alcance 1-2. Asigna 1 ficha de Concentración a esa nave por cada nave enemiga que tengas dentro de tu arco de fuego a alcance 1-3. No puedes asignar más de 3 fichas de esta forma.'''
'Cassian Andor':
text: '''%REBELONLY%%LINEBREAK%Al final de la fase de Planificación, puedes elegir una nave enemiga que tengas a alcance 1-2. Di en voz alta la dirección y velocidad que crees que va a tener esa nave, y luego mira su selector d emaniobras. Si aciertas, puedes girar la rueda de tu selector para asignarle otra maniobra.'''
'Finn':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques con un armamento principal o te defiendas, si la nave enemiga está dentro de tu arco de fuego, puedes añadir 1 resultado de cara vacía a tu tirada.'''
'Rey':
text: '''%REBELONLY%%LINEBREAK%Al comienzo de la fase Final, puedes colocar 1 de las fichas de Concentración de tu nave sobre esta carta. Al comienzo de la fase de Combate, puedes asignar 1 de esas fichas a tu nave.'''
'Burnout SLAM':
name: "Superacelerador de emergencia"
text: '''%LARGESHIPONLY%%LINEBREAK%Tu barra de acciones gana el icono %SLAM%.%LINEBREAK%Después de que realices una acción de MASA, descarta esta carta.'''
'Primed Thrusters':
name: "Propulsores sobrealimentados"
text: '''%SMALLSHIPONLY%%LINEBREAK%Las fichas de Tensión no te impiden realizar acciones de impulso o de tonel volado a menos que tengas asignadas 3 fichas de Tensión o más.'''
'Pattern Analyzer':
name: "Analizador de patrones"
text: '''Cuando ejecutes una maniobra, puedes resolver el paso "Comprobar Tensión del piloto" después del paso "Realizar una acción" (en vez de antes de ese paso).'''
'Snap Shot':
name: "Disparo de reacción"
text: '''Después de que una nave enemiga ejecute una maniobra, puedes efectuar este ataque contra esa nave. <strong>Ataque:</strong> Ataca a 1 nave. No puedes modificar tus dados de ataque y no puedes volver a atacar en esta fase.'''
'M9-G8':
text: '''%REBELONLY%%LINEBREAK%Cuando una nave que tengas fijada como blanco esté atacando, puedes elegir 1 dado de ataque. El atacante debe volver a tirar ese dado.%LINEBREAK%Puedes fijar como blanco otras naves aliadas.'''
'EMP Device':
name: "Dispositivo de pulso electromagnético"
text: '''Durante la fase de Combate, en vez de efecturas ningún ataque, puedes descartar esta carta para asignar 2 fichas de Iones a toda nave que tengas a alcance 1.'''
'Captain Rex':
name: "Capitán Rex"
text: '''%REBELONLY%%LINEBREAK%Después de que efectúes un ataque no impacte, puedes asignar 1 ficha de Concentración a tu nave.'''
'General Hux':
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Acción:</strong> Elige hasta 3 naves aliadas que tengas a alcance 1-2. Asigna 1 ficha de Concentración a cada una de esas naves y asigna la carta de Estado "Lealtad fanática" a 1 de ellas. Luego recibes 1 ficha de Tensión.'''
'Operations Specialist':
name: "Especialista en operaciones"
text: '''%LIMITED%%LINEBREAK%Después de que una nave aliada que tengas a alcance 1-2 efectúe un ataque que no impacte, puedes asignar 1 ficha de Concentración a una nave aliada situada a alcance 1-3 del atacante.'''
'Targeting Synchronizer':
name: "Sincronizador de disparos"
text: '''Cuando una nave aliada que tengas a alcance 1-2 ataque a una nave que tienes fijada como blanco, esa nave aliada considera el encabezado "<strong>Ataque (Blanco fijado):</strong> como si fuera "<strong>Ataque:</strong>." Si un efecto de juego indica a esa nave que gaste una ficha de Blanco fijada, en vez de eso puede gastar tu ficha de Blanco fijado.'''
'Hyperwave Comm Scanner':
name: "Escáner de frecuencias hiperlumínicas"
text: '''Al comienzo del paso "Desplegar fuerzas", puedes elegir considerar la Habilidad de tu piloto como si fuera 0, 6 o 12 hasta el final del paso. Durante la preparación de la partida, después de que otra nave aliada sea colocada a alcance 1-2 de ti, puedes asignar 1 ficha de Concentración o Evasión a esa nave.'''
'Trick Shot':
name: "Disparo inverosímil"
text: '''Cuando ataques, si el ataque se considera obstruido, puedes tirar 1 dado de ataque adicional.'''
'Hotshot Co-pilot':
name: "Copiloto extraordinario"
text: '''Cuando ataques con un armamento princnipal, el defensor debe gastar 1 ficha de Concentración si le es posible.%LINEBREAK%Cuando te defiendas, el atacante debe gastar 1 ficha de Concentración si le es posible.'''
'''Scavenger Crane''':
name: "Grúa de salvamento"
text: '''Después de que una nave que tengas a alcance 1-2 sea destruida, puedes elegir una carta de Mejora %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, o Modificación que estuviera equipada en tu nave y ponerla boca arriba. Luego tira 1 dado de ataque. Si sacas una cara vacía, descarta tu "Grúa de salvamento".'''
'Bodhi Rook':
text: '''%REBELONLY%%LINEBREAK%Cuando fijes un blanco, puedes fijarlo sobre una nave enemiga que esté situada a alcance 1-3 de cualquier nave aliada.'''
'Baze Malbus':
text: '''%REBELONLY%%LINEBREAK%Después de que efectúes un ataque que no impacte, puedes realizar inmediatamente un ataque con tu armamento principal contra una nave diferente. No podrás realizar ningún otro ataque en esta misma ronda.'''
'Inspiring Recruit':
name: "Recluta inspirador"
text: '''Una vez por ronda, cuando una nave aliada que tengas a alcance 1-2 se quite una ficha de Tensión, puede quitarse 1 ficha de Tensión adicional.'''
'Swarm Leader':
name: "Jefe de enjambre"
text: '''Cuando ataques con un armamento principal, elige hasta 2 ortas naves aliadas que tengan al defensor dentro de sus arcos de fuego a alcance 1-3. Quita 1 ficha de Evasión de cada nave elegida para tirar 1 dado de ataque adicional por cada ficha quitada.'''
'Bistan':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques a alcance 1-2, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%.'''
'Expertise':
name: "Maestría"
text: '''Cuando ataques, si no estás bajo tensión, puedes cambair todos tus resultados %FOCUS% por resultados %HIT%.'''
'BoShek':
text: '''Cuando una nave con la que estás en contacto se activa, puedes mirar la maniobra que ha elegido. Si lo haces, el jugador que controla esa nave <strong>debe</strong> elegir en el selector una maniobra adyacente. La nave puede revelar y efectuar esa maniobra incluso aunque esté bajo tensión.'''
# C-ROC
'Heavy Laser Turret':
ship: "Crucero C-ROC"
name: "Torreta de láser pesado"
text: '''<span class="card-restriction">Sólo crucero C-ROC</span>%LINEBREAK%<strong>Ataque (energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque contra 1 nave (incluso contra una nave fuera de tu arco de fuego).'''
'Cikatro Vizago':
text: '''%SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes descartar esta carta pare reemplazar una carta de Mejora %ILLICIT% o %CARGO% que tengas equipada boca arriba por otra carta de Mejora de ese mismo tipo con un coste en puntos de escuadrón igual o inferior.'''
'Azmorigan':
text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes gastar 1 de Energía para reemplazar una carta de Mejora %CREW% o %TEAM% que tengas equipada boca arriba por otra carta de Mejora de ese mismo tipo con un coste en puntos de escuadrón igual o inferior.'''
'Quick-release Cargo Locks':
name: "Enganches de carga de apertura rápida"
text: '''%LINEBREAK%Al final de la fase de Activación puedes descartar esta carta para <strong>colocar</strong> 1 indicador de Contenedores.'''
'Supercharged Power Cells':
name: "Células de energía sobrealimentadas"
text: '''Cuando ataques, puedes descartar esta carta para tirar 2 dados de ataque adicionales.'''
'ARC Caster':
name: "Proyector ARC"
text: '''<span class="card-restriction">Sólo Escoria y Rebelde.</span>%DUALCARD%%LINEBREAK%<strong>Cara A:</strong>%LINEBREAK%<strong>Ataque:</strong> Ataca a 1 nave. Si este ataque impacta, debes elegir 1 otra nave a alcance 1 del defensor para que sufra 1 punto de daño.%LINEBREAK%Luego dale la vuelta a esta carta.%LINEBREAK%<strong>Cara B:</strong>%LINEBREAK%(Recargándose) Al comienzo de la fase de Combate, puedes recibir una ficha de Armas inutilizadas para darle la vuelta a esta carta.'''
'Wookiee Commandos':
name: "Comandos wookiees"
text: '''Cuando ataques, puedes volver a tirar tus resultados %FOCUS%.'''
'Synced Turret':
name: "Torreta sincronizada"
text: '''<strong>Ataque (Blanco fijado:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).%LINEBREAK%Si el defensor está dentro de tu arco de fuego principal, puedes volver a tirar tantos dados de ataque como tu valor de Armamento principal.'''
'Unguided Rockets':
name: "Cohetes no guiados"
text: '''<strong>Ataque (Concentración):</strong> Ataca a 1 nave.%LINEBREAK%Tus dados de ataque solo pueden ser modificados mediante el gasto de una ficha de Concentración para su efecto normal.'''
'Intensity':
name: "Ímpetu"
text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Cara A:</strong> Después de que realices una acción de impulso o de tonel volado, puedes asignar 1 ficha de Concentración o de Evasión a tu nave. Si lo haces, dale la vuelta a esta carta.%LINEBREAK%<strong>Cara B:</strong> (Agotada) Al final de la fase de Combate, puedes gasta 1 ficha de Concentración o de Evasión para darle la vuelta a esta carta.'''
'Jabba the Hutt':
name: "Jabba el Hutt"
text: '''%SCUMONLY%%LINEBREAK%Cuando equipes esta carta, coloca 1 ficha de Material Ilícito encima de cada carta de Mejora %ILLICIT% en tu escuadrón. Cuando debas descartar una carta de Mejora, en vez de eso puedes descartar 1 ficha de Material ilícito que esté encima de esa carta.'''
'IG-RM Thug Droids':
name: "Droides matones IG-RM"
text: '''Cuando ataques, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%.'''
'Selflessness':
name: "Autosacrificio"
text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%Cuando una nave aliada que tengas a alcance 1 sea impactada por un ataque, puedes descartar esta carta para sufrir todos los resultados %HIT% no anulados en vez de la nave objetivo.'''
'Breach Specialist':
name: "Especialista en brechas"
text: '''Cuando recibas una carta de Daño boca arriba, puedes gastar 1 ficha de Refuerzo para darle la vuelta y ponerla boca abajo (sin resolver su efecto). Si lo haces, hasta el final de la ronda, cuando recibas una carta de Daño boca arriba, dale la vuelta par aponerla boca abajo (sin resolver su efecto).'''
'Bomblet Generator':
name: "Generador de minibombas"
text: '''Cuando reveles tu maniobra, puedes <strong>soltar</strong> 1 ficha de Minibomba%LINEBREAK%Esta ficha se <strong>detona</strong> al final de la fase de Activación.%LINEBREAK%<strong>Ficha de Minibomba:</strong> Cuando esta ficha detone, cada nave a Alcance 1 tira 2 dados de ataque y sufre todo el daño (%HIT%) y daño crítico (%CRIT%) obtenido en la tirada. Después se descarta esta ficha.'''
'Cad Bane':
text: '''%SCUMONLY%%LINEBREAK%Tu barra de mejoras gana el icono %BOMB%. Una vez por ronda, cuando una nave enemiga tire dados de ataque debido a la detonación de una bomba aliada, puedes elegir cualquier cantidad de resultados %FOCUS% y de cara vacía. La nave enemiga debe volver a tirar esos resultados.'''
'Minefield Mapper':
name: "Trazador de campos de minas"
text: '''Durante la preparación de la partida, después del paso "Desplegar fuerzas", puedes descartar cualquier cantidad de tus cartas de Mejora %BOMB% equipadas. Coloca las correspondientes fichas de Bomba en la zona de juego más allá de alcance 3 de las naves enemigas.'''
'R4-E1':
text: '''Puedes realizar acciones que figuren en tus cartas de Mejora %TORPEDO% y %BOMB% incluso aunque estés bajo tensión. Después de que realices una acción de esta manera, puedes descartar esta carta para retirar 1 ficha de Tensión de tu nave.'''
'Cruise Missiles':
name: "Misiles de crucero"
text: '''<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque. %LINEBREAK%Puedes tirar tantos dados de ataque adicionales como la velocidad de la maniobra que has ejecutado en esta ronda, hasta un máximo de 4 dados adicionales.'''
'Ion Dischargers':
name: "Descargadores de iones"
text: '''Después de que recibas una ficha de Iones, puedes elegir una nave enemiga que tengas a alcance 1. Si lo haces retira esa ficha de Iones. A continuación, esa nave puede elegir recibir 1 ficha de Iones. Si lo hace, descarta esta carta.'''
'Harpoon Missiles':
name: "Misiles arpón"
text: '''<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efcetuar este ataque.%LINEBREAK%Si este ataque impacta, después de resolver el ataque, asigna el estado "¡Arponeado!" al defensor.'''
'Ordnance Silos':
name: "Silos de munición"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando te equipes con esta carta, coloca 3 fichas de Munición de artillería encima de cada otra carta de mejora %BOMB% que tengas equipada. Cuando debas descartar una carta de Mejora, en vez de eso puedes descartar 1 ficha de Munición de artillería que esté encima de esa carta.'''
'Trajectory Simulator':
name: "Simulador de trayectorias"
text: '''Puedes lanzar bombas utilizando la plantilla de maniobra (%STRAIGHT% 5) en vez de soltarlas. No puedes lanzar de esta manera bombas que tengan el encabezado "<strong>Acción:</strong>".'''
'Jamming Beam':
name: "Haz de interferencias"
text: '''<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, asígnale al defensor 1 ficha de Interferencia. Luego se anulan <strong>todos</strong> los resultados de los dados.'''
'Linked Battery':
name: "Batería enlazada"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando ataques con tu armament principal o con un armamento secundario %CANNON%, puedes volver a tirar 1 dado de ataque.'''
'Saturation Salvo':
name: "Andanada de saturación"
text: '''Después de que efectúes un ataque con un armamento secundario %TORPEDO% o %MISSILE% que no impacte, toda nave que esté situada a alcance 1 del defensor y que tenga una puntuación de Agilidad inferior al coste en puntos de escuadrón de la carta de Meora %TORPEDO% o %MISSILE% debe tirar 1 dado de ataque y sufrir cualquier daño normal (%HIT%) o daño crítico (%CRIT%) obtenido.'''
'Contraband Cybernetics':
name: "Ciberimplantes ilícitos"
text: '''Cuando pases a ser la nave activa durante la fase de Activación, puedes descartar esta carta y recibir 1 ficha de Tensión. Si lo haces, hasta el final de la ornda, puedes llevar a cabo acciones y maniobras rojas incluso aunque estés bajo tensión.'''
'Maul':
text: '''%SCUMONLY% <span class="card-restriction">Ignora esta restricción si tu escuadrón contiene a "Ezra Bridger."</span>%LINEBREAK%Cuando ataques, si no estás bajo tensión, puedes recibir cualquier cantidad de fichas de Tensión para volver a tirar esa misma cantidad de dados de ataque.%LINEBREAK% Después de que realices un ataque que impacte, puedes retirar 1 de tus fichas de Tensión.'''
'Courier Droid':
name: "Droide mensajero"
text: '''Al comienzo del paso "Desplegar fuerzas", puedes elegir que la puntuación de Habilidad de tu piloto se considere 0 u 8 hasta el final de este paso.'''
'"Chopper" (Astromech)':
text: '''<strong>Acción: </strong>Descarta 1 de tus otras cartas de Mejora equipadas para recuperar 1 ficha de Escudos.'''
'Flight-Assist Astromech':
name: "Droide astromecánico de ayuda al pilotaje"
text: '''No puedes efectuar ataques ataques contra naves que estén situadas fuera de tu arco de fuego.%LINEBREAK%Después de que ejecutes una maniobra, si no te has solapado con una nave ni con un obstáculo, y no tienes ninguna nave enemiga a alcance 1-3 situada dentro de tu arco de fuego, puedes realizar una acción gratuita de impulso o tonel volado.'''
'Advanced Optics':
name: "Sensores ópticos avanzados"
text: '''No puedes tener más de 1 ficha de Concentración.%LINEBREAK%Durante la fase Final, no retires de tu nave las fichas de Concentración que no hayas usado.'''
'Scrambler Missiles':
name: "Misiles interferidores"
text: '''<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efectuar este ataque.%LINEBREAK%Si este ataque impacta, el defensor y toda otra nave que tenga a alcance 1 recibe 1 ficha de Interferencia. Luego se anulan <strong>todos</strong> los resultados de dados.'''
'R5-TK':
text: '''Puedes fijar como blanco naves aliadas.%LINEBREAK%Puedes efectuar ataques contra naves aliadas.'''
'Threat Tracker':
name: "Rastreador de amenazas"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando una nave enemiga que tengas a alcance 1-2 y dentro de tu arco de fuego se convierta en la nave activa durante la fase de Combate, puedes gastar la ficha de Blanco fijado que tengas sobre esa nave para realizar una acción gratuita de impulso o tonel volado, si esa acción figura en tu barra de acciones.'''
'Debris Gambit':
name: "Treta de los desechos"
text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Acción:</strong> Asigna 1 ficha de Evasión a tu nave por cada obstáculo que tengas a alcance 1, hast aun máximo de 2 fichas de Evasión.'''
'Targeting Scrambler':
name: "Interferidor de sistemas de puntería"
text: '''Al comienzo de la fase de Planificación, puedes recibir una ficha de Armas bloqueadas para elegir una nave que tengas a alcance 1-3 y asignarle el Estado "Sistemas interferidos".'''
'Death Troopers':
name: "Soldados de la muerte"
text: '''Después de que otra nave aliada que tengas a alcance 1 se convierta en el defensor, si estás situado a alcance 1-3 del atacante y dentro de su arco de fuego, el atacante recibe 1 ficha de Tensión.'''
'ISB Slicer':
name: "Técnico en guerra electrónica de la OSI"
text: '''%IMPERIALONLY%%LINEBREAK%Después de que realices una acción de interferencia contra una nave enemiga, puedes elegir una nave que esté situada a alcance 1 de esa nave enemiga y no esté interferida, y asignarle 1 ficha de Interferencia.'''
'Tactical Officer':
name: "Oficial táctico"
text: '''%IMPERIALONLY%%LINEBREAK%Tu barra de acciones gana el icono %COORDINATE%.'''
'Saw Gerrera':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques, puedes sufrir 1 de daño para cambiar todos tus resultados %FOCUS% por resultados %CRIT%.'''
'Director Krennic':
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", asigna el Estado "Prototipo optimizado" a una nave aliada del Imperio Galáctico que tenga un valor de Escudos igual o inferior a 3.'''
'Magva Yarro':
text: '''%REBELONLY%%LINEBREAK%Después de que te defiendas, puedes fijar como blanco al atacante.'''
'Renegade Refit':
name: "Reequipado por los Renegados"
text: '''<span class="card-restriction">Sólo T-65 Ala-X y Ala-U.</span>%LINEBREAK%Te puedes equipar con un máximo de 2 mejoras de Modificación distintas.%LINEBREAK%El coste en puntos de escuadrón de cada una de las mejoras %ELITE% que tengas equipadas en tu nave se reduce en 1 (hasta un mínimo de 0).'''
'Thrust Corrector':
name: "Corrector de empuje"
text: '''Cuando te defiendas, si no tienes asignadas más de 3 fichas de Tensión, puedes recibir 1 ficha de Tensión para anular todos los resultados de tus dados. Si lo haces, añade 1 resultado %EVADE% a tu tirada. No podrás volver a modificar tus dados durante este ataque.%LINEBREAK%Sólo puedes equipar esta Mejora en naves con una puntuación de Casco 4 o inferior.'''
modification_translations =
"Stealth Device":
name: "Dispositivo de Sigilo"
text: """Tu Agilidad se incrementa en 1. Descarta esta carta si eres alcanzado por un ataque."""
"Shield Upgrade":
name: "Escudos Mejorados"
text: """Tu valor de Escudos se incrementa en 1."""
"Engine Upgrade":
name: "Motor Mejorado"
text: """Tu barra de acciones gana el ícono %BOOST%."""
"Anti-Pursuit Lasers":
name: "Cañones Láser Antipersecución"
text: """Después de que una nave enemiga ejecute una maniobra que le cause solapar su peana con la tuya, lanza un dado de ataque. Si el resultado es %HIT% o %CRIT%, el enemigo sufre 1 de daño."""
"Targeting Computer":
name: "Computadora de Selección de Blancos"
text: """Tu barra de acciones gana el icono %TARGETLOCK%."""
"Hull Upgrade":
name: "Blindaje mejorado"
text: """Tu valor de Casco se incrementa en 1."""
"Munitions Failsafe":
name: "Sistema de Munición a Prueba de Fallos"
text: """Cuando ataques con un armamento secundario que requiera descartarlo para efectuar el ataque, no se descarta a menos que el ataque impacte al objetivo."""
"Stygium Particle Accelerator":
name: "Acelerador de Partículas de Estigio"
text: """<span class="card-restriction">Soo TIE Fantasma.</span><br /><br />Cuando realices una acción de camuflaje o desactives tu camuflaje, puedes realizar una acción gratuita de Evasión."""
"Advanced Cloaking Device":
name: "Dispositivo de Camuflaje Avanzado"
text: """Despues de que efectúes un ataque, puedes realizar una acción gratuita de camuflaje."""
ship: "TIE Fantasma"
"Combat Retrofit":
name: "Equipamiento de Combate"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Tu valor de casco se incrementa en 2 y tu valor de escudos se incrementa en 1."""
ship: 'Transporte mediano GR-75'
"B-Wing/E2":
text: """<span class="card-restriction">Solo Ala-B.</span><br /><br />Tu barra de mejoras gana el icono de mejora %CREW%."""
ship: "Ala-B"
"Countermeasures":
name: "Contramedidas"
text: """Al comienzo de la fase de Combate, puedes descartar esta carta para aumentar en 1 tu Agilidad hasta el final de la ronda. Después puedes quitar 1 ficha enemiga de Blanco Fijado de tu nave."""
"Experimental Interface":
name: "Interfaz Experimental"
text: """Una vez por ronda, después de que realices una acción, puedes llevar a cabo 1 acción gratuita de una carta de Mejora equipada que tenga el encabezado "<strong>Acción:</strong>". Después recibes 1 ficha de Tension."""
"Tactical Jammer":
name: "Inhibidor Táctico"
text: """Tu nave puede obstruir ataques enemigos."""
"Autothrusters":
name: "Propulsores Automatizados"
text: """Cuando te defiendas, si estás fuera del arco de fuego del atacante, o dentro de su arco de fuego pero más allá de alcance 2, puedes cambiar 1 de tus resultados de cara vacía por un resultado %EVADE%. Sólo puedes equiparte con esta carta si tienes el icono de acción %BOOST%."""
"Twin Ion Engine Mk. II":
name: "Motor Iónico Doble Modelo II"
text: """<span class="card-restriction">Solo TIE.</span>%LINEBREAK%Puedes tratar todas las maniobras de inclinación (%BANKLEFT% y %BANKRIGHT%) como si fueran maniobras verdes."""
"Maneuvering Fins":
name: "Alerones de Estabilización"
text: """<span class="card-restriction">Solo YV-666.</span>%LINEBREAK%Cuando reveles una maniobra de giro (%TURNLEFT% o %TURNRIGHT%), puedes rotar tu selector para elegir en su lugar la maniobra de inclinación correspondiente (%BANKLEFT% o %BANKRIGHT%) de igual velocidad."""
"Ion Projector":
name: "Proyector de Iones"
text: """%LARGESHIPONLY%%LINEBREAK%Después de que una nave enemiga ejecute una maniobra que la solape con tu nave, tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, la nave enemiga recibe 1 ficha de Iones."""
"Advanced SLAM":
name: "Motor Sublumínico Avanzado"
text: """Después de efectuar una acción de MASA, si no te has solapado con un obstáculo ni con otra nave, puedes llevar a cabo una acctión gratuita."""
'Integrated Astromech':
name: "Droide Astromecánico Integrado"
text: '''<span class="card-restriction">Solo X-wing.</span>%LINEBREAK%Cuando recibas una carta de Daño, puedes descartar 1 de tus cartas de Mejora %ASTROMECH% para descartar esa carta de Daño (sin resolver su efecto).'''
'Optimized Generators':
name: "Generadores optimizados"
text: '''%HUGESHIPONLY%%LINEBREAK%Una vez por ronda, cuando asignes Energía a una carta de Mejora equipada, obtienes 2 de Energía.'''
'Automated Protocols':
name: "Procedimientos automatizados"
text: '''%HUGESHIPONLY%%LINEBREAK%OUna vez por ronda, después de que realices una acción que no sea una acción de recuperación o de refuerzo, puedes gastar 1 de Energía para realizar una acción gratuita de recuperación o de refuerzo.'''
'Ordnance Tubes':
text: '''%HUGESHIPONLY%%LINEBREAK%You may treat each of your %HARDPOINT% upgrade icons as a %TORPEDO% or %MISSILE% icon.%LINEBREAK%When you are instructed to discard a %TORPEDO% or %MISSILE% Upgrade card, do not discard it.'''
'Long-Range Scanners':
name: "Sensores de Largo Alcance"
text: '''Puedes fijar como blanco naves que tengas a alcance 3 o superior. No puedes fijar como blanco naves que tengas a alcance 1-2. Para poder equipar esta carta has de tener los iconos de mejora %TORPEDO% y %MISSILE% en tu barra de mejoras.'''
"Guidance Chips":
name: "Chips de Guiado"
text: """Una vez por ronda, cuando ataques con un sistema de armamento secundario %TORPEDO% o %MISSILE%, puedes cambiar 1 de tus resultados de dado por un resultado %HIT% (o por un resultad %CRIT% si tu valor de Armamento principal es de 3 o más)."""
'Vectored Thrusters':
name: "Propulsores vectoriales"
text: '''%SMALLSHIPONLY%%LINEBREAK%Tu barra de acciones gana el icono de acción %BARRELROLL%.'''
'Smuggling Compartment':
name: "Compartimento para contrabando"
text: '''<span class="card-restriction">Sólo YT-1300 y YT-2400.</span>%LINEBREAK%Tu barra de mejoras gana el icono %ILLICIT%.%LINEBREAK%Puedes equipar 1 mejora de Modificación adicional que no cueste más de 3 puntos de escuadrón.'''
'Gyroscopic Targeting':
name: "Estabilización giroscópica"
ship: "Nave de persecución clase Lancero"
text: '''<span class="card-restriction">Sólo Nave de persecución clase Lancero.</span>%LINEBREAK%Al final de la fase de Combate, si en esta ronda ejecutaste una maniobra de velocidad 3, 4 o 5, puedes reorientar tu arco de fuego móvil.'''
'Captured TIE':
ship: "Caza TIE"
name: "TIE capturado"
text: '''<span class="card-restriction">Sólo Caza TIE.</span>%REBELONLY%%LINEBREAK%Las naves enemigas cuyos pilotos tengan una Habilidad más baja que la tuya no pueden declararte como blanco de un ataque. Después de que efectúes un ataque o cuando seas la única nave aliada que queda en juego, descarta esta carta.'''
'Spacetug Tractor Array':
name: "Campos de tracción de remolque"
ship: "Saltador Quad"
text: '''<span class="card-restriction">Sólo Saltador Quad.</span>%LINEBREAK%<strong>Acción:</strong> Elige una nave que tengas dentro de tu arco de fuego a distancia 1 y asígnale una ficha de Campo de tracción. Si es una nave aliada, resuelve el efecto de la ficha de Campo de tracción como si se tratara de una nave enemiga.'''
'Lightweight Frame':
name: "Fuselaje ultraligero"
text: '''<span class="card-restriction">Sólo TIE.</span>%LINEBREAK%Cuando te defiendas, tras tirar los dados de defensa, si hay más dados de ataque que dados de defensa, tira 1 dado de defensa adicional.%LINEBREAK%Esta mejora no puede equiparse en naves con puntuación de Agilidad 3 o superior.'''
'Pulsed Ray Shield':
name: "Escudo de rayos pulsátil"
text: '''<span class="card-restriction">Sólo Escoria y Rebelde.</span>%LINEBREAK%Durante la fase Final, puedes recibir 1 ficha de Iones para recuperar 1 ficha de Escudos (pero no puedes exceder tu valor de Escudos). Sólo puedes equipar esta carta si tu valor de Escudos es 1.'''
'Deflective Plating':
name: "Blindaje deflector de impactos"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando una bomba aliada se detone, puedes elegir no sufrir sus efectos. Si lo haces, tira un dado de ataque. Si sacas %HIT%, descarta esta carta.'''
'Servomotor S-Foils':
name: "Alas móviles"
text: '''<span class="card-restriction">Sólo T-65 Ala-X.</span> %DUALCARD%%LINEBREAK%<strong>Cara A (Ataque):</strong>Tu barra de acciones gana el icono %BARRELROLL%. Si no estás bajo tensión, cuando reveles una maniobra (%TURNLEFT% 3) o (%TURNRIGHT% 3), puedes considerarla como si fuera una maniobra roja (%TROLLLEFT% 3) o (%TROLLRIGHT% 3) con la misma dirección.%LINEBREAK%Al comienzo de la fase de Activación, puedes darle la vuelta a esta carta.%LINEBREAK%<strong>Cara B (Cerrada):</strong>Tu valor de Armamento principal se reduce en 1. Tu barra de acciones gana el icono %BOOST%. Tus maniobras (%BANKLEFT% 2) y (%BANKRIGHT% 2 ) se consideran verdes.%LINEBREAK%Al comienzo de la fase de Activacion, puedes darle la vuelta a esta carta.'''
'Multi-spectral Camouflage':
name: "Camuflaje multiespectral"
text: '''%SMALLSHIPONLY%%LINEBREAK%Después de que recibas una ficha roja de Blanco fijado, si sólo tienes asignada 1 ficha roja de Blanco fijado, tira 1 dado de defensa. Si obtienes un resultado %EVADE%, retira esa ficha roja de Blanco fijado.'''
title_translations =
"Slave I":
name: "Esclavo 1"
text: """<span class="card-restriction">Solo Firespray-31.</span><br /><br />Tu barra de mejoras gana el icono %TORPEDO%."""
"Millennium Falcon":
name: "Halcón Milenario"
text: """<span class="card-restriction">Solo YT-1300.</span><br /><br />Tu barra de acciones gana el icono %EVADE%."""
"Moldy Crow":
name: "Cuervo Oxidado"
text: """<span class="card-restriction">Solo HWK-290.</span><br /><br />Durante la fase Final, no retires de tu nave las fichas de Concentración que no hayas usado."""
"ST-321":
text: """<span class="card-restriction">Solo Lanzadera clase <em>Lambda</em>.</span><br /><br />Cuando fijas un blanco, puedes hacerlo con cualquier nave enemiga de la zona de juego."""
ship: "Lanzadera clase Lambda"
"Royal Guard TIE":
name: "TIE de la Guardia Real"
ship: "Interceptor TIE"
text: """<span class="card-restriction">Solo TIE Interceptor.</span><br /><br />Puedes equipar un máximo de 2 mejoras distintas de Modificación (en vez de 1).<br /><br />Esta mejora no puede equiparse en naves con pilotos de Habilidad 4 o inferior."""
"Dodonna's Pride":
name: "Orgullo de Donna"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />Cuando realices una accion de Coordinación, puedes elegir 2 naves aliadas en vez de 1. Cada una de estas naves pueden realizar 1 accion gratuita."""
ship: "Corbeta CR90 (Proa)"
"A-Wing Test Pilot":
name: "Piloto de Ala-A experimental"
text: """<span class="card-restriction">Solo Ala-A.</span><br /><br />Tu barra de mejoras gana 1 icono de mejora %ELITE%.<br /><br />No puedes equipar 2 cartas de Mejora %ELITE% iguales. Tampoco te puedes equipar con esta carta si la Habilidad de tu piloto es 1 o inferior."""
ship: "Ala-A"
"Tantive IV":
name: "Tantive IV"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />La barra de mejoras de tu sección de proa gana 1 icono adicional de %CREW% y 1 icono adicional de %TEAM%."""
ship: "Corbeta CR90 (Proa)"
"Bright Hope":
name: "Esperanza Brillante"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Una ficha de Refuerzo asignada a tu seccion de proa añade 2 resultados de %EVADE% en vez de 1."""
ship: 'Transporte mediano GR-75'
"Quantum Storm":
name: "Tormenta Cuántica"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Al principio de la fase Final, si tienes 1 ficha de Energía o menos, ganas 1 ficha de Energía."""
ship: 'Transporte mediano GR-75'
"Dutyfree":
name: "Libre de Impuestos"
text: """<span class="card-restriction">Solo GR-75./span><br /><br />Cuando realices una acción de Interferencia, puedes elegir una nave enemiga situada a alcance 1-3 en lugar de 1-2."""
ship: 'Transporte mediano GR-75'
"Jaina's Light":
name: "Luz de Jaina"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />Cuando te defiendas, una vez por ataque, si recibes una carta de Daño boca arriba, puedes descartarla y robar otra carta de Daño boca arriba."""
"Outrider":
name: "Jinete del Espacio"
text: """<span class="card-restriction">Solo YT-2400.</span><br /><br />Mientras tu nave tenga equipada una mejora de %CANNON%, <strong>no puedes</strong> atacar con tu armamento principal y puedes atacar con armamentos secundarios %CANNON% contra naves enemigas fuera de tu arco de fuego."""
"Andrasta":
name: "Andrasta"
text: """<span class="card-restriction">Solo Firespray-31.</span><br /><br />Tu barra de mejoras gana 2 iconos %BOMB% adicionales."""
"TIE/x1":
ship: "TIE Avanzado"
text: """<span class="card-restriction">Solo TIE Avanzado.</span>%LINEBREAK%Tu barra de mejoras gana el icono %SYSTEM%.%LINEBREAK%Si te equipas con una mejora %SYSTEM%, su coste en puntos de escuadrón se reduce en 4 (hasta un mínimo de 0)."""
"BTL-A4 Y-Wing":
name: "BTL-A4 Ala-Y"
text: """<span class="card-restriction">Solo Ala-Y.</span><br /><br />No puedes atacar naves que estén fuera de tu arco de fuego. Después de que efectúes un ataque con tu armamento principal, puedes realizar inmediatamente un ataque con arma secundaria %TURRET%."""
ship: "Ala-Y"
"IG-2000":
name: "IG-2000"
text: """<span class="card-restriction">Solo Agresor.</span><br /><br />Tu piloto tiene la misma capacidad especial que cualquier otra nave aliada equipada con la carta de Mejora <em>IG-2000</em> (además de su propia capacidad especial)."""
ship: "Agresor"
"Virago":
name: "Virago"
text: """<span class="card-restriction">Solo Víbora Estelar.</span><br /><br />Tu barra de mejoras gana los iconos %SYSTEM% y %ILLICIT%.<br /><br />Esta mejora no puede equiparse en naves con pilotos de Habilidad 3 o inferior."""
ship: 'Víbora Estelar'
'"Heavy Scyk" Interceptor (Cannon)':
name: 'Interceptor "Scyk Pesado" (Cañón)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %CANNON%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
'"Heavy Scyk" Interceptor (Missile)':
name: 'Interceptor "Scyk Pesado" (Misil)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %MISSILE%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
'"Heavy Scyk" Interceptor (Torpedo)':
name: 'Interceptor "Scyk Pesado" (Torpedo)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %TORPEDO%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
"Dauntless":
name: "Intrépido"
text: """<span class="card-restriction">Solo VT-49 Diezmador.</span><br /><br />Después de que ejecutes una maniobra que te solape con otra nave, puedes realizar 1 acción gratuita. Luego recibes 1 ficha de Tensión."""
ship: 'VT-49 Diezmador'
"Ghost":
name: "Espíritu"
text: """<span class="card-restriction">Sólo VCX-100.</span>%LINEBREAK%Equipa la carta de Título <em>Fantasma</em> a una Lanzadera de ataque aliada y acóplala a esta nave.%LINEBREAK%Después de que ejecutes una maniobra, puedes desplegar la Lanzadera de ataque desde los salientes de la parte trasera de tu peana."""
"Phantom":
name: "Fantasma"
text: """Mientras estás acoplado, el <em>Espíritu</em> puede efectuar ataques de armamento principal desde su arco de fuego especial y, al final de la fase de Combate, puede efectuar un ataque adicional con una %TURRET% equipada. Si efectúa este ataque, no puede volver a atacar durante esta ronda."""
ship: 'Lanzadera de Ataque'
"TIE/v1":
text: """<span class="card-restriction">Solo Prototipo de TIE Av.</span>%LINEBREAK%Después de que fijes a un blanco, puedes realizar una acción gratuita de evasión."""
ship: 'Prototipo de TIE Avanzado'
"Mist Hunter":
name: "Cazador de la Niebla"
text: """<span class="card-restriction">Solo Caza Estelar G-1A.</span>%LINEBREAK%Tu barra de acción gana el icono %BARRELROLL%.%LINEBREAK%<strong>Debes</strong> equiparte con 1 carta de Mejora "Proyector de Campo de Tracción" (pagando su coste normal en puntos de escuadrón)."""
ship: 'Caza Estelar G-1A'
"Punishing One":
name: "Castigadora"
text: """<span class="card-restriction">Solo Saltador Maestro 5000.</span>%LINEBREAK%Tu valor de Armamento principal se incrementa en 1."""
ship: 'Saltador Maestro 5000'
"Hound's Tooth":
name: "Diente de Perro"
text: """<span class="card-restriction">Solo YV-666.</span>%LINEBREAK%Después de que seas destruido, y antes de retirarte de la zona de juego, puedes <strong>desplegar</strong> al Piloto del <span>Cachorro de Nashtah</span>.%LINEBREAK%El <span>Cachorro de Nashtah</span> no puede atacar en esta ronda."""
"Assailer":
name: "Acometedor"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%Cuando te defiendas, si la sección atacada tiene asginada una ficha de Refuerzo, puedes cambiar 1 resultado de %FOCUS% por 1 resultado %EVADE%."""
"Instigator":
name: "Instigador"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%ADespués de que hayas llevado a cabo una acción de recuperación, recuperas 1 de Escudos adicional."""
"Impetuous":
name: "Impetuoso"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%Después de que hayas efectuado un ataque que destruya una nave enemiga, puedes fijar un blanco."""
'TIE/x7':
text: '''<span class="card-restriction">Sólo TIE Defensor.</span>%LINEBREAK%Tu barra de mejoras pierde los iconos de mejora %CANNON% y %MISSILE%.%LINEBREAK%Después de que ejecutes una maniobra de velocidad 3, 4 o 5, si no te solapaste con un obstáculo o nave, puedes realizar una acción gratuita de evasión.'''
ship: 'Defensor TIE'
'TIE/D':
text: '''<span class="card-restriction">Sólo TIE Defensor.</span>%LINEBREAK%Una vez por ronda, después de que efectúes un ataque con un armamento secundario %CANNON% con un coste en puntos de escuadrón inferior a 4, puedes efcetuar un ataque con tu armamento principal.'''
ship: 'Defensor TIE'
'TIE Shuttle':
name: "Lanzadera TIE"
text: '''<span class="card-restriction">Sólo TIE Bombardero.</span>%LINEBREAK%Tu barra de mejoras pierde todos los iconos de mejora %TORPEDO%, %MISSILE% y %BOMB% y gana 2 iconos de mejora %CREW%. No puedes equipar ninguna carta de Mejora %CREW% con un coste en puntos de escuadrón superior a 4.'''
ship: 'Bombardero TIE'
'Requiem':
text: '''%GOZANTIONLY%%LINEBREAK%When you deploy a ship, treat its pilot skill value as "8" until the end of the round.'''
'Vector':
text: '''%GOZANTIONLY%%LINEBREAK%After you execute a maneuver, you may deploy up to 4 attached ships (instead of 2).'''
'Suppressor':
text: '''%GOZANTIONLY%%LINEBREAK%Once per round, after you acquire a target lock, you may remove 1 focus, evade, or blue target lock token from that ship.'''
'Black One':
name: "Negro Uno"
text: '''Después de que realices una acción de impulso o de tonel volado, puedes quitar 1 ficha de Blanco fijado enemiga de una nave aliada que tengas a alcance 1. Esta mejora no puede equiparse en naves con pilotos de Habilidad 6 o inferior.'''
ship: "T-70 Ala-X"
'Millennium Falcon (TFA)':
name: "Halcón Milenario (TFA)"
text: '''Después de que ejecutes una maniobra de inclinación (%BANKLEFT% o %BANKRIGHT%) de velocidad 3, si no estás en contacto con otra nave y no estás bajo tensión, puedes recibir 1 ficha de Tensión para cambiar la orientación de tu nave 180°.'''
'Alliance Overhaul':
name: "Reacondicionado por la Alianza"
text: '''<span class="card-restriction">Sólo ARC-170.</span>%LINEBREAK%Cuando ataques con un armamento principal desde tu arco de fuego normal, puedes tirar 1 dado de ataque adicional. Cuando ataques desde tu arco de fuego auxiliar, puedes cambiar 1 de tus resultados %FOCUS% por 1 resultado %CRIT%.'''
'Special Ops Training':
ship: "Caza TIE/sf"
name: "Entrenamiento de operaciones especiales"
text: '''<span class="card-restriction">Sólo TIE/sf.</span>%LINEBREAK%Cuando ataques con un armamento principal desde tu arco de fuego normal, puedes tirar 1 dado adicional de ataque. Si decides no hacerlo, puedes realizar un ataque adicional desde tu arco de fuego aixiliar.'''
'Concord Dawn Protector':
name: "Protector de Concord Dawn"
ship: "Caza Estelar del Protectorado"
text: '''<span class="card-restriction">Sólo Caza estelar del Protectorado.</span>%LINEBREAK%Cuando te defiendas, si estás dentro del arco de fuego del atacante y a alcance 1 y el atacante está dentro de tu arco de fuego, añade 1 resultado %EVADE%.'''
'Shadow Caster':
name: "Sombra Alargada"
ship: "Nave de persecución clase Lancero"
text: '''<span class="card-restriction">Sólo Nave de persecución clase Lancero</span>%LINEBREAK%Después de que efectúes un ataque que impacte, si el defensor está dentro de tu arco de fuego móvil y a alcance 1-2, puedes asignarle 1 ficha de Campo de tracción.'''
# Wave X
'''Sabine's Masterpiece''':
ship: "Caza TIE"
name: "Obra maestra de Sabine"
text: '''<span class="card-restriction">Sólo Caza TIE.</span>%REBELONLY%%LINEBREAK%Tu barra de mejoras gana los iconos %CREW% y %ILLICIT%.'''
'''Kylo Ren's Shuttle''':
ship: "Lanzadera clase Ípsilon"
name: "Lanzadera de Kylo Ren"
text: '''<span class="card-restriction">Sólo Lanzadera clase Ípsilon.</span>%LINEBREAK%Al final de la fase de Combate, elige una nave enemiga que tengas a alcance 1-2 y no esté bajo tensión. El jugador que la controla debe asignarle una ficha de Tensión o asignar una ficha de Tensión a otra d esus naves que esté situada a alcance 1-2 de ti.'''
'''Pivot Wing''':
name: "Ala pivotante"
ship: "Ala-U"
text: '''<span class="card-restriction">Sólo Ala-U.</span> %DUALCARD%%LINEBREAK%<strong>Cara A (Ataque):</strong> Tu Agilidad se incrementa en 1.%LINEBREAK%Después de que ejecutes una maniobra, puedes darle la vuelta a esta carta.%LINEBREAK%<strong>Cara B (Aterrizaje):</strong> Cuando reveles una maniobra (%STOP% 0), puedes cambiar la orientación de tu nave en 180°.%LINEBREAK%Después de que ejecutes una maniobra, puedes darle la vuelta a esta carta.'''
'''Adaptive Ailerons''':
name: "Alerones adaptativos"
ship: "Fustigador TIE"
text: '''<span class="card-restriction">Sólo Fustigador TIE.</span>%LINEBREAK%Inmediatamente antes de revelar tu selector de maniobras, si no estás bajo tensión, debes ejecutar una manibora blanca (%BANKLEFT% 1), (%STRAIGHT% 1) o (%BANKRIGHT% 1).'''
# C-ROC
'''Merchant One''':
name: "Mercader Uno"
ship: "Crucero C-ROC"
text: '''<span class="card-restriction">Sólo C-ROC Cruiser.</span>%LINEBREAK%Tu barra de mejoras gana 1 icono %CREW% adicional y 1 icono %TEAM% adicional y pierde 1 icono %CARGO%.'''
'''"Light Scyk" Interceptor''':
name: 'Interceptor "Scyk Ligero"'
ship: "Interceptor M3-A"
text: '''<span class="card-restriction">Sólo Interceptor M3-A.</span>%LINEBREAK%Toda slas cartas de Daño que te inflijan se te asignan boca arriba. Puedes ejecutar todas las maniobras de inclinación (%BANKLEFT% o %BANKRIGHT%) como maniobras verdes. No puedes equiparte con mejoras de Modificación.s.'''
'''Insatiable Worrt''':
name: "Worrt insaciable"
ship: "Crucero C-ROC"
text: '''Después de que realices la acción de recuperación, ganas 3 de energía.'''
'''Broken Horn''':
name: "Cuerno Roto"
ship: "Crucero C-ROC"
text: '''Cuando te defiendas, si tienes asignada una ficha de Refuerzo, puedes añadir 1 resultado %EVADE% adicional. Si lo haces, tras defenderte, descarta tu ficha de Refuerzo.'''
'Havoc':
name: "Estrago"
ship: "Bombardero Scurrg H-6"
text: '''<span class="card-restriction">Sólo Bombarder Scurrg H-6.</span>%LINEBREAK%Tu barra de mejoras gana los iconos %SYSTEM% y %SALVAGEDASTROMECH% y pierde el icono %CREW%.%LINEBREAK%No puedes equiparte con cartas de mejora %SALVAGEDASTROMECH% que no sean únicas.'''
'Vaksai':
ship: "Caza Kihraxz"
text: '''<span class="card-restriction">Sólo Caza Kihraxz.</span>%LINEBREAK%El coste en puntos de escuadrón de cada una de tus mejoras equipadas se reduce en 1 (hast aun mínimo de 0).%LINEBREAK%Puedes equipar un máximo de 3 mejoras distintas de Modificación.'''
'StarViper Mk. II':
name: "Víbora Estelar modelo II"
ship: "Víbora Estelar"
text: '''<span class="card-restriction">Sólo Víbora Estelar.</span>%LINEBREAK%Puedes equipar un máximo de 2 mejoras distintas de Título.%LINEBREAK%Cuando realices una acción de tonel volado <strong>debes</strong> utilizar la plantilla (%BANKLEFT% 1) o (%BANKRIGHT% 1) en vez de la plantilla (%STRAIGHT% 1).'''
'XG-1 Assault Configuration':
ship: "Ala Estelar clase Alfa"
name: "Configuración de asalto Xg-1"
text: '''<span class="card-restriction">Sólo Ala Estelar clase Alfa.</span>%LINEBREAK%Tu barra de mejoras gana 2 iconos %CANNON%.%LINEBREAK%Puedes efectuar ataques con sistemas de armamento secundario %CANNON% con un coste igual o inferior a 2 puntos de escuadrón incluso aunque tengas asignada una ficha de Armas bloqueadas.'''
'Enforcer':
name: "Brazo Ejecutor"
ship: "Caza M12-L Kimogila"
text: '''<span class="card-restriction">Sólo Caza M12-L Kimogila.</span>%LINEBREAK%Después de que te defiendas, si el atacante está situado dentro de tu arco de fuego centrado, recibe 1 fciha de Tensión.'''
'Ghost (Phantom II)':
name: "Espíritu (Fantasma II)"
text: '''<span class="card-restriction">Sólo VCX-100.</span>%LINEBREAK%Equipa la carta de Título <em>Fantasma II</em> a una Lanzadera clase <em>Sheathipede</em> aliada y acóplala a esta nave.%LINEBREAK%Después de que ejecutes una maniobra, puedes desplegar la nave que tienes acoplada desde los salientes de la parte trasera de tu peana.'''
'Phantom II':
name: "Fantasma II"
ship: "Lanzadera clase Sheathipede"
text: '''Mientras estés acoplado, el <em>Espíritu</em> puede efectuar ataques con su armamento principal desde su arco de fuego especial.%LINEBREAK%Mientras estés acoplado, al final de la fase de Activación, el <em>Espíritu</em> puede efectuar una acción gratuita de coordinación.'''
'First Order Vanguard':
name: "Vanguardia de la Primera Orden"
ship: "Silenciador TIE"
text: '''<span class="card-restriction">Sólo Silenciador TIE.</span>%LINEBREAK%Cuando ataques, si el defensor es la única nave que tienes dentro de tu arco de fuego a alcance 1-3, puedes volver a tirar 1 dado de ataque.%LINEBREAK%Cuando te defiendas, puedes descartar esta carta para volver a tirar todos tus dados de defensa.'''
'Os-1 Arsenal Loadout':
name: "Configuración de Arsenal Os-1"
ship: "Ala Estelar clase Alfa"
text: '''<span class="card-restriction">Sólo Ala Estelar clase Alfa.</span>%LINEBREAK%Tu barra de mejoras gana los iconos %TORPEDO% y %MISSILE%.%LINEBREAK%Puedes efectuar ataques con sistemas de armamento secundario %TORPEDO% y %MISSILE% contra naves que hayas fijado como blanco incluso aunque tengas asignada una ficha de Armas bloqueadas.'''
'Crossfire Formation':
name: "Formación de fuego cruzado"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando te defiendas, si hay por lo menos 1 otra nave aliada de la Reistencia situada a alcance 1-2 del atacante, puedes añadir 1 resultado %FOCUS% a tu tirada.'''
'Advanced Ailerons':
name: "Alerones avanzados"
ship: "Segador TIE"
text: '''<span class="card-restriction">Sólo Segador TIE.</span>%LINEBREAK%Tus maniobras (%BANKLEFT% 3) y (%BANKRIGHT% 3) se consideran blancas.%LINEBREAK%Inmediatamente antes de revelar tu selector de maniobras, si no estás bajo tensión, debes ejecutar una manibora blanca (%BANKLEFT% 1), (%STRAIGHT% 1) o (%BANKRIGHT% 1).'''
condition_translations =
'''I'll Show You the Dark Side''':
name: "Yo te mostraré el Lado Oscuro"
text: '''Cuando esta carta es asignada, si no está ya en juego, el jugador que la ha asignado busca en el mazo de Daño 1 carta de Daño que tenga el atributo <strong><em>Piloto</em></strong> y puede colocarla boca arriba sobre esta carta de Estado. Luego vuelve a barajar el mazo de Daño.%LINEBREAKCuando sufras daño crítico durante un ataque, en vez de eso recibes la carta de Daño boca arriba que has elegido.%LINEBREAK%Cuando no haya ninguna carta de Daño sobre esta carta de Estado, retírala.'''
'Suppressive Fire':
name: "Fuego de supresión"
text: '''Cuando ataques a una nave que no sea el "Capitán Rex", tira 1 dado de ataque menos.%LINEBREAK% Cuando declares un ataque que tenga como blanco al "Capitán Rex" o cuando el "Capitán Rex" sea destruido, retira esta carta.%LINEBREAK%Al final de la fase de Combate, si el "Capitán Rex" no ha efectuado un ataque en esta fase, retira esta carta.'''
'Fanatical Devotion':
name: "Lealtad Fanática"
text: '''Cuando te defiendas, no pudes gastar fichas de Concentración.%LINEBREAK%Cuando ataques, si gastas una ficha de Concentración parar cambiar todos los resultados %FOCUS% por resultados %HIT%, deja aparte el primer resultado %FOCUS% que has cambiado. El resultado %HIT% que has dejado aparte no puede ser anulado por dados de defensa, pero el defensor puede anular resultados %CRIT% antes que él.%LINEBREAK%Durante la fase Final, retira esta carta.'''
'A Debt to Pay':
name: "Una deuda por saldar"
text: '''Cuando ataques a una nave que tiene la carta de Mejora "Una cuenta pendiente", puedes cambiar 1 resultado %FOCUS% por un resultado %CRIT%.'''
'Shadowed':
name: "Vigilado"
text: '''Se considera que "Thweek" tiene el mismo valor de Habilidad que tu piloto tenía después de la preparación de la partida.%LINEBREAK%El valor de Habilidad de "Thweek" no cambia si el valor de Habilidad de tu piloto se modifica o eres destruido.'''
'Mimicked':
name: "Imitado"
text: '''Se considera que "Thweek" tiene tu misma capacidad especial de piloto.%LINEBREAK%"Thweek" no puede utilizar tu capacidad especial de piloto para asignar una carta de Estado.%LINEBREAK%"Thweek" no pierde tu capacidad especial de piloto si eres destruido.'''
'Harpooned!':
name: "¡Arponeado!"
text: '''Cuando seas impactado por un ataque, si hay al menos 1 resultad %CRIT% sin anular, toda otra nave que tengas a alcance 1 sufre 1 punto de daño. Luego descarta esta carta y recibe 1 carta de Daño boca abajo.%LINEBREAK%Cuando seas destruido, toda nave que tengas a alcance 1 sufre 1 punto de daño.%LINEBREAK%<strong>Acción:</strong> Descarta esta carta. Luego tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, sufres 1 punto de daño.'''
'Rattled':
name: "Estremecido"
text: '''Cuando sufras daño normal o daño crítico causado por una bomba, sufres 1 punto adicional de daño crítico. Luego, retira esta carta%LINEBREAK%<strong>Acción:</strong> Tira 1 dado de ataque. Si sacas %FOCUS% o %HIT%, retira esta carta.'''
'Scrambled':
name: "Sistemas interferidos"
text: '''Cuando ataques a una nave que tengas a alcance 1 y esté equipada con la mejora "Interferidor de sistemas de puntería", no puedes modificar tus dados de ataque.%LINEBREAK%Al final de la fase de Combate, retira esta carta.'''
'Optimized Prototype':
name: "Prototipo optimizado"
text: '''Tu valor de Escudos se incrementa en 1.%LINEBREAK%Una vez por ronda, cuando efectúes un ataque con tu armamento principal, puedes gastar 1 resultado de dado para retirar 1 ficha de Escudos del defensor.%LINEBREAK%Después de que efectúes un ataque con tu armamento principal, una nave aliada que tengas a alcance 1-2 y esté equipada con la carta de Mejora "Director Krennic" puede fijar como blanco al defensor.'''
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations
| 151417 | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.es = 'Español'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations['Español'] =
action:
"Barrel Roll": "Tonel Volado"
"Boost": "Impulso"
"Evade": "Evadir"
"Focus": "Concentración"
"Target Lock": "Blanco Fijado"
"Recover": "Recuperar"
"Reinforce": "Reforzar"
"Jam": "Interferir"
"Coordinate": "Coordinar"
"Cloak": "Camuflaje"
slot:
"Astromech": "Droide Astromech"
"Bomb": "Bomba"
"Cannon": "Cañón"
"Crew": "Tripulación"
"Elite": "Élite"
"Missile": "Misiles"
"System": "Sistemas"
"Torpedo": "Torpedos"
"Turret": "Torreta"
"Cargo": "Carga"
"Hardpoint": "Hardpoint"
"Team": "Equipo"
"Illicit": "Ilícita"
"Salvaged Astromech": "Droide Astromech Remendado"
"Tech": "Tecnología"
sources: # needed?
"Core": "Caja Básica"
"A-Wing Expansion Pack": "Pack de Expansión Ala-A"
"B-Wing Expansion Pack": "Pack de Expansión Ala-B"
"X-Wing Expansion Pack": "Pack de Expansión Ala-X"
"Y-Wing Expansion Pack": "Pack de Expansión Ala-Y"
"Millennium Falcon Expansion Pack": "Pack de Expansión Halcón Milenario"
"HWK-290 Expansion Pack": "Pack de Expansión HWK-290"
"TIE Fighter Expansion Pack": "Pack de Expansión Caza TIE"
"TIE Interceptor Expansion Pack": "Pack de Expansión Interceptor TIE"
"TIE Bomber Expansion Pack": "Pack de Expansión Bombardero TIE"
"TIE Advanced Expansion Pack": "Pack de Expansión TIE Avanzado"
"Lambda-Class Shuttle Expansion Pack": "Pack de Expansión Lanzadera clase LAmbda"
"Slave I Expansion Pack": "Pack de Expansión Esclavo 1"
"Imperial Aces Expansion Pack": "Pack de Expansión Ases Imperiales"
"Rebel Transport Expansion Pack": "Pack de Expansión Transporte Rebelde"
"Z-95 Headhunter Expansion Pack": "Pack de Expansión Z-95 Cazacabezas"
"TIE Defender Expansion Pack": "Pack de Expansión Defensor TIE"
"E-Wing Expansion Pack": "Pack de Expansión Ala-E"
"TIE Phantom Expansion Pack": "Pack de Expansión TIE Fantasma"
"Tantive IV Expansion Pack": "Pack de Expansión Tantive IV"
"Rebel Aces Expansion Pack": "Pack de Expansión Ases Rebeldes"
"YT-2400 Freighter Expansion Pack": "Pack de Expansión Carguero YT-2400"
"VT-49 Decimator Expansion Pack": "Pack de Expansión VT-49 Diezmador"
"StarViper Expansion Pack": "Pack de Expansión Víbora Estelar"
"M3-A Interceptor Expansion Pack": "Pack de Expansión Interceptor M3-A"
"IG-2000 Expansion Pack": "Pack de Expansión IG-2000"
"Most Wanted Expansion Pack": "Pack de Expansión Los Más Buscados"
"Imperial Raider Expansion Pack": "Pack de Expansión Incursor Imperial"
"K-Wing Expansion Pack": "Pack de Expansión Ala-K"
"TIE Punisher Expansion Pack": "Pack de Expansión Castigador TIE"
"Kihraxz Fighter Expansion Pack": "Pack de Expansión Caza Kihraxz"
"Hound's Tooth Expansion Pack": "Pack de Expansión Diente de Perro"
"The Force Awakens Core Set": "Caja Básica El Despertar de la Fuerza"
"T-70 X-Wing Expansion Pack": "Pack de Expansión T-70 Ala-X"
"TIE/fo Fighter Expansion Pack": "Pack de Expansión Caza TIE/fo"
"Imperial Assault Carrier Expansion Pack": "Pack de Expansión Portacazas de Asalto Imperial"
"Ghost Expansion Pack": "Pack de Expansión Espíritu"
"Inquisitor's TIE Expansion Pack": "Pack de Expansión TIE del Inquisidor"
"Mist Hunter Expansion Pack": "Pack de Expansión Cazador de la Niebla"
"Punishing One Expansion Pack": "Pack de Expansión Castigadora"
"Imperial Veterans Expansion Pack": "Pack de Expansión Veteranos Imperiales"
"Protectorate Starfighter Expansion Pack": "Pack de Expansión Caza estelar del Protectorado"
"Shadow Caster Expansion Pack": "Pack de Expansión Sombra Alargada"
"Special Forces TIE Expansion Pack": "Pack de Expansión TIE de las Fuerzas Especiales"
"ARC-170 Expansion Pack": "Pack de Expansión ARC-170"
"U-Wing Expansion Pack": "Pack de Expansión Ala-U"
"TIE Striker Expansion Pack": "Pack de Expansión Fustigador TIE"
"Upsilon-class Shuttle Expansion Pack": "Pack de Expansión Lanzadera clase Ípsilon"
"Sabine's TIE Fighter Expansion Pack": "Pack de Expansión Caza TIE de Sabine"
"Quadjumper Expansion Pack": "Pack de Expansión Saltador Quad"
"C-ROC Cruiser Expansion Pack": "Pack de Expansión Crucero C-ROC"
"TIE Aggressor Expansion Pack": "Pack de Expansión Tie Agresor"
"Scurrg H-6 Bomber Expansion Pack": "Pack de Expansión Bombardero Scurrg H-6"
"Auzituck Gunship Expansion Pack": "Pack de Expansión Cañonera Auzituck"
"TIE Silencer Expansion Pack": "Pack de Expansión Silenciador TIE"
"Alpha-class Star Wing Expansion Pack": "Pack de Expansión Ala Estelar clase Alfa"
"Resistance Bomber Expansion Pack": "Pack de Expansión Bombardero de la Resistencia"
"Phantom II Expansion Pack": "Pack de Expansión Fantasma II"
"Kimogila Fighter Expansion Pack": "Pack de Expansión Caza M12-L Kimogila"
"Saw's Renegades Expansion Pack": "Pack de Expansión Renegados de Saw"
"TIE Reaper Expansion Pack": "Pack de Expansión Segador TIE"
ui:
shipSelectorPlaceholder: "Selecciona una nave"
pilotSelectorPlaceholder: "Selecciona un piloto"
upgradePlaceholder: (translator, language, slot) ->
switch slot
when 'Elite'
"Sin Talento de Élite"
when 'Astromech'
"Sin Droide Astromecánico"
when 'Illicit'
"Sin Mejora Ilícita"
when 'Salvaged Astromech'
"Sin Droide Astromech Remendado"
else
"Sin Mejora de #{translator language, 'slot', slot}"
modificationPlaceholder: "Sin Modificación"
titlePlaceholder: "Sin Título"
upgradeHeader: (translator, language, slot) ->
switch slot
when 'Elite'
"Talento de Élite"
when 'Astromech'
"Droide Astromecánico"
when 'Illicit'
"Mejora Ilícita"
when 'Salvaged Astromech'
"Droide Astromech Remendado"
else
"Mejora de #{translator language, 'slot', slot}"
unreleased: "inédito"
epic: "épico"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'This squad uses unreleased content!'
'.epic-content-used .translated': 'This squad uses Epic content!'
'.illegal-epic-too-many-small-ships .translated': 'You may not field more than 12 of the same type Small ship!'
'.illegal-epic-too-many-large-ships .translated': 'You may not field more than 6 of the same type Large ship!'
'.collection-invalid .translated': 'You cannot field this list with your collection!'
# Type selector
'.game-type-selector option[value="standard"]': 'Standard'
'.game-type-selector option[value="custom"]': 'Custom'
'.game-type-selector option[value="epic"]': 'Epic'
'.game-type-selector option[value="team-epic"]': 'Team Epic'
'.xwing-card-browser .translate.sort-cards-by': 'Ordenar cartas por'
'.xwing-card-browser option[value="name"]': 'Nombre'
'.xwing-card-browser option[value="source"]': 'Fuente'
'.xwing-card-browser option[value="type-by-points"]': 'Tipo (por Puntos)'
'.xwing-card-browser option[value="type-by-name"]': 'Tipo (por Nombre)'
'.xwing-card-browser .translate.select-a-card': 'Selecciona una carta del listado de la izquierda.'
# Info well
'.info-well .info-ship td.info-header': 'Nave'
'.info-well .info-skill td.info-header': 'Habilidad'
'.info-well .info-actions td.info-header': 'Acciones'
'.info-well .info-upgrades td.info-header': 'Mejoras'
'.info-well .info-range td.info-header': 'Alcance'
# Squadron edit buttons
'.clear-squad' : 'Nuevo Escuadron'
'.save-list' : 'Grabar'
'.save-list-as' : 'Grabar como...'
'.delete-list' : 'Eliminar'
'.backend-list-my-squads' : 'Cargar Escuadron'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Imprimir/Ver como </span>Text'
'.randomize' : 'Aleatorio!'
'.randomize-options' : 'Opciones de aleatoriedad…'
'.notes-container > span' : 'Squad Notes'
# Print/View modal
'.bbcode-list' : 'Copia el BBCode de debajo y pegalo en el post de tu foro.<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.vertical-space-checkbox' : """Añade espacio para cartas de daño/mejora cuando imprima. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Imprima en color. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="fa fa-print"></i> Imprimir'
# Randomizer options
'.do-randomize' : 'Genera Aleatoriamente!'
# Top tab bar
'#empireTab' : 'Imperio Galactico'
'#rebelTab' : 'Alianza Rebelde'
'#scumTab' : 'Escoria y Villanos'
'#browserTab' : 'Explorador de Cartas'
'#aboutTab' : 'Acerca de'
singular:
'pilots': 'Piloto'
'modifications': 'Modificación'
'titles': 'Título'
types:
'Pilot': 'Piloto'
'Modification': 'Modificación'
'Title': 'Título'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders['Español'] = () ->
exportObj.cardLanguage = 'Español'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# ship translations
exportObj.renameShip 'Lambda-Class Shuttle', 'Lanzadera clase Lambda'
exportObj.renameShip 'TIE Advanced', 'TIE Avanzado'
exportObj.renameShip 'TIE Bomber', 'Bombardero TIE'
exportObj.renameShip 'TIE Fighter', 'Caza TIE'
exportObj.renameShip 'TIE Interceptor', 'Interceptor TIE'
exportObj.renameShip 'TIE Phantom', 'TIE Fantasma'
exportObj.renameShip 'TIE Defender', 'Defensor TIE'
exportObj.renameShip 'TIE Punisher', 'Castigador TIE'
exportObj.renameShip 'TIE Advanced Prototype', 'Prototipo de TIE Avanzado'
exportObj.renameShip 'VT-49 Decimator', 'VT-49 Diezmador'
exportObj.renameShip 'TIE/fo Fighter', 'Caza TIE/fo'
exportObj.renameShip 'TIE/sf Fighter', 'Caza TIE/sf'
exportObj.renameShip 'TIE Striker', 'Fustigador TIE'
exportObj.renameShip 'Upsilon-class Shuttle', 'Lanzadera clase Ípsilon'
exportObj.renameShip 'TIE Aggressor', 'TIE Agresor'
exportObj.renameShip 'TIE Silencer', 'Silenciador TIE'
exportObj.renameShip 'Alpha-class Star Wing', 'Ala Estelar clase Alfa'
exportObj.renameShip 'TIE Reaper', 'Segador TIE'
exportObj.renameShip 'A-Wing', 'Ala-A'
exportObj.renameShip 'B-Wing', 'Ala-B'
exportObj.renameShip 'E-Wing', 'Ala-E'
exportObj.renameShip 'X-Wing', 'Ala-X'
exportObj.renameShip 'Y-Wing', 'Ala-Y'
exportObj.renameShip 'K-Wing', 'Ala-K'
exportObj.renameShip 'Z-95 Headhunter', 'Z-95 Cazacabezas'
exportObj.renameShip 'Attack Shuttle', 'Lanzadera de Ataque'
exportObj.renameShip 'CR90 Corvette (Aft)', 'Corbeta CR90 (Popa)'
exportObj.renameShip 'CR90 Corvette (Fore)', 'Corbeta CR90 (Proa)'
exportObj.renameShip 'GR-75 Medium Transport', 'Transporte mediano GR-75'
exportObj.renameShip 'T-70 X-Wing', 'T-70 Ala-X'
exportObj.renameShip 'U-Wing', 'Ala-U'
exportObj.renameShip 'Auzituck Gunship', 'Cañonera Auzituck'
exportObj.renameShip 'B/SF-17 Bomber', 'Bombardero B/SF-17'
exportObj.renameShip 'Sheathipede-class Shuttle', 'Lanzadera clase Sheathipede'
exportObj.renameShip 'M3-A Interceptor', 'Interceptor M3-A'
exportObj.renameShip 'StarViper', 'Víbora Estelar'
exportObj.renameShip 'Aggressor', 'Agresor'
exportObj.renameShip 'Kihraxz Fighter', 'Caza Kihraxz'
exportObj.renameShip 'G-1A Starfighter', 'Caza Estelar G-1A'
exportObj.renameShip 'JumpMaster 5000', 'Saltador Maestro 5000'
exportObj.renameShip 'Protectorate Starfighter', 'Caza Estelar del Protectorado'
exportObj.renameShip 'Lancer-class Pursuit Craft', 'Nave de persecución clase Lancero'
exportObj.renameShip 'Quadjumper', 'Saltador Quad'
exportObj.renameShip 'C-ROC Cruiser', 'Crucero C-ROC'
exportObj.renameShip 'Scurrg H-6 Bomber', 'B<NAME> H-6'
exportObj.renameShip 'M12-L Kimogila Fighter', 'Caza M12-L Kimogila'
pilot_translations =
"Wedge Antilles":
text: """Cuando ataques, la Agilidad del piloto se reduce en 1 (hasta un mínimo de 0)."""
ship: "Ala-X"
"<NAME>":
text: """Después de gastar una ficha de Concentración, en vez de descartarla puedes asignar esa ficha a cualquier otra nave aliada que tengas a alcance 1-2."""
ship: "Ala-X"
"Red Squadron Pilot":
name: "Piloto del escuadrón Rojo"
ship: "Ala-X"
"<NAME> Pilot":
name: "<NAME>"
ship: "Ala-X"
"Biggs Darklighter":
text: """Las demás naves aliadas que tengas a alcance 1 no pueden ser seleccionadas como objetivo de ataques si en vez de eso el atacante pudiese seleccionarte a tí como objetivo."""
ship: "Ala-X"
"<NAME>walker":
text: """Cuando te defiendas en combate puedes cambiar 1 de tus resultados %FOCUS% por un resultado %EVADE%."""
ship: "Ala-X"
"Gray Squadron Pilot":
name: "Piloto del escuadrón Gris"
ship: "Ala-Y"
'"Dutch" Vander':
text: """Después de que fijes un blanco, elige otra nave aliada que tengas a alcance 1-2. La nave elegida podrá fijar un blanco inmediatamente."""
ship: "Ala-Y"
"<NAME>":
text: """Cuando ataques a alcance 2-3, puedes volver a lanzar cualesquier dados en los que hayas sacado caras vacías."""
ship: "Ala-Y"
"Gold Squadron Pilot":
name: "Piloto del escuadrón Oro"
ship: "Ala-Y"
"Academy Pilot":
name: "Piloto de la Academia"
ship: "Caza TIE"
"Obsidian Squadron Pilot":
name: "Piloto del escuadrón Obsidiana"
ship: "Caza TIE"
"Black Squadron Pilot":
name: "Piloto del escuadrón Negro"
ship: "Caza TIE"
'"<NAME>"':
name: '"<NAME>"'
text: """Cuando ataques a alcance 1, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%"""
ship: "Caza TIE"
'"Night Beast"':
name: '"<NAME>"'
text: """Después de que ejecutes una maniobra verde, puedes realizar una acción gratuita de Concentración"""
ship: "Caza TIE"
'"Backstabber"':
name: '"<NAME>"'
text: """Cuando ataques desde fuera del arco de fuego del defensor, tira 1 dado de ataque adicional."""
ship: "Caza TIE"
'"Dark <NAME>se"':
name: '"<NAME>"'
text: """Cuando te defiendas en combate, las naves que te ataquen no podrán gastar fichas de Concentración ni volver a tirar dados de ataque."""
ship: "Caza TIE"
'"<NAME>"':
name: '"<NAME>"'
text: """Si atacas a alcance 1, tira 1 dado de ataque adicional."""
ship: "Caza TIE"
'"<NAME>"':
name: '"<NAME>"'
text: """Cuando otra nave aliada que tengas a alcance 1 ataque con su armamento principal, podrá volver a tirar 1 dado de ataque."""
ship: "Caza TIE"
"Tempest Squadron Pilot":
name: "Piloto del escuadrón Tempestad"
ship: "TIE Avanzado"
"Storm Squadron Pilot":
name: "Piloto del escuadrón Tormenta"
ship: "TIE Avanzado"
"<NAME>":
text: """Cuando tu ataque inflija una carta de Daño boca arriba al defensor, en vez de eso roba 3 cartas de Daño, elige 1 de ellas a tu elección y luego descarta las otras."""
ship: "TIE Avanzado"
"<NAME>":
text: """Puedes llevar a cabo dos acciones durante tu paso de acción."""
ship: "TIE Avanzado"
"Alpha Squadron Pilot":
name: "Piloto del escuadrón Alfa"
ship: "Interceptor TIE"
"Avenger Squadron Pilot":
name: "Piloto del escuadrón Vengador"
ship: "Interceptor TIE"
"Saber Squadron Pilot":
name: "Piloto del escuadrón Sable"
ship: "Interceptor TIE"
"\"Fel's Wrath\"":
name: '"<NAME>"'
ship: "Interceptor TIE"
text: """Cuando tengas asignadas tantas cartas de Daño como tu Casco o más, no serás destruido hasta el final de la fase de Combate."""
"<NAME>":
ship: "Interceptor TIE"
text: """Después de que efectúes un ataque, puedes llevar a cabo una acción gratuita de impulso o tonel volado."""
"<NAME>":
ship: "Interceptor TIE"
text: """Cuando recibas una ficha de Tensión, puedes asignar 1 ficha de Concentración a tu nave."""
"<NAME>":
text: """Puedes realizar acciones incluso aunque tengas fichas de Tensión."""
ship: "Ala-A"
"Arvel Crynyd":
text: """Puedes designar como objetivo de tu ataque a una nave enemiga que esté dentro de tu arco de ataque y en contacto contigo."""
ship: "Ala-A"
"Green Squadron Pilot":
name: "Piloto del escuadrón Verde"
ship: "Ala-A"
"Prototype Pilot":
name: "Piloto de pruebas"
ship: "Ala-A"
"Outer Rim Smuggler":
name: "Contrabandista del Borde Exterior"
"Che<NAME>":
text: """Cuando recibas una carta de Daño boca arriba, ponla boca abajo inmediatamente sin resolver su texto de reglas."""
"<NAME>":
text: """Después de que ejecutes una maniobra verde, elige otra nave aliada que tengas a alcance 1. Esa nave podrá realizar una acción gratuita de las indicadas en su barra de acciones."""
"<NAME>":
text: """Cuando ataques, puedes volver a tirar todos tus dados. Si decides hacerlo, debes volver a tirar tantos como te sea posible."""
"<NAME>":
name: "<NAME>"
"<NAME>":
text: """Cuando ataques, el defensor recibe 1 ficha de Tensión si anula al menos 1 resultado %CRIT%."""
"<NAME>":
text: """Cuando realices una maniobra de inclinación (%BANKLEFT% o %BANKRIGHT%), puedes girar tu selector de maniobras para escoger la otra maniobra de inclinación de la misma velocidad."""
"<NAME>":
text: """Cuando ataques con un armamento secundario, puedes volver a tirar 1 dado de ataque."""
"Ten Numb":
text: """Cuando atacas, 1 de tus resultados %CRIT% no puede ser anulado por los dados de defensa."""
ship: "Ala-B"
"Ibtisam":
text: """Cuando atacas o te defiendes, si tienes al menos 1 ficha de Tensión, puedes volver a tirar 1 de tus dados."""
ship: "Ala-B"
"Dagger Squadron Pilot":
name: "Piloto del escuadrón Daga"
ship: "Ala-B"
"Blue Squadron Pilot":
name: "Piloto del escuadrón Azul"
ship: "Ala-B"
"Rebel Operative":
name: "<NAME>"
ship: "HWK-290"
"<NAME>":
text: """Al comienzo de la fase de Combate, elige otra nave aliada que tengas a alcance 1-3. Hasta el final de la fase, se considera que el piloto de esa nave tiene habilidad 12."""
ship: "HWK-290"
"<NAME>":
text: """Al comienzo de la fase de Combate, puedes asignar 1 de tus fichas de Concentración a otra nave aliada que tengas a alcance 1-3."""
ship: "HWK-290"
"<NAME>":
text: """Cuando otra nave aliada que tengas a alcance 1-3 efectúe un ataque, si no tienes fichas de Tensión puedes recibir 1 ficha de Tensión para que esa nave tire 1 dado de ataque adicional."""
ship: "HWK-290"
"Scimitar Squadron Pilot":
name: "Piloto del escuadrón Cimitarra"
ship: "Bombardero TIE"
"Gamma Squadron Pilot":
name: "Piloto del escuadrón Gamma"
ship: "Bombardero TIE"
"Gamma Squadron Veteran":
name: "<NAME> escuadrón <NAME>"
ship: "Bombardero TIE"
"<NAME>":
name: "<NAME>"
ship: "Bombardero TIE"
text: """Cuando otra nave aliada que tengas a alcance 1 ataque con un sistema de armamento secundario, puede volver a tirar un máximo de 2 dados de ataque."""
"<NAME>":
name: "<NAME>"
ship: "Bombardero TIE"
text: """Cuando atacas con un sistema de armamento secundario, puedes incrementar o reducir en 1 el alcance del arma (hasta un límite de alcance comprendido entre 1 y 3)."""
"Omicron Group Pilot":
name: "Pi<NAME>to del grupo Ó<NAME>"
ship: "Lanzadera clase Lambda"
"<NAME>":
name: "<NAME>"
text: """Cuando una nave enemiga fije un blanco, deberá fijar tu nave como blanco (si es posible)."""
ship: "Lanzadera clase Lambda"
"<NAME>":
name: "<NAME>"
text: """Al comienzo de la fase de Combate, puedes asignar 1 de tus fichas azules de Blanco Fijado a una nave aliada que tengas a alcance 1 si no tiene ya una ficha azul de Blanco Fijado."""
ship: "Lanzadera clase Lambda"
"<NAME>":
name: "<NAME>"
text: """Cuando otra nave aliada que tengas a alcance 1-2 vaya a recibir una ficha de Tensión, si tienes 2 fichas de Tensión o menos puedes recibirla tú en su lugar."""
ship: "Lanzadera clase Lambda"
"<NAME>":
ship: "Interceptor TIE"
text: """Cuando realices una acción de tonel volado, puedes recibir 1 ficha de Tensión para utilizar la plantilla (%BANKLEFT% 1) o la de (%BANKRIGHT% 1) en vez de la plantilla de (%STRAIGHT% 1)."""
"Royal Guard Pilot":
name: "<NAME> la Guard<NAME>"
ship: "Interceptor TIE"
"<NAME>":
ship: "Interceptor TIE"
text: """Cuando reveles una maniobra %UTURN%, puedes ejecutarla como si su velocidad fuese de 1, 3 ó 5."""
"<NAME>":
ship: "Interceptor TIE"
text: """Cuando ataques desde alcance 2-3, puedes gastar 1 ficha de Evasión para añadir 1 resultado %HIT% a tu tirada."""
"<NAME>":
ship: "Interceptor TIE"
text: """Las naves enemigas que tengas a alcance 1 no pueden realizar acciones de Concentración o Evasión, y tampoco pueden gastar fichas de Concentración ni de Evasión."""
"GR-75 Medium Transport":
name: "Transporte mediano GR-75"
ship: "Transporte mediano GR-75"
"Bandit Squadron Pilot":
name: "Piloto del escuadrón B<NAME>o"
ship: "Z-95 Cazacabezas"
"Tala Squadron Pilot":
name: "Piloto del escuadrón Tala"
ship: "Z-95 Cazacabezas"
"<NAME>":
name: "<NAME>"
text: """Cuando ataques, el defensor es alcanzado por tu ataque, incluso aunque no sufra ningún daño."""
ship: "Z-95 Cazacabezas"
"<NAME>":
name: "<NAME>"
text: """Después de que realices un ataque, puedes elegir otra nave aliada a alcance 1. Esa nave puede llevar a cabo 1 acción gratuita."""
ship: "Z-95 Cazacabezas"
"Delta Squadron Pilot":
name: "Piloto del escuadrón Delta"
ship: "Defensor TIE"
"Onyx Squadron Pilot":
name: "Piloto del escuadrón Ónice"
ship: "Defensor TIE"
"<NAME>":
name: "<NAME>"
text: """Cuando ataques, inmediatamente después de tirar los dados de ataque puedes fijar al defensor como blanco si éste ya tiene asignada una ficha de Blanco Fijado."""
ship: "Defensor TIE"
"<NAME>":
text: """Después de que efectúes un ataque que inflinja al menos 1 carta de Daño al defensor, puedes gastar 1 ficha de Concentración para poner esas cartas boca arriba."""
ship: "Defensor TIE"
"Knave Squadron Pilot":
name: "Piloto del escuadrón Canalla"
ship: "Ala-E"
"Blackmoon Squadron Pilot":
name: "Piloto del escuadrón L<NAME>"
ship: "Ala-E"
"<NAME>":
text: """Cuando una nave neemiga situada dentro de tu arco de fuego a alcance 1-3 se defienda, el atacante puede cambiar 1 de sus resultados %HIT% por 1 resultado %CRIT%."""
ship: "Ala-E"
"<NAME>":
text: """Puedes efectuar 1 ataque al comienzo de la fase Final, pero si lo haces no podrás atacar en la ronda siguiente."""
ship: "Ala-E"
"Sigma Squadron Pilot":
name: "Piloto del escuadrón <NAME>"
ship: "TIE Fantasma"
"Shadow Squadron Pilot":
name: "Piloto del escuadrón Sombra"
ship: "TIE Fantasma"
'"Echo"':
name: '"<NAME>"'
text: """Cuando desactives tu camuflaje, debes usar la plantilla de maniobra (%BANKLEFT% 2) o la de (%BANKRIGHT% 2) en lugar de la plantilla (%STRAIGHT% 2)."""
ship: "TIE Fantasma"
'"<NAME>"':
name: '"<NAME>"'
text: """Después de que efectúes un ataque que impacte, puedes asignar una ficha de Concentración a tu nave."""
ship: "TIE Fantasma"
"CR90 Corvette (Fore)":
name: "<NAME>beta CR90 (Proa)"
ship: "Corbeta CR90 (Proa)"
text: """Cuando ataques con tu armamento principal, puedes gastar 1 de Energía para tirar 1 dado de ataque adicional."""
"CR90 Corvette (Aft)":
name: "<NAME> CR90 (Popa)"
ship: "Corbeta CR90 (Popa)"
"<NAME>":
text: """Después de que efectúes un ataque, puedes eliminar 1 ficha de Concentración, Evasión o Blanco Fijado (azul) del defensor."""
ship: "Ala-X"
"<NAME>":
text: """Cuando recibas una ficha de Tensión, puedes descartarla y tirar 1 dado de ataque. Si sacas %HIT%, esta nave recibe 1 carta de Daño boca abajo."""
ship: "Ala-X"
'"<NAME>" <NAME>':
text: """Cuando fijes un blanco o gastes una ficha de Blanco Fijado, puedes quitar 1 ficha de Tensión de tu nave."""
ship: "Ala-X"
"<NAME>":
text: """Cuando una nave enemiga te declare como objetivo de un ataque, puedes fijar esa nave como blanco."""
ship: "Ala-X"
"<NAME>":
text: """Después de que realices una acción de Concentración o te asignen una ficha de Concentración, puedes efectuar una acción gratuita de impulso o tonel volado."""
ship: "Ala-A"
"<NAME>":
text: """Mientras te encuentres a alcance 1 de al menos 1 nave enemiga, tu Agilidad aumenta en 1."""
ship: "Ala-A"
"<NAME>":
text: """Cuando ataques, puedes quitarte 1 ficha de Tensión para cambiar todos tus resultados %FOCUS% por %HIT%."""
ship: "Ala-B"
"<NAME>":
text: """Puedes efectuar ataques con armamentos secundarios %TORPEDO% contra naves enemigas fuera de tu arco de fuego."""
ship: "Ala-B"
# "CR90 Corvette (Crippled Aft)":
# name: "CR90 Corvette (Crippled Aft)"
# ship: "Corbeta CR90 (Popa)"
# text: """No puedes seleccionar ni ejecutar maniobras (%STRAIGHT% 4), (%BANKLEFT% 2), o (%BANKRIGHT% 2)."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90 Corvette (Crippled Fore)"
# ship: "Corbeta CR90 (Proa)"
"Wild Space Fringer":
name: "Fronterizo del Espacio Salvaje"
ship: "YT-2400"
"Dash Rendar":
text: """Puedes ignorar obstáculos durante la fase de Activación y al realizar acciones."""
'"Leebo"':
text: """Cuando recibas una carta de Daño boca arriba, roba 1 carta de Daño adicional, resuelve 1 de ellas a tu elección y descarta la otra."""
"<NAME>":
text: """Si efectúas un ataque con un armamento principal contra una nave que tenga fichas de Tensión, tiras 1 dado de ataque adicional."""
"Patrol Leader":
name: "<NAME>"
ship: "VT-49 Diezmador"
"<NAME>":
name: "<NAME>"
text: """Cuando atacas a alcance 1-2, puedes cambiar 1 de tus resultados de %FOCUS% por un resultado %CRIT%."""
ship: "VT-49 Diezmador"
"<NAME>":
ship: "VT-49 Diezmador"
name: "<NAME>"
text: """Si no te quedan escudos y tienes asignada al menos 1 carta de Daño, tu Agilidad aumenta en 1."""
"<NAME>":
name: "<NAME>"
text: """Después de ejecutar un maniobra, toda nave enemiga con la que estés en contacto sufre 1 daño."""
ship: "VT-49 Diezmador"
"Black Sun Enforcer":
name: "Ejecutor del Sol Negro"
ship: "Víbora Estelar"
"Black Sun Vigo":
name: "Vigo del Sol Negro"
ship: "Víbora Estelar"
"<NAME>":
name: "<NAME>"
text: """Cuando te defiendas, una nave aliada que tengas a alcance 1 puede sufrir en tu lugar 1 resultado %HIT% o %CRIT% no anulado."""
ship: "Víbora Estelar"
"<NAME>":
text: """Al comienzo de la fase de Combate, si tienes alguna nave enemiga a alcance 1 puedes asignar 1 ficha de Concentración a tu nave."""
ship: "Víbora Estelar"
"<NAME>":
name: "<NAME>"
ship: "Interceptor M3-A"
"Tansarii Point Veteran":
name: "<NAME>"
ship: "Interceptor M3-A"
"<NAME>":
text: """Cuando otra nave aliada situada a alcance 1 se defienda, puede volver a tirar 1 dado de defensa."""
ship: "Interceptor M3-A"
"<NAME>":
text: """Después de que te hayas defendido de un ataque, si el ataque no impactó, puedes asignar 1 ficha de Evasión a tu nave."""
ship: "Interceptor M3-A"
"IG-88A":
text: """Después de que efectúes un ataque que destruya al defensor, puedes recuperar 1 ficha de Escudos."""
ship: "Agresor"
"IG-88B":
text: """Una vez por ronda, después de que efectúes un ataque y lo falles, puedes efectuar un ataque con un sistema de armamento secundario %CANNON% que tengas equipado."""
ship: "Agresor"
"IG-88C":
text: """Después de que realices una acción de impulso, puedes llevar a cabo una acción gratuita de Evasión."""
ship: "Agresor"
"IG-88D":
text: """Puedes ejecutar la maniobra (%SLOOPLEFT% 3) o (%SLOOPRIGHT% 3) utilizando la plantilla (%TURNLEFT% 3) o (%TURNRIGHT% 3) correspondiente."""
ship: "Agresor"
"<NAME>":
name: "<NAME>"
"<NAME> (Scum)":
text: """Cuando ataques o te defiendas, puedes volver a tirar 1 de tus dados por cada nave enemiga que tengas a alcance 1."""
"<NAME> (Scum)":
text: """Cuando ataques una nave que esté dentro de tu arco de fuego auxiliar, tira 1 dado de ataque adicional."""
"<NAME>":
text: """Cuando sueltes una bomba, puedes utilizar la plantilla de maniobra [%TURNLEFT% 3], [%STRAIGHT% 3] o [%TURNRIGHT% 3] en vez de la plantilla de [%STRAIGHT% 1]."""
"<NAME>":
ship: "Ala-Y"
text: """Cuando ataques una nave que esté fuera de tu arco de fuego, tira 1 dado de ataque adicional."""
"<NAME>":
ship: "Ala-Y"
text: """Después de gastar una ficha de Blanco Fijado, puedes recibir 1 ficha de Tensión para fijar un blanco."""
"<NAME>":
name: "<NAME>"
ship: "Ala-Y"
"<NAME>":
name: "<NAME>"
ship: "Ala-Y"
"<NAME>":
name: "<NAME>"
ship: "HWK-290"
"<NAME>":
text: """Cuando una nave enemiga a alcance 1-3 reciba como mínimo 1 ficha de iones, si no tienes fichas de Tensión puedes recibir 1 ficha de Tensión para que esa nave sufra 1 de daño."""
ship: "HWK-290"
"<NAME>":
text: """Al comienzo de la fase de Combate, puedes quitar 1 ficha de Concentración o Evasión de una nave enemiga a alcance 1-2 y asignar esa ficha a tu nave."""
"<NAME>":
text: """Al final de la fase de Activación, elige 1 nave enemiga a alcance 1-2. Hasta el final de la fase de Combate, se considera que el piloto de esa nave tiene Habilidad 0."""
"<NAME>":
name: "<NAME>"
ship: "Z-95 Cazacabezas"
"Black <NAME>":
name: "<NAME>"
ship: "Z-95 Cazacabezas"
"<NAME>":
text: """Cuando ataques, si no tienes ninguna otra nave aliada a alcance 1-2, tira 1 dado de ataque adicional."""
ship: "Z-95 Cazacabezas"
"<NAME>":
text: """Al comienzo de la fase de Combate, puedes quitar 1 ficha de Concentración o Evasión de otra nave aliada que tengas a alcance 1-2 y asignar esa ficha a tu nave."""
ship: "Z-95 Cazacabezas"
"<NAME>":
name: "<NAME>"
ship: "TIE Avanzado"
text: """Al comienzo de la fase de Combate, puedes fijar como blanco una nave enemiga que tengas a alcance 1."""
"<NAME>":
ship: "TIE Avanzado"
text: """Cuando reveles tu maniobra, puedes incrementar o reducir en 1 la velocidad de la maniobra (hasta un mínimo de 1)."""
"<NAME>":
ship: "TIE Avanzado"
text: """Las naves enemigas que tengas a alcance 1 no pueden aplicar su modificador al combate por alcance cuando ataquen."""
"<NAME>":
name: "<NAME>"
ship: "TIE Avanzado"
text: """Al comienzo de la fase Final, puedes gastar una de tus fichas de Blanco fijado asignadas a una nave enemiga para seleccionar al azar y poner boca arriba 1 carta de Daño que esa nave tenga asignada boca abajo."""
"<NAME>":
text: """Cuando una nave aliada declare un ataque, puedes gastar una ficha de Blanco Fijado que hayas asignado al defensor para reducir su Agilidad en 1 contra el ataque declarado."""
"<NAME>":
ship: 'Ala-K'
text: """Una vez por ronda, cuando ataques, puedes elegir entre gastar 1 de Escudos para tirar 1 dado de ataque adicional <strong>o bien</strong> tirar 1 dado de ataque menos para recuperar 1 de Escudos."""
"<NAME>":
ship: 'Ala-K'
text: """Cuando otra nave aliada que tengas a alcance 1-2 esté atacando, puede usar tus fichas de Concentración."""
"Guardian Squadron Pilot":
name: "Pi<NAME>to del Escuadrón Guardián"
ship: 'Ala-K'
"Warden Squadron Pilot":
name: "Piloto del Escuadrón Custodio"
ship: 'Ala-K'
'"Redline"':
name: '"<NAME>"'
ship: 'Castigador TIE'
text: """Puedes mantener 2 blancos fijados sobre una misma nave. Cuando fijes un blanco, puedes fijar la misma nave como blanco por segunda vez."""
'"Deathrain"':
name: '"<NAME>"'
ship: 'Castigador TIE'
text: """Cuando sueltes una bomba, puedes usar los salientes frontales de la peana de tu nave. Puedes realizar una acción gratuita de tonel volado después de soltar una bomba."""
'Black Eight Squadron Pilot':
name: "<NAME>"
ship: 'Castigador TIE'
'Cutlass Squadron Pilot':
name: "<NAME>"
ship: 'Castigador TIE'
"Moralo Eval":
text: """Puedes efectuar ataques con sistemas de armamento secundarios %CANNON% contra naves que estén dentro de tu arco de fuego auxiliar."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"<NAME>"':
name: "<NAME>"
ship: "Caza TIE"
text: """Cuando ataques a un defensor que tiene 1 o más cartas de Daño, tira 1 dado de ataque adicional."""
"The In<NAME>itor":
name: "<NAME>"
ship: "Prototipo de TIE Avanzado"
text: """Cuando ataques con tu armamento principal a alcance 2-3, el alcance del ataque se considera 1."""
"<NAME>":
ship: "Caza Estelar G-1A"
text: """Cuando ataques, puedes tirar 1 dado de ataque adicional. Si decides hacerlo, el defensor tira 1 dado de defensa adicional."""
"R<NAME>less <NAME>elancer":
name: "<NAME>"
ship: "Caza Estelar G-1A"
"<NAME>":
name: "<NAME>"
ship: "Caza Estelar G-1A"
"<NAME>":
ship: "Saltador Maestro 5000"
text: """Una vez por ronda, después de que te defiendas, si el atacante está dentro de tu arco de fuego, puedes efectuar un ataque contra esa nave."""
"Talonbane Cobra":
ship: "Caza Kihraxz"
text: """Cuando ataques o te defiendas, duplica el efecto de tus bonificaciones al combate por alcance."""
"Gr<NAME>":
name: "<NAME>"
ship: "Caza Kihraxz"
text: """Cuando te defiendas, tira 1 dado de defensa adicional si el atacante está situado dentro de tu arco de fuego."""
"Black Sun Ace":
name: "As del Sol Negro"
ship: "Caza Kihraxz"
"<NAME>":
name: "<NAME>"
ship: "Caza Kihraxz"
"<NAME>":
name: "<NAME>"
ship: "YV-666"
"<NAME>":
ship: "YV-666"
text: """Cuando realices un ataque con éxito, antes de inflingir el daño puedes anular 1 de tus resultados %CRIT% para añadir 2 resultados %HIT%."""
# T-70
"<NAME>":
ship: "T-70 Ala-X"
text: """Cuando ataques o te defiendas, si tienes una ficha de Concentración, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%."""
'"Blue Ace"':
name: '"<NAME>"'
ship: "T-70 Ala-X"
text: """Cuando realices una acción de impulso, puedes utilizar la plantilla de maniobra (%TURNLEFT% 1) o (%TURNRIGHT% 1)."""
"Red Squadron Veteran":
name: "<NAME>"
ship: "T-70 Ala-X"
"Blue Squadron Novice":
name: "Novato del Esc. Azul"
ship: "T-70 Ala-X"
'"Red Ace"':
name: "<NAME>"
ship: "T-70 Ala-X"
text: '''La primera vez que quites una ficha de Escudos de tu nave en cada ronda, asigna 1 ficha de Evasión a tu nave.'''
# TIE/fo
'"Omega Ace"':
name: '"As Omega"'
ship: "Caza TIE/fo"
text: """Cuando ataques a un defensor que has fijado como blanco, puedes gastar las fichas de Blanco Fijado y una ficha de Concentración para cambiar todos tus resultados de dados por resultados %CRIT%."""
'"Epsilon Leader"':
name: '"<NAME>"'
ship: "Caza TIE/fo"
text: """Al comienzo de la fase de Combate, retira 1 ficha de Tensión de cada nave aliada que tengas a alcance 1."""
'"Zeta Ace"':
name: '"As Zeta"'
ship: "Caza TIE/fo"
text: """Cuando realices una acción de tonel volado, puedes utilizar la plantilla de maniobra (%STRAIGHT% 2) en vez de la plantilla (%STRAIGHT% 1)."""
"Omega Squadron Pilot":
name: "Piloto del Esc. Omega"
ship: "Caza TIE/fo"
"Zeta Squadron Pilot":
name: "Piloto del Esc. Zeta"
ship: "Caza TIE/fo"
"Epsilon Squadron Pilot":
name: "Piloto del Esc. Epsilon"
ship: "Caza TIE/fo"
'"Omega Leader"':
name: "<NAME>"
ship: "Caza TIE/fo"
text: '''Las naves enemigas que tienes fijadas como blanco no pueden modificar ningún dado cuando te atacan o se defienden de tus ataques.'''
'<NAME>':
text: '''Cuando reveles una maniobra verde o roja, puedes girar tu selector de maniobras para escoger otra maniobra del mismo color.'''
'"<NAME>"':
name: "<NAME>"
ship: "Caza TIE"
text: """Los Cazas TIE aliados que tengas a alcance 1-3 pueden realizar la acción de tu carta de Mejora %ELITE% equipada."""
'"<NAME>"':
ship: "Caza TIE"
text: """Cuando ataques, al comienzo del paso "Comparar los resultados", puedes anular todos los resultados de los dados. Si anulas al menos un resultado %CRIT%, inflinge 1 carta de Daño boca abajo al defensor."""
'"<NAME>"':
name: "<NAME>"
ship: "Caza TIE"
text: """Cuando otra nave aliada que tengas a alcance 1 gaste una ficha de Concentración, asigna 1 ficha de Concentración a tu nave."""
'<NAME>':
ship: "Lanzadera de Ataque"
text: """Cuando te defiendas, si estás bajo tensión, puedes cambiar hasta 2 de tus resultados %FOCUS% por resultados %EVADE%."""
'"<NAME> Leader"':
name: "<NAME>"
text: '''Cuando ataques, si no estás bajo tensión, puedes recibir 1 ficha de Tensión para tirar 1 dado de ataque adicional.'''
ship: "Caza TIE/fo"
'"Epsilon Ace"':
name: "<NAME>"
text: '''Mientras no tengas ninguna carta de Daño asignada, se considera que tienes Habilidad 12.'''
ship: "Caza TIE/fo"
"<NAME>":
text: """Cuando una nave enemiga que tengas a alcance 1-2 efectúe un ataque, puedes gastar una ficha de Concentración. Si decides hacerlo, el atacante tira 1 dado de ataque menos."""
'"<NAME>"':
text: """Al comienzo de la fase de Combate, toda nave enemiga con la que estés en contacto recibe 1 ficha de Tensión."""
'H<NAME> Syndulla (Attack Shuttle)':
name: "<NAME> (Lanzadera de Ataque)"
ship: "Lanzadera de Ataque"
text: """Cuando reveles una maniobra verde o roja, puedes girar tu selector de maniobras para escoger otra maniobra del mismo color."""
'<NAME>':
ship: "Lanzadera de Ataque"
text: """Inmediatamente antes de revelar tu maniobra, puedes realizar una acción gratuita de impulso o tonel volado."""
'"<NAME>':
ship: "Lanzadera de Ataque"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
"<NAME>":
name: "<NAME>"
ship: "VCX-100"
'<NAME>':
text: '''Una vez por ronda, después de que te descartes de una carta de Mejora %ELITE%, dale la vuelta a esa carta para ponerla boca arriba.'''
ship: "Bombardero TIE"
'<NAME>':
text: '''Mientras no estés bajo tensión, puedes ejecutar tus maniobras %TROLLLEFT% y %TROLLRIGHT% como maniobras blancas.'''
ship: "T-70 Ala-X"
"<NAME>":
text: """Después de que te defiendas, puedes ralizar una acción gratuita."""
ship: "Prototipo de TIE Avanzado"
"4-LOM":
ship: "Caza Estelar G-1A"
text: """Al comienzo de la fase Final, puedes asignar 1 de tus fichas de Tensión a otra nave que tengas a alcance 1."""
"Tel <NAME>":
ship: "Saltador Maestro 5000"
text: """La primrea vez que seas destruido, en vez de eso anula todo el daño restante, descarta todas tus cartas de Daño e inflinge 4 cartas de Daño boca abajo a esta nave."""
"<NAME>":
ship: "Saltador Maestro 5000"
text: """Al comienzo de la fase de Combate, puedes asignar a otra nave aliada a alcance 1 todas las fichas de Concentración, Evasión y Blanco Fijado que tengas asignadas."""
"Contracted Scout":
name: "<NAME>"
ship: "Saltador Maestro 5000"
'"Deathfire"':
name: "<NAME>"
text: '''Cuando reveles tu selector de maniobras o después de que realices una acción, puedes realizar una acción de carta de Mejora %BOMB% como acción gratuita.'''
ship: "Bombardero TIE"
"Sienar Test Pilot":
name: "Piloto de pruebas de Sienar"
ship: "Prototipo de TIE Avanzado"
"Baron of the Empire":
name: "<NAME>"
ship: "Prototipo de TIE Avanzado"
"<NAME> Stele (TIE Defender)":
name: "<NAME> (Defensor TIE)"
text: """Cuando tu ataque inflija una carta de Daño boca arriba al defensor, en vez de eso roba 3 cartas de Daño, elige 1 de ellas a tu elección y luego descarta las otras."""
ship: "Defensor TIE"
"<NAME>":
name: "<NAME>"
text: """Cuando reveles una maniobra %STRAIGHT%, puedes considerarla como una maniobra %KTURN%."""
ship: "Defensor TIE"
"Glaive Squadron Pilot":
name: "<NAME> del escu<NAME>"
ship: "Defensor TIE"
"<NAME> (PS9)":
text: """Cuando ataques o te defiendas, si tienes una ficha de Concentración, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%."""
ship: "T-70 Ala-X"
"Resistance Sympathizer":
name: "<NAME>atizante de la Resistencia"
ship: "YT-1300"
"Rey":
text: """Cuando ataques o te defiendas, si la nave enemiga está dentro de tu arco de fuego, puedes volver a tirar hasta 2 dados en los que hayas sacado caras vacías."""
'Han <NAME> (TFA)':
text: '''En el momento de desplegarte durante la preparación de la partida, se te puede colocar en cualquier parte de la zona de juego que esté más allá de alcance 3 de las naves enemigas.'''
'Che<NAME> (TFA)':
text: '''Después de que otra nave aliada que tengas a alcance 1-3 sea destruida (pero no hay aabandonado el campo de batalla), puedes efectuar un ataque.'''
'<NAME>':
ship: "ARC-170"
text: '''Cuando ataques o te defiendas, puedes gastar una ficha de Blanco fijado que tengas sobre la nave enemiga para añadir 1 resultado %FOCUS% a tu tirada.'''
'<NAME>':
ship: "ARC-170"
text: '''Cuando otra nave aliada que tengas a alcance 1-2 esté atacando, puede usar tus fichas azules de Blanco fijado como si fuesen suyas.'''
'<NAME>':
ship: "ARC-170"
text: '''Después de que una nave enemiga que tengas dentro de tu arco de fuego a alcance 1-3 ataque a otra nave aliada, puedes realizar una acción gratuita.'''
'<NAME>':
ship: "ARC-170"
text: '''Después de que ejecutes una maniobra, puedes tirar 1 dado de ataque. Si sacas %HIT% o %CRIT%, quita 1 ficha de Tensión de tu nave.'''
'"Quickdraw"':
name: "<NAME>"
ship: "Caza TIE/sf"
text: '''Una vez por ronda, cuando pierdas una ficha de Escudos, puedes realizar un ataque de armamento principal.'''
'"Backdraft"':
name: "<NAME>"
ship: "Caza TIE/sf"
text: '''Cuando ataques a una nave que esté dentro de tu arco de fuego auxiliar, puedes añadir 1 resultado %CRIT%.'''
'Omega Specialist':
name: "Especialista del Escuadrón Omega"
ship: "Caza TIE/sf"
'Zeta Specialist':
name: "Especialista del Escuadrón Zeta"
ship: "Caza TIE/sf"
'<NAME>':
ship: "Caza Estelar del Protectorado"
text: '''Cuando ataques o te defiendas, si tienes la nave enemiga a alcance 1, puedes tirar 1 dado adicional.'''
'<NAME>':
name: "<NAME>"
ship: "Caza Estelar del Protectorado"
text: '''Al comienzo de la fase de Combate, puedes elegir 1 nave enemiga que tengas a alcance 1. Si estás dentro de su arco de fuego, esa nave descarta todas sus fichas de Concentración y Evasión.'''
'<NAME>':
ship: "Caza Estelar del Protectorado"
text: '''Después de que ejecutes una maniobra roja, asigna 2 fichas de Concentración a tu nave.'''
'<NAME>':
name: "<NAME>"
ship: "Caza Estelar del Protectorado"
'<NAME>':
name: "<NAME>"
ship: "Caza Estelar del Protectorado"
'<NAME>':
name: "<NAME>"
ship: "Caza Estelar del Protectorado"
'<NAME>':
ship: "Nave de persecución clase Lancero"
text: '''Al comienzo de la fase de Combate, puedes elegir una nave que tengas a alcance 1. Si esa nave está dentro de tus arcos de fuego normal <strong>y</strong> móvil, asígnale 1 ficha de Campo de tracción.'''
'<NAME>':
ship: "Nave de persecución clase Lancero"
text: '''Al comienzo de la fase de Combate, puedes elegir una nave que tengas a alcance 1-2. Si esa nave está dentro de tu arco de fuego móvil, asígnale 1 ficha de Tensión.'''
'<NAME> (Scum)':
ship: "Nave de persecución clase Lancero"
text: '''Cuando te defiendas contra una nave enemiga que tengas dentro de tu arco de fuego móvil a alcance 1-2, puedes añadir 1 resultado %FOCUS% a tu tirada.'''
'<NAME>':
name: "Cazador de puerto clandest<NAME>"
ship: "Nave de persecución clase Lancero"
'<NAME> (TIE Fighter)':
ship: "Caza TIE"
text: '''Inmediatametne antes de revelar tu maniobra, puedes realizar una acción gratuita de impulso o tonel volado.'''
'"Zeb" Orrelios (TIE Fighter)':
ship: "Caza TIE"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
'<NAME>':
ship: "Lanzadera clase Ípsilon"
text: '''La primera vez que seas impactado por un ataque en cada ronda, asigna la carta de Estad "Yo te mostraré el Lado Oscuro" al atacante.'''
'<NAME>':
ship: "Saltador Quad"
text: '''Al final de la fase de Activación, <strong>debes</strong> asignar una ficha de Campo de tracción a toda nave con la que estés en contacto.'''
'<NAME>':
ship: "Ala-U"
text: '''Al comienzo de la fase de Activación, puedes quitar 1 ficha de Tensión de 1 otra nave aliada que tengas a alcance 1-2.'''
'<NAME>':
ship: "Ala-U"
text: '''Cuando una nave aliada fije un blanco, esa nave puede fijarlo sobre una nave enemiga que esté situada a alcance 1-3 de cualquier nave aliada.'''
'<NAME>':
ship: "Ala-U"
text: '''Después de que una nave enemiga ejecute una maniobra que la haga solaparse con tu nave, puedes realizar una acción gratuita.'''
'''"<NAME>"''':
ship: "Fustigador TIE"
name: '"<NAME>"'
text: '''Cuando tengas equipada la carta de Mejora "Alreones adaptativos", puedes elegir ignorar su capacidad de carta.'''
'''"Pure Sabacc"''':
ship: "Fustigador TIE"
name: '"<NAME>"'
text: '''Cuando ataques, si tienes 1 o menos cartas de Daño, tira 1 dado de ataque adicional.'''
'''"Countdown"''':
ship: "Fustigador TIE"
name: '"<NAME>"'
text: '''Cuando te defiendas, si no estás bajo tensión, durante el paso "Comparar los resultados", puedes sufrir 1 punto de daño para anular <strong>todos</strong> los resultados de los dados. Si lo haces, recibes 1 ficha de Tensión.'''
'<NAME>':
ship: "T-70 Ala-X"
text: '''Cuando recibas una ficha de Tensión, si hay alguna nave enemiga dentro de tu arco de fuego a alcance 1, puedes descartar esa ficha de Tensión.'''
'"Snap" <NAME>':
ship: "T-70 Ala-X"
text: '''Después de que ejecutes una maniobra de velocidad 2, 3 ó 4, si no estás en contacto con ninguna nave, puedes realizar una acción gratuita de impulso.'''
'<NAME>':
ship: "T-70 Ala-X"
text: '''Cuando ataques o te defiendas, puedes volver a tirar 1 de tus dados por cada otra nave aliada que tengas a Alcance 1.'''
'<NAME>':
ship: "Caza TIE"
text: '''Al comienzo de la fase de Combate, puedes gastar 1 ficha de Concentración para elegir una nave aliada que tengas a alcance 1. Esa nave puede realizar 1 acción gratuita.'''
'<NAME>':
ship: "Caza TIE"
name: "<NAME>"
text: '''Después de que efectúes un ataque, asigna la carta de Estado "Fuego de supresión" al defensor.'''
'Major Str<NAME>an':
ship: "Lanzadera clase Ípsilon"
name: "<NAME>"
text: '''A efectos de tus acciones y cartas de Mejora, puedes considerar las naves aliadas que tengas a alcance 2-3 como si estuvieran a alcance 1.'''
'<NAME>':
ship: "Lanzadera clase Ípsilon"
name: "<NAME>"
text: '''Durante la preparación de la partida, las naves aliadas pueden ser colocadas en cualquier lugar de la zona de juego que esté situado a alcance 1-2 de ti.'''
'<NAME>':
ship: "Saltador Quad"
name: "<NAME>"
text: '''Cuando reveles una maniobra de retroceso, puedes soltar una bomba usando los salientes de la parte frontal de tu peana (incluso una bomba con el encabezado "<strong>Acción:</strong>").'''
'<NAME>':
ship: "Saltador Quad"
text: '''Cuando te defiendas, en vez de usar tu valor de Agilidad, puedes tirar tantos dados de defensa como la velocidad de la maniobra que has ejecutado en esta ronda.'''
"Blue Squadron Pathfinder":
name: "Infiltrador del Escuadrón Azul"
ship: "Ala-U"
"Black Squadron Scout":
name: "Explorador del Escuadrón Negro"
ship: "Fustigador TIE"
"Scarif Defender":
name: "Defensor de Scarif"
ship: "Fustigador TIE"
"Imperial Trainee":
name: "Cadete Imperial"
ship: "Fustigador TIE"
"Starkiller Base Pilot":
ship: "Lanzadera clase Ípsilon"
name: "Piloto de la base Starkiller"
"<NAME>":
ship: "Saltador Quad"
name: "Traficante de armas de <NAME>"
'Genesis Red':
ship: "Interceptor M3-A"
text: '''Después de que fijes un blanco, asigna fichas de Concentración y fichas de Evasión a tu nave hasta que tengas tantas fichas de cada tipo como la nave que has fijado.'''
'<NAME>':
ship: "Interceptor M3-A"
text: '''Al comienzo de la fase de Combate, puedes recibir una ficha de Armas inutilizadas para poner boca arriba una de tus cartas de Mejora %TORPEDO% o %MISSILE% descartadas.'''
'<NAME>':
ship: "Interceptor M3-A"
text: '''Cuando ataques o te defiendas, puedes gastar 1 ficha de Escudos para volver a tirar cualquier cantidad de tus dados.'''
'Sun<NAME>':
ship: "Interceptor M3-A"
text: '''Una vez por ronda, después de que tires o vuelvas a tirar los dados, si has sacado el mismo resultado en cada uno de tus dados, puedes añadir 1 más de esos resultados a la tirada.'''
'C-ROC C<NAME>iser':
ship: "Crucero C-ROC"
name: "<NAME>-<NAME>"
'<NAME>':
ship: "TIE Agresor"
text: '''Cuando ataques, puedes gastar 1 ficha de Concentración para anular todos los resultados %FOCUS% y de cara vacía del defensor.'''
'"Double Edge"':
ship: "TIE Agresor"
name: "<NAME>"
text: '''Una vez por ronda, después de que efectúes un ataque con un armamento secundario que no impacte, puedes efectuar un ataque con un arma diferente.'''
'Onyx Squadron Escort':
ship: "TIE Agresor"
name: "<NAME>"
'Sienar Specialist':
ship: "TIE Agresor"
name: "Especialista de <NAME>"
'<NAME>':
ship: "Caza Kihraxz"
text: '''Después de que te defiendas, si la tirada que realizaste no consistió exactamente en 2 dados de defensa, el atacante recibe 1 ficha de Tensión.'''
'<NAME>':
ship: "Cañonera Auzituck"
text: '''Cuando otra nave aliada que tengas a alcance 1 se esté defendiendo, puedes gastar 1 ficha de Refuerzo. Si lo haces, el defensor añade 1 resultado %EVADE%.'''
'<NAME>':
ship: "Cañonera Auzituck"
text: '''Cuando ataques, si no tienes ninguna ficha de Escudos y tienes asignada como mínimo 1 carta de Daño, tira 1 dado de ataque adicional.'''
'<NAME>':
name: "<NAME>"
ship: "Cañonera Auzituck"
'Kashyyyk Defender':
name: "Defensor de <NAME>"
ship: "Cañonera Auzituck"
'Capt<NAME> (Scum)':
name: "<NAME> (Scum)"
ship: "Bombardero Scurrg H-6"
text: '''Puedes ignorar las bombas aliadas. Cuando una nave aliada se está defendiendo, si el atacante mide el alcance a través de una ficha de Bomba aliada, el defensor puede añadir 1 resultado%EVADE%.'''
'Captain Nym (Rebel)':
name: "<NAME> (Rebelde)"
ship: "Bombardero Scurrg H-6"
text: '''Una vez por ronda, puedes impedir que una bomba aliada detone.'''
'L<NAME>':
name: "<NAME>"
ship: "Bombardero Scurrg H-6"
'K<NAME>':
name: "<NAME>"
ship: "Bombardero Scurrg H-6"
'Sol <NAME>':
ship: "Bombardero Scurrg H-6"
text: '''Cuando sueltes una bomba, puedes utilizar la plantilla de maniobra (%TURNLEFT% 1) o (%TURNRIGHT% 1) en vez de la plantilla de (%STRAIGHT% 1).'''
'<NAME>':
ship: 'Víbora Estelar'
text: '''Si no estás bajo tensión, cuando reveles una maniobra de giro, inclinación o giro de Segnor, puedes ejecutarla como si fuera una maniobra roja de giro Tallon con la misma dirección (izquierda o derecha) utilizando la plantilla de maniobra revelada originalmente.'''
'Th<NAME>':
ship: 'Víbora Estelar'
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", puedes elegir 1 nave enemiga y asignarle la carta de Estado "Vigilado" o "Imitado".'''
'Black <NAME>':
name: "<NAME>"
ship: 'Víbora Estelar'
'<NAME>':
name: "<NAME>"
ship: "Caza Kihraxz"
text: '''Una vez por ronda, después de que una nave enemiga que no se está defendiendo contra un ataque sufra daño normal o daño crítico, puedes efectuar un ataque contra esa nave.'''
'<NAME>':
ship: "Ala Estelar clase Alfa"
name: "<NAME>"
text: '''Cuando te defiendas, si tienes asignada una ficha de Armas bloqueadas, tira 1 dado de defensa adicional.'''
'Nu Squadron Pilot':
name: "Piloto del Escuadrón Nu"
ship: "Ala Estelar clase Alfa"
'Rho Squadron Veteran':
name: "Veterano del Escuadrón Rho"
ship: "Ala Estelar clase Alfa"
'<NAME>':
ship: "Ala Estelar clase Alfa"
name: "<NAME>"
text: '''Cuando recibas una ficha de Armas bloqueadas, si no estás bajo tensión, puedes recibir 1 ficha de Tensión para retirar esa ficha de Armas bloqueadas.'''
'<NAME>':
name: "<NAME>"
ship: "Caza M12-L Kimogila"
'<NAME>':
name: "<NAME>"
ship: "Caza M12-L Kimogila"
'<NAME>':
ship: "Caza M12-L Kimogila"
text: '''Después de que efectúes un ataque, toda nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego centrado debe elegir entre sufrir 1 daño o retirar todas sus fichas de Concrentración y Evasión.'''
'<NAME> (Kimogila)':
ship: "Caza M12-L Kimogila"
text: '''Al comienzo de la fase de Combate, puedes fijar como blanco una nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego centrado.'''
'<NAME>au (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando una nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego pase a ser la nave activa durante la fase de Combate, si no estás bajo tensión, puedes recibir 1 ficha de Tensión. Si lo haces, esa nave no podrá gastar fichas para modificar sus dados cuando ataque en esta ronda.'''
'Ezra Bridger (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: """Cuando te defiendas, si estás bajo tensión, puedes cambiar hasta 2 de tus resultados %FOCUS% por resultados %EVADE%."""
'"Zeb" Orrelios (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
'AP-5':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando realices la acción de coordinación, después de que elijas a una nave aliada y antes de que esa nave realice su acción gratuita, puedes recibir 2 fichas de Tensión para quitarle 1 ficha de Tensión a esa nave.'''
'Crimson Squadron Pilot':
name: "<NAME>"
ship: "Bombardero B/SF-17"
'"Crimson Leader"':
name: '"<NAME>"'
ship: "Bombardero B/SF-17"
text: '''Cuando ataques, si el defensor está situado dentro de tu arco de fuego, puedes gastar 1 resultado %HIT% o %CRIT% para asignar el estado "Estremecido" al defensor.'''
'"Crimson Specialist"':
name: '"<NAME> <NAME> <NAME>"'
ship: "Bombardero B/SF-17"
text: '''Cuando coloques una ficha de Bomba que has soltado después de revelar tu selector de maniobras, puedes colocarla en cualquier lugar de la zona de juego donde quede en contacto con tu nave.'''
'"Cobalt Leader"':
name: '"<NAME>"'
ship: "Bombardero B/SF-17"
text: '''Cuando ataques, si el defensor está situado a alcance 1 de una ficha de Bomba, el defensor tira 1 dado de defensa menos (hasta un mínimo de 0).'''
'S<NAME>ar-Jaemus Analyst':
name: "<NAME>"
ship: "Silenciador TIE"
'First Order Test Pilot':
name: "Piloto de pruebas de la Primera Orden"
ship: "Silenciador TIE"
'<NAME> (TIE Silencer)':
name: "<NAME> (Silenciador TIE)"
ship: "Silenciador TIE"
text: '''La primera vez que seas impactado por un ataque en cada ronda, asigna la carta de Estado "Yo te mostraré el Lado Oscuro" al atacante.'''
'Test Pilot "Blackout"':
name: 'Piloto de pruebas "Apagón"'
ship: "Silenciador TIE"
text: '''Cuando ataques, si el ataque está obstruido, el defensor tira 2 dados de defensa menos (hasta un mínimo de 0).'''
'Partisan Renegade':
name: "Insurgente de los Partisanos"
ship: "Ala-U"
'Cavern Angels Zealot':
name: "Fanático de los Ángeles Cavernarios"
ship: "Ala-X"
'Kullbee Sperado':
ship: "Ala-X"
text: '''Después de que realices una acción de impulso o de tonel volado, puedes darle la vuelta a la carta de Mejora "Alas móviles" que tengas equipada en tu nave.'''
'Major Vermeil':
name: "<NAME>"
ship: "Segador TIE"
text: '''Cuando ataques, si el defensor no tiene asignada ninguna ficha de Concentración ni de Evasión, puedes cambiar 1 de tus resultados %FOCUS% o de cara vacía por un resultado %HIT%.'''
'"<NAME>"':
name: '"<NAME>"'
text: '''Después de que una nave aliada ejecute una maniobra con una velocidad de 1, si esa nave está situada a alcance 1 de ti y no se ha solapado con ninguna nave, puedes asignarle 1 de tus fichas de Concentración o Evasión.'''
ship: "Segador TIE"
'<NAME>':
name: '<NAME>'
ship: "Segador TIE"
text: '''Cuando te defiendas, si el atacante está interferido, añade 1 resultado %EVADE% a tu tirada.'''
'Scarif Base Pilot':
name: "<NAME>to de la base de Scarif"
ship: "Segador TIE"
'<NAME>':
ship: "Ala-X"
text: '''Después de que realices una acción de impulso, puedes recibir 1 ficha de Tensión para recibir 1 ficha de Evasión.'''
'<NAME>':
ship: "Ala-U"
text: '''Cuando una nave aliada que tengas a alcance 1-2 efectúe un ataque, si esa nave está bajo tensión o tiene asignada por lo menos 1 carta de Daño, puede volver a tirar 1 dado de ataque.'''
'Benthic Two-Tubes':
name: "<NAME>"
ship: "Ala-U"
text: '''Después de que realices una acción de concentración, puedes retirar 1 de tus fichas de Concentración para asignarla a una nave aliada que tengas a alcance 1-2.'''
'<NAME>':
ship: "Ala-U"
text: '''Cuando otra nave aliada que tengas a alcance 1-2 se defienda, el atacante no puede volver a tirar más de 1 dado de ataque.'''
'Edrio Two-Tubes':
name: "<NAME>"
ship: "Ala-X"
text: '''Cuando te conviertas en la nave activa durante la fase de Activación, si tienes asignadas 1 o más fichas de Concentración, puedes realizar una acción gratuita.'''
upgrade_translations =
"Ion Cannon Turret":
name: "Torreta de cañones de iones"
text: """<strong>Ataque:</strong> Ataca 1 nave (aunque esté fuera de tu arco de fuego).<br /><br />Si este ataque impacta, el defensor sufre 1 punto de daño y recibe 1 ficha de Iones. Después se anulan todos los resultados de los dados."""
"<NAME>":
name: "<NAME>"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
"R2 Astromech":
name: "Droide Astromecánico R2"
text: """Puedes ejecutar todas las maniobras de velocidad 1 y 2 como maniobras verdes."""
"R2-D2":
text: """Después de que ejecutes una maniobra verde, puedes recuperar 1 ficha de Escudos (pero no puedes tener más fichas que tu valor de Escudos)."""
"R2-F2":
text: """<strong>Acción:</strong> Tu valor de agilidad aumenta en 1 hasta el final de esta ronda de juego."""
"R5-D8":
text: """<strong>Acción:</strong> Tira 1 dado de defensa.<br /><br />Si sacas %EVADE% o %FOCUS%, descarta 1 carta de Daño que tengas boca abajo."""
"R5-K6":
text: """Después de gastar tu ficha de Blanco Fijado, tira 1 dado de defensa.<br /><br />Si sacas un resultado %EVADE% puedes volver a fijar la misma nave como blanco inmediatamente. No puedes gastar esta nueva ficha de Blanco Fijado durante este ataque."""
"R5 Astromech":
name: "Droide Astromecánico R5"
text: """Durante la fase Final, puedes elegir 1 de las cartas de Daño con el atributo <strong>Nave</strong> que tengas boca arriba, darle la vuelta y dejarla boca abajo."""
"Determination":
name: "Determinación"
text: """Cuando se te asigne una carta de Daño boca arriba que tenga el atributo <strong>Piloto</strong>, descártala inmediatamente sin resolver su efecto."""
"Swarm Tactics":
name: "Táctica de Enjambre"
text: """Al principio de la fase de Combate, elige 1 nave aliada que tengas a alcance 1.<br /><br />Hasta el final de esta fase, se considera que el valor de Habilidad de la nave elejida es igual que el tuyo."""
"Squad Leader":
name: "<NAME>"
text: """<strong>Acción:</strong> Elije una nave a alcance 1-2 cuyo pilioto tenga una Habilidad más baja que la tuya.<br /><br />La nave elegida puede llevar a cabo 1 acción gratuita de inmediato."""
"Expert Handling":
name: "<NAME>"
text: """<strong>Acción:</strong> Realiza una acción gratuita de tonel volado. Si no tienes el icono de acción %BARRELROLL%, recibes una ficha de Tensión.<br /><br />Después puedes descartar 1 ficha enemiga de Blanco Fijado que esté asignada a tu nave."""
"Marksmanship":
name: "<NAME>"
text: """<strong>Acción:</strong> Cuando ataques en esta ronda puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT% y tus demás resultados %FOCUS% por resultados %HIT%."""
"Concussion Missiles":
name: "Misiles de Impacto"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Puedes cambiar 1 resultado de cara vacía por un resultado %HIT%."""
"Cluster Missiles":
name: "Misiles de Racimo"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque <strong>dos veces</strong>."""
"D<NAME>":
name: "<NAME>"
text: """<strong>Acción:</strong> Ejecuta una maniobra blanca (%TURNLEFT% 1) o (%TURNRIGHT% 1) y luego recibe 1 ficha de Tensión.<br /><br />Después, si no tienes el ícono de acción %BOOST%, tira 2 dados de ataque y sufre todos los daños normales (%HIT%) y críticos (%CRIT%) obtenidos."""
"Elusiveness":
name: "<NAME>"
text: """Cuando te defiendas en combate, puedes recibir 1 ficha de Tensión para elegir 1 dado de ataque. El atacante deberá volver a lanzar ese dado.<br /><br />No puedes usar esta habilidad si ya tienes una ficha de Tensión."""
"Homing Missiles":
name: "<NAME>"
text: """<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque.<br /><br />El defensor no puede gastar fichas de evasión durante este ataque."""
"Push the Limit":
name: "<NAME>á<NAME>"
text: """Una vez por ronda, después de que realices una acción podras realizar a cabo 1 acción gratuita de entre las que figuren en tu barra de acciones.<br /><br />Después recibes 1 ficha de Tensión."""
"Deadeye":
name: "<NAME>"
text: """%SMALLSHIPONLY%%LINEBREAK%Puedes tratar la expresión <strong>"Ataque (blanco fijado)"</strong> como si dijera <strong>"Ataque (concentración)"</strong>.<br /><br />Cuando un ataque te obligue a gastar una ficha de Blanco Fijado, puedes gastar una ficha de Concentración en su lugar."""
"Expose":
name: "<NAME>"
text: """<strong>Acción:</strong> Hasta el final de la ronda, el valor de tu armamento principal se incrementa en 1 y tu Agilidad se reduce en 1."""
"Gunner":
name: "<NAME>"
text: """Después de que efectúes un ataque y lo falles, puedes realizar inmediatamente un ataque con tu armamento principal. No podrás realizar ningún otro ataque en esta misma ronda."""
"Ion Cannon":
name: "<NAME>"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Si este ataque impacta, el defensor sufre 1 de daño y recibe 1 ficha de Iones. Después se anulan <b>todos</b> los resultados de los dados."""
"Heavy Laser Cannon":
name: "<NAME>"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Inmediatamente después de lanzar los dados de ataque, debes cambiar todos tus resultados %CRIT% por resultados %HIT%."""
"Seismic Charges":
name: "Cargas Sísmicas"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Carga Sísmica.<br /><br />Esta ficha se <strong>detona</strong> al final de la fase de Activación."""
"Mercenary Copilot":
name: "Copilo<NAME> M<NAME>"
text: """Cuando ataques a alcance 3, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%."""
"Assault Missiles":
name: "<NAME>"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta al objetivo, toda otra nave que haya a alcance 1 del defensor sufre 1 daño."""
"Veteran Instincts":
name: "Instinto de Veterano"
text: """La Habilidad de tu piloto se incrementa en 2."""
"Proximity Mines":
name: "Minas de Proximidad"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Mina de Proximidad.<br /><br />Cuando la peana o la plantilla de maniobra de una nave se solape con esta ficha, ésta se <strong>detona</strong>.<br /><br /><strong>Ficha de Mina de proximidad:</strong> Cuando se detona una de estas fichas de Bomba, la nave que la haya atravesado o solapado tira 3 dados de ataque y sufre todo el daño (%HIT%) y daño crítico (%CRIT%) obtenido en la tirada. Después se descarta esta ficha."""
"Weapons Engineer":
name: "Ingeniero de Armamento"
text: """Puedes tener 2 Blancos Fijados a la vez (pero sólo 1 para cada nave enemiga).<br /><br />Cuando fijes un blanco, puedes fijar como blanco a dos naves distintas."""
"Draw Their Fire":
name: "Atraer su fuego"
text: """Cuando una nave aliada que tengas a alcance 1 sea alcanzada por un ataque, puedes sufrir tú 1 de sus resultados %CRIT% no anulados en vez de la nave objetivo."""
"Luke Skywalker":
text: """Después de que efectúes un ataque y lo falles, puedes realizar inmediatamente un ataque con tu armamento principal. Puedes cambiar 1 resultado %FOCUS% por 1 resultado %HIT%. No podrás realizar ningún otro ataque en esta misma ronda."""
"<NAME>":
text: """Todas las maniobras %STRAIGHT% se consideran verdes para ti."""
"Chewbacca":
text: """Cuando recibas una carta de Daño, puedes descartarla de inmediato y recuperar 1 de Escudos.<br /><br />Luego descarta esta carta de Mejora."""
"Advanced Proton Torpedoes":
name: "Torpedos de protones avanzados"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque. Puedes cambiar hasta 3 resultados de caras vacías por resultados %FOCUS%."""
"Autoblaster":
name: "Cañón Blaster Automático"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Tus resultados %HIT% no pueden ser anulados por los dados de defensa.<br /><br />El defensor puede anular tus resultados %CRIT% antes que los %HIT%."""
"Fire-Control System":
name: "Sistema de Control de Disparo"
text: """Después de que efectúes un ataque, puedes fijar al defensor como blanco."""
"Blaster Turret":
name: "Torreta Bláster"
text: """<strong>Ataque (Concentración):</strong> Gasta 1 ficha de Concentración para efectuar este ataque contra una nave (aunque esté fuera de tu arco de fuego)."""
"Recon Specialist":
name: "Especialista en Reconocimiento"
text: """Cuando realices una acción de Concentración, asigna 1 ficha de Concentración adicional a tu nave."""
"Saboteur":
name: "<NAME>"
text: """<strong>Acción:</strong> Elige 1 nave enemiga que tengas a alcance 1 y tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, elige al azar 1 carta de Daño que esa nave tenga asignada boca abajo, dale la vuelta y resuélvela."""
"Intelligence Agent":
name: "Agente del Servicio de Inteligencia"
text: """Al comienzo de la fase de Activación, elige 1 nave enemiga que tengas a alcance 1-2. Puedes mirar el selector de maniobras de esa nave."""
"Proton Bombs":
name: "<NAME>"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Bombas de Protones.<br /><br />Esta ficha se <strong>detona</strong> al final de la fase de Activación."""
"<NAME>":
name: "<NAME>"
text: """Cuando reveles una maniobra roja, puedes descartar esta carta para tratarla como si fuera una maniobra blanca hasta el final de la fase de Activación."""
"Advanced Sensors":
name: "Sensores Avanzados"
text: """Inmediatamente antes de que reveles tu maniobra, puedes realizar 1 acción gratuita.<br /><br />Si utilizas esta capacidad, debes omitir tu paso de "Realizar una acción" durante esta ronda."""
"Sensor Jammer":
name: "Emisor de Interferencias"
text: """Cuando te defiendas, puedes cambiar 1 de los resultados %HIT% por uno %FOCUS%.<br /><br />El atacante no puede volver a lanzar el dado cuyo resultado hayas cambiado."""
"<NAME>":
text: """Después de que ataques a una nave enemiga, puedes sufrir 2 de daño para que esa nave reciba 1 de daño crítico."""
"Rebel Captive":
name: "<NAME>"
text: """Una vez por ronda, la primera nave que te declare como objetivo de un ataque recibe inmediatamente 1 ficha de Tensión."""
"Flight Instructor":
name: "<NAME>"
text: """Cuando te defiendas, puedes volver a tirar 1 dado en el que hayas sacado %FOCUS%. Si la Habilidad del piloto atacante es de 2 o menos, puedes volver a tirar 1 dado en el que hayas sacado una cara vacía."""
"Navigator":
name: "Oficial de Navegación"
text: """Cuando reveles una maniobra, puedes rotar el selector para escoger otra maniobra que tenga la misma dirección.<br /><br />Si tienes alguna ficha de Tensión, no puedes rotar el selector para escoger una maniobra roja."""
"Opportunist":
name: "Oportunista"
text: """Cuando ataques, si el defensor no tiene fichas de Concentración o de Evasión, puedes recibir 1 ficha de Tensión para tirar 1 dado de ataque adicional.<br /><br />No puedes utilizar esta capacidad si tienes fichas de Tensión."""
"Comms Booster":
name: "Amplificador de Comunicaciones"
text: """<strong>Energía:</strong> Gasta 1 de Energía para descartar todas las fichas de Tensión de una nave aliada que tengas a alcance at Range 1-3. Luego asigna 1 ficha de Concentración a esa nave."""
"Slicer Tools":
name: "Sistemas de Guerra Electrónica"
text: """<strong>Acción:</strong> Elige 1 o mas naves enemigas situadas a alcance 1-3 y que tengan fichas de Tensión. Por cada nave elegida, puedes gastar 1 de Energía para que esa nave sufra 1 daño."""
"Shield Projector":
name: "Proyector de Escudos"
text: """Cuando una nave enemiga pase a ser la nave activa durante la fase de Combate, puedes gastar 3 de Energía para obligar a esa nave a atacarte (si puede) hasta el final de la fase."""
"Ion Pulse Missiles":
name: "Misiles de Pulso Iónico"
text: """<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta, el defensor sufre 1 daño y recibe 2 fichas de Iones. Después se anulan <strong>todos</strong> los resultados de los dados."""
"<NAME>":
name: "<NAME>"
text: """Al comienzo de la fase de Combate, quita 1 ficha de tensión de otra nave aliada que tengas a alcance 1."""
"<NAME>":
name: "<NAME>"
text: """Al comienzo de la fase de Combate, puedes elegir 1 nave aliada que tengas a alcance 1-2. Intercambia tu Habilidad de piloto por la Habilidad de piloto de esa nave hasta el final de la fase."""
"<NAME>":
name: "<NAME>"
text: """Cuando ataques a una nave situada dentro de tu arco de fuego, si tú no estás dentro del arco de fuego de esa nave, su Agilidad se reduce en 1 (hasta un mínimo de 0)."""
"<NAME>":
name: "<NAME>"
text: """Cuando ataques, puedes volver a tirar 1 dado de ataque. Si la Habilidad del piloto defensor es 2 o menor, en vez de eso puedes volver a tirar hasta 2 dados de ataque."""
"<NAME>":
name: "<NAME>"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Después de que realices este ataque, el defensor recibe 1 ficha de Tensión si su Casco es de 4 o inferior."""
"R<NAME>":
name: "<NAME>"
text: """Una vez por ronda cuando te defiendas, si tienes al atacante fijado como blanco, puedes gastar esa ficha de Blanco Fijado para elegir algunos o todos sus dados de ataque. El atacante debe volver a tirar los dados que hayas elegido."""
"R7-T1":
name: "R7-T1"
text: """<strong>Acción:</strong> Elije 1 nave enemiga a alcance 1-2. Si te encuentras dentro de su arco de fuego, puedes fijarla como blanco. Después puedes realizar una acción gratuita de impulso."""
"Tactician":
name: "Estratega"
text: """%LIMITED%%LINEBREAK%Después de que efectúes un ataque contra una nave que esté situada dentro de tu arco de fuego a alcance 2, esa nave recibe 1 ficha de Tensión."""
"R2-D2 (Crew)":
name: "R2-D2 (Tripulante)"
text: """Al final de la fase Final, si no tienes Escudos, puedes recuperar 1 de Escudos y tirar 1 dado de ataque. Si sacas %HIT%, pon boca arriba 1 de las cartas de Daño que tengas boca abajo (elegida al azar) y resuélvela."""
"C-3PO":
name: "C-3PO"
text: """Una vez por ronda, antes de que tires 1 o mas dados de defensa, puedes decir en voz alta cuántos resultados %EVADE% crees que vas a sacar. Si aciertas (antes de modificar los dados), añade 1 %EVADE% al resultado."""
"Single Turbolasers":
name: "Batería de Turboláseres"
text: """<strong>Ataque (Energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque. La Agilidad del defensor se duplica contra este ataque. Puedes cambiar 1 de tus resultados de %FOCUS% por 1 resultado de %HIT%."""
"Quad Laser Cannons":
name: "<NAME>"
text: """<strong>Ataque (Energía):</strong> Gasta 1 de Energía de esta carta para efectuar este ataque. Si no impacta, puedes gastar inmediatamente 1 de Energía de esta carta para repetir el ataque."""
"Tibanna Gas Supplies":
name: "<NAME>"
text: """<strong>Energía:</strong> Puedes descartar esta carta para obtener 3 de Energía."""
"Ionization Reactor":
name: "Reactor de Ionización"
text: """<strong>Energía:</strong> Gasta 5 de Energía de esta carta y descártala para para que todas las demás naves situadas a alcance 1 sufran 1 de daño y reciban 1 ficha de Iones."""
"Engine Booster":
name: "Motor Sobrepotenciado"
text: """Immediatamente antes de revelar tu selector de maniobras, puedes gastar 1 de Energía para ejecutar 1 maniobra blanca de (%STRAIGHT% 1). No puedes usar esta capacidad si al hacerlo te solapas con otra nave."""
"R3-A2":
name: "R3-A2"
text: """Cuando declares al objetivo de tu ataque, si el defensor está dentro de tu arco de fuego, puedes recibir 1 ficha de Tensión para hacer que el defensor reciba 1 ficha de Tensión."""
"R2-D6":
name: "R2-D6"
text: """Tu barra de mejoras gana el icono de mejora %ELITE%.<br /><br />No puedes equiparte esta mejora si ya tienes un icono de mejora %ELITE% o si la Habilidad de de tu piloto es de 2 o menos."""
"Enhanced Scopes":
name: "Radar Mejorado"
text: """La Habilidad de tu piloto se considera 0 durante la fase de Activación."""
"Ch<NAME> Re<NAME>":
name: "Re<NAME>ado en Ch<NAME>"
ship: "Ala-A"
text: """<span class="card-restriction">Solo Ala-A.</span><br /><br />Esta carta tiene un coste negativo en puntos de escuadrón."""
"Proton Rockets":
name: "<NAME>"
text: """<strong>Ataque (Concentración):</strong> Descarta esta carta para efectuar este ataque.<br /><br />Puedes tirar tantos dados de ataque adicionales como tu puntuación de Agilidad, hasta un máximo de 3 dados adicionales."""
"<NAME>":
text: """Despues de que quites una ficha de Tensión de tu nave, puedes asiganar una ficha de Concentración a tu nave."""
"<NAME>":
text: """Una vez por ronda, cuando una nave aliada que tengas a alcance 1-3 realice una accion de Concentración o vaya a recibir una ficha de Concentración, en vez de eso puedes asignarle a esa nave una ficha de Evasión."""
"<NAME>":
text: """<strong>Acción:</strong> Gasta cualquier cantidad de Energía para elegir ese mismo número de naves enemigas que tengas a alcance 1-2. Descarta todas las fichas de Concentración, Evasión y Blanco Fijado (azules) de las naves elegidas."""
# TODO Check card formatting
"R4-D6":
name: "R4-D6"
text: """Cuando seas alcanzado por un ataque y haya al menos 3 resultados %HIT% sin anular, puedes anular todos los que quieras hasta que solo queden 2. Recibes 1 ficha de Tensión por cada resultado que anules de este modo."""
"R5-P9":
name: "R5-P9"
text: """Al final de la fase de Combate, puedes gastar 1 de tus fichas de Concentración para recuperar 1 ficha de Escudos (hasta un máximo igual a tu puntuación de Escudos)."""
"WED-15 Repair Droid":
name: "Droide de Reparaciones WED-15"
text: """<strong>Acción:</strong> Gasta 1 de Energia para descartar 1 carta de Daño que tengas boca abajo, o bien gasta 3 de Energía para descartar 1 carta de Daño que tengas boca arriba."""
"<NAME>":
name: "<NAME>"
text: """Al pincipio de la fase de Activación, puedes descartar esta carta para que la Habilidad de todas tus naves se considere 12 hasta el final de la fase."""
"<NAME>":
name: "<NAME>"
text: """Cuando otra nave aliada que tengas a alcance 1 efectúe un ataque, podrá cambiar 1 de sus resultados de %HIT% por 1 resultado de %CRIT%."""
"Expanded Cargo Hold":
name: "Bodega de Carga Ampliada"
text: """<span class="card-restriction">Solo GR-75</span><br /><br />Una vez por ronda, cuando tengas que recibir una carta de Daño boca arriba, puedes robar esa carta del mazo de Daño de proa o del mazo de Daño de popa."""
ship: 'Transporte mediano GR-75'
"Backup Shield Generator":
name: "Generador de Escudos Auxiliar"
text: """Al final de cada ronda, puedes gastar 1 de Energía para recuperar 1 de Escudos (hasta el maximo igual a tu puntuación de Escudos)."""
"EM Emitter":
name: "Emisor de señal Electromagnética"
text: """Cuando obstruyas un ataque, el defensor tira 3 dados de defensa adicionales en vez de 1."""
"Frequency Jammer":
name: "Inhibidor de Frecuencias"
text: """Cuando lleves a cabo una acción de intereferencia, elige 1 nave enemiga que no tenga fichas de Tensión y se encuentre a alcance 1 de la nave interferida. La nave elegida recibe una ficha de Tension."""
"<NAME>":
name: "<NAME>"
text: """Cuando ataques, si tienes la defensor fijado como blanco, puedes gastar esa ficha de Blanco Fijado para cambiar todos tus resultados de %FOCUS% por resultados de %HIT%."""
"<NAME>":
name: "<NAME>"
text: """Al comienzo de la fase de Activación, puedes descartar esta carta para que todas las naves aliadas que muestren una maniobra roja seleccionada la traten como si fuera una maniobra blanca hasta el final de la fase."""
"<NAME>":
name: "<NAME>"
text: """Al comiuenzo de la fase de Activación, elige 1 nave enemiga que tengas a alcance 1-3. Puedes mirar su selector de maniobras. Si ha seleccionado una maniobra blanca, adjudica 1 ficha de Tensión a esa nave."""
"Gunnery Team":
name: "<NAME>"
text: """Una vez por ronda, cuando ataques con un armamento secudario, puedes gastar 1 de Energía para cambiar 1 cara de dado vacía por 1 resultado de %HIT%."""
"Sensor Team":
name: "Equipo de Control de Sensores"
text: """Cuando fijes un blanco, puedes fijar como blanco una nave enemiga a alcance 1-5 (en lugar de 1-3)."""
"Engineering Team":
name: "Equipo de Ingeniería"
text: """Durante la fase de Activación, si enseñas una maniobra %STRAIGHT%, recibes 1 de Energía adicional durante el paso de "Obtener Energía"."""
"<NAME>":
name: "<NAME>"
text: """<strong>Acción:</strong> Tira 2 dados de defensa. Por cada %FOCUS% que saques, asigna 1 ficha de Concentración a tu nave. Por cada resultado de %EVADE% que saques, asigna 1 ficha de Evasión a tu nave."""
"<NAME>":
name: "<NAME>"
text: """Al final de la fase de Combate, toda nave enemiga situada a alcance 1 que no tenga 1 ficha de Tensión recibe 1 ficha de Tensión."""
"Fleet Officer":
name: "<NAME>"
text: """<strong>Acción:</strong> Elige un máximo de 2 naves aliadas que tengas a alcance 1-2 y asigna 1 ficha de Concentración a cada una de ellas. Luego recibes 1 ficha de Tensión."""
"L<NAME> Wolf":
name: "<NAME>"
text: """Cuando ataques o defiendas, si no tienes ninguna otra nave aliada a alcance 1-2, pues volver a tirar 1 dado en el que hayas sacado una cara vacía."""
"Stay On Target":
name: "Seguir al Objetivo"
text: """Cuando reveles una maniobra, puedes girar tu selector para escoger otra maniobra que tenga la misma velocidad.<br /><br />Tu maniobra se considera roja."""
"Dash Rendar":
text: """Puedes efectuar ataques mientras estés solapado con un obstáculo.<br /><br />Tus ataques no pueden ser obstruidos."""
'"Leebo"':
text: """<strong>Acción:</strong> Realiza una acción gratuita de Impulso. Después recibes 1 marcador de Iones."""
"Ruthlessness":
name: "<NAME>"
text: """Después de que efectúes un ataque que impacte, <strong>debes</strong> elegir otra nave situada a alcance 1 del defensor (exceptuando la tuya). Esa nave sufre 1 daño."""
"Int<NAME>ation":
name: "<NAME>"
text: """Mientras estes en contacto con una nave enemiga, la Agilidad de esa nave se reduce en 1."""
"<NAME>":
text: """Al comienzo de la fase de Combate, si no te quedan Escudos y tu nave tiene asignada al menos 1 carta de Daño, puedes realizar una acción gratuita de Evasión."""
"<NAME>":
text: """Cuando recibas una carta de Daño boca arriba, puedes descartar esta carta de Mejora u otra carta de %CREW% para poner boca abajo esa carta de Daño sin resolver su efecto."""
"Ion Torpedoes":
name: "<NAME>"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta, el defensor y toda nave que esté a alcance 1 reciben 1 ficha de Iones cada una."""
"Bomb Loadout":
name: "Compartimento de Bombas"
text: """<span class="card-restriction">Solo ala-Y.</span><br /><br />Tu barra de mejoras gana el icono %BOMB%."""
ship: "Ala-Y"
"Bodyguard":
name: "<NAME>"
text: """%SCUMONLY%<br /><br />Al principio de la fase de Combate, puedes gastar 1 ficha de Concentración para elegir 1 nave aliada situada a alcance 1 cuyo piloto tenga una Habilidad más alta que la tuya. Hasta el final de la ronda, la puntuación de Agilidad de esa nave se incrementa en 1."""
"Calculation":
name: "Planificación"
text: """Cuando ataques, puedes gastar 1 ficha de Concentración para cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
"Accuracy Corrector":
name: "<NAME>"
text: """Cuando ataques, durante el paso "Modificar la tirada de ataque", puedes anular los resultados de todos tus dados. Después puedes añadir 2 resultados %HIT% a tu tirada.<br /><br />Si decides hacerlo, no podrás volver a modificar tus dados durante este ataque."""
"Inertial Dampeners":
name: "<NAME>"
text: """Cuando reveles tu maniobra, puedes descartar esta carta para ejecutar en su lugar una maniobra blanca [0%STOP%]. Después recibes 1 ficha de Tensión."""
"<NAME>":
name: "<NAME>"
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, el defensor sufre 1 de daño y, si no tiene asignada ninguna ficha de Tensión, recibe también 1 ficha de Tensión. Después se anulan <strong>todos</strong> los resultados de los dados."""
'"<NAME>" <NAME>':
name: 'Ca<NAME> "<NAME>"'
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Durante este ataque, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%."""
"Dead Man's Switch":
name: "Dispositivo de Represalia"
text: """Cuando seas destruido, toda nave que tengas a alcance 1 sufre 1 daño."""
"Feedback Array":
name: "Transmisor de Sobrecargas"
text: """Durante la fase de Combate, en vez de efectuar ataques, puedes recibir 1 ficha de Iones y sufrir 1 daño para elegir 1 nave enemiga a alcance 1. Esa nave sufre 1 daño."""
'"Hot Shot" Blaster':
name: "<NAME>"
text: """<strong>Ataque:</strong> Descarta esta carta para atacar a 1 nave (aunque esté fuera de tu arco de fuego)."""
"Greedo":
text: """%SCUMONLY%<br /><br />La primera vez que ataques cada ronda y la primera vez que te defiendas cada ronda, la primera carta de Daño inflingida será asignada boca arriba."""
"Outlaw Tech":
name: "<NAME>"
text: """%SCUMONLY%<br /><br />Después de que ejecutes una maniobra roja, puedes asignar 1 ficha de Concentración a tu nave."""
"K4 Security Droid":
name: "Droide de Seguridad K4"
text: """%SCUMONLY%<br /><br />Después de que ejecutes una maniobra verde, puedes fijar un blanco."""
"Salvaged Astromech":
name: "Droide Astromecánico Remendado"
text: """Cuando recibas una carta de Daño boca arriba con el atributo <strong>Nave</strong>, puedes descartarla de inmediato (antes de resolver sus efectos).<br /><br />Luego descarta esta carta de Mejora."""
'"Gen<NAME>"':
name: '"<NAME>"'
text: """Si estás equipado con una bomba que puede soltarse cuando revelas tu selector de maniobras, puedes elegir soltar la bomba <strong>después</strong> de ejecutar tu maniobra."""
"Unhinged Astromech":
name: "Droide Astromecánico Desquiciado"
text: """Puedes ejecutar todas las maniobras de velocidad 3 como maniobras verdes."""
"R4 Agromech":
name: "Droide Agromecánico R4"
text: """Cuando ataques, después de gastar una ficha de Concentración puedes fijar al defensor como blanco."""
"R4-B11":
text: """Cuando ataques, si tienes al defensor fijado como blanco, puedes gastar la ficha de Blanco Fijado para elegir cualquier o todos sus dados de defensa. El defensor debe volver a tirar los dados elegidos."""
"Autoblaster Turret":
name: "Torreta de Bláster Automático"
text: """<strong>Ataque:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).<br /><br />Tus resultados %HIT% no pueden ser anulados por los dados de defensa.<br /><br />El defensor puede anular tus resultados %CRIT% antes que los %HIT%."""
"Advanced Targeting Computer":
ship: "TIE Avanzado"
name: "Computadora de Selección de Blancos Avanzada"
text: """<span class="card-restriction">Solo TIE Avanzado.</span>%LINEBREAK%Cuando ataques con tu armamento principal, si tienes al defensor fijado como blanco, puedes añadir 1 %CRIT% al resultado de tu tirada. Si decides hacerlo, no podrás gastar fichas de Blanco Fijado durante este ataque."""
"Ion Cannon Battery":
name: "<NAME>"
text: """<strong>Ataque (Energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque. Si este ataque impacta, el defensor sufre 1 de daño crítico y recibe 1 ficha de Iones. Después se anulan <strong>todos<strong> los resultados de los dados."""
"<NAME>":
name: "<NAME>"
text: """%IMPERIALONLY%%LINEBREAK%Una vez por ronda, antes de que una nave aliada vaya a tirar dados, puedes decir un resultado de dado. Tras tirarlos, se debe cambiar 1 de los resultados obtenidos por el resultado elegido antes. El resultado de ese dado no podrá volver a ser modificado."""
"Boss<NAME>":
text: """%SCUMONLY%%LINEBREAK%Después de que realices un ataque y falles, si no tienes fichas de Tensión <strong>debes</strong> recibir 1 ficha de Tensión. Después asigna 1 ficha de Concentración a tu nave y fija al defensor como blanco."""
"<NAME>":
name: "<NAME>"
text: """%SMALLSHIPONLY%%LINEBREAK%Después de que ejecutes una maniobra blanca o verde en tu selector, puedes descartar esta carta para rotar tu nave 180º. Luego recibes 1 ficha de Tensión <strong>después</strong> del paso de "comprobar Tensión del piloto."""
"Twin Laser Turret":
name: "<NAME>"
text: """<strong>Ataque:</strong> Efectúa este ataque <strong>dos veces</strong> (incluso contra una nave situada fuera de tu arco de fuego).<br /><br />Cada vez que este ataque impacte, el defensor sufre 1 de daño. Luego se anulan <strong>todos</strong> los resultados de los dados."""
"Plasma Torpedoes":
name: "<NAME> de Pl<NAME>"
text: """<strong>Ataque (Blanco fijado):</strong> Gasta tu ficha de Blanco fijado y descarta esta carta para efectuar este ataque.<br /><br />Si el ataque impacta, después de inflingir daños quita 1 ficha de Escudos del defensor."""
"Ion Bombs":
name: "<NAME>"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Bomba de iones.<br /><br />Esta ficha <strong>detona</strong> al final de la fase de Activación.<br /><br /><strong>Ficha de Bomba de iones:</strong> Cuando se detona esta ficha de Bomba, toda nave que se encuentre a alcance 1 de ella recibe 2 fichas de Iones. Después se descarta esta ficha."""
"Conner Net":
name: "<NAME>"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Red Conner.<br /><br />Esta ficha se <strong>detona</strong> cuando la peana o plantilla de maniobra de una nave se solape con ella.<br /><br /><strong>Ficha de Red Conner:</strong> Cuando es detona esta ficha de Bomba, la nave que la haya atravesado o solapado sufre 1 daño, recibe 2 fichas de Iones y se salta su paso de "Realizar una acción". Después se descarta esta ficha."""
"<NAME>":
name: "<NAME>"
text: """Cuando sueltes una bomba, puedes usar la plantilla (%STRAIGHT% 2) en lugar de la plantilla (%STRAIGHT% 1)."""
"Cluster Mines":
name: "<NAME>"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 conjunto de Minas de racimo.<br /><br />Cada ficha de Mina de racimo se <strong>detona</strong> cuando la peana o plantilla de maniobra de una nave se solapa con ella.<br /><br /><strong>Ficha de Mina de racimo:</strong> Cuando se detona una de estas fichas de Bomba, la nave que la haya atravesado o solapado tira 2 dados de ataque y sufre 1 punto de daño por cada %HIT% o %CRIT% obtenido en la tirada. Después se descarta esta ficha."""
'<NAME>ack Shot':
name: "<NAME>"
text: '''Cuando ataques a una nave situada dentro de tu arco de fuego, al comienzo del paso "Comparar los resultados", puedes descartar esta carta para anular 1 resultado %EVADE% del defensor.'''
"Advanced Homing Missiles":
name: "<NAME>"
text: """<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efectuar este ataque.%LINEBREAK%Si el ataque impacta, inflinge 1 carta de Daño boca arriba al defensor. Luego se anulan <strong>todos</strong> los resultados de los dados."""
'Agent K<NAME>':
name: "<NAME>"
text: '''%IMPERIALONLY%%LINEBREAK%Al comienzo de la primera ronda, elige 1 nave enemiga pequeña o grande. Cuando ataques a esa nave o te defiendas de esa nave, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%.'''
'XX-23 S-Thread Tracers':
name: "Hiperrastreadores XX-23"
text: """<strong>Ataque (Concentración):</strong> Descarta esta carta para efectuar este ataque. Si este ataque impacta, toda nave aliada que tengas a alcance 1-2 puede fijar al defensor como blanco. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Tractor Beam":
name: "Proyector de Campo de Tracción"
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, el defensor recibe 1 ficha de Campo de Tracción. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Cloaking Device":
name: "Dispositivo de Camuflaje"
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Acción:</strong> Realiza una acción gratuita de camuflaje.%LINEBREAK%Al final de cada ronda, si estás camuflado, tira 1 dado de ataque. Si sacas %FOCUS%, descarta esta carta y luego elige entre desactivar el camuflaje o retirar tu ficha de Camuflaje."""
"Shield Technician":
name: "Técnico de Escudos"
text: """%HUGESHIPONLY%%LINEBREAK%Cuando lleves a cabo una acción de recuperación, en vez de retirar todas tus fichas de Energía, puedes elegir qué cantidad de fichas de Energía deseas retirar."""
"Grand Moff Tarkin":
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Al comienzo de la fase de Combate, puedes elegir otra nave que tengas a alcance 1-4. Escoge entre retirar 1 ficha de Concentración de la nave elegida o asignarle 1 ficha de Concentración a esa nave."""
"<NAME>":
name: "<NAME>"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Si durante la fase de Activación te solapas con un obstáculo, en vez de recibir 1 carta de Daño boca arriba, tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, sufres 1 de daño."""
"<NAME>":
name: "<NAME>"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%<strong>ENERGÍA</strong>: Puedes descartar hasta 3 fichas de Escudos de tu nave. Por cada ficha de Escudos descartada, obtienes 1 de Energía."""
'<NAME>':
name: "<NAME>"
text: """Al comienzo de la fase de Combate, puedes descartar esta carta y recibir 1 ficha de Tensión. Si lo haces, hasta el final de la ronda, cuando ataques o defiendes puedes cambiar todos tus resultados %FOCUS% por resultados %HIT% o %EVADE%."""
'Extra Munitions':
name: "Munic<NAME> A<NAME>"
text: """Cuando te equipas con esta carta, coloca 1 ficha de Munición de artillería sobre cada carta de Mejora %TORPEDO%, %MISSILE% y %BOMB% que tengas equipada. Cuando se te indique que descartes una carta de Mejora, en vez de eso puedes descartar 1 ficha de Munición de artillería que haya encima de esa carta."""
"Weapons Guidance":
name: "Sistema de Guiado de Armas"
text: """Cuando ataques, puedes gastar una ficha de Concentración para cambiar 1 de tus resultados de cara vacia por un resultado %HIT%."""
"BB-8":
text: """Cuando reveles una maniobra verde, puedes realizar una acción gratuita de tonel volado."""
"R5-X3":
text: """Antes de revelar tu maniobra, puedes descartar esta carta para ignorar todos los obstáculos hasta el final de la ronda."""
"Wired":
name: "<NAME>"
text: """Cuando ataques o te defiendas, si estás bajo tensión, puedes volver a tirar 1 o más de tus resultados %FOCUS%."""
'Cool Hand':
name: "<NAME>"
text: '''Cuando recibas una ficha de Tensión, puedes descartar esta carta para asignar 1 ficha de Concetración o de Evasión a tu nave.'''
'Juke':
name: "<NAME>"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando ataques, si tienes una ficha de Evasión, puedes cambiar 1 de los resultados %EVADE% del defensor por un resultado %FOCUS%.'''
'Comm Relay':
name: "Repetidor de Comunicaciones"
text: '''No puedes tener más de 1 ficha de Evasión.%LINEBREAK%Durante la fase Final, no retires de tu nave las fichas de Evasión que no hayas usado.'''
'Dual Laser Turret':
text: '''%GOZANTIONLY%%LINEBREAK%<strong>Attack (energy):</strong> Spend 1 energy from this card to perform this attack against 1 ship (even a ship outside your firing arc).'''
'Broadcast Array':
text: '''%GOZANTIONLY%%LINEBREAK%Your action bar gains the %JAM% action icon.'''
'Rear Admiral Ch<NAME>aneau':
text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Execute a white (%STRAIGHT% 1) maneuver.'''
'Ordnance Experts':
text: '''Once per round, when a friendly ship at Range 1-3 performs an attack with a %TORPEDO% or %MISSILE% secondary weapon, it may change 1 of its blank results to a %HIT% result.'''
'Docking Clamps':
text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%You may attach 4 up to TIE fighters, TIE interceptors, TIE bombers, or TIE Advanced to this ship. All attached ships must have the same ship type.'''
'"Zeb" Orrelios':
text: """%REBELONLY%%LINEBREAK%Las naves enemigas dentro de tu arco de fuego que estén en contacto contigo no se consideran en contacto contigo cuando tú o ellas os activéis durante la fase de Combate."""
'<NAME>':
text: """%REBELONLY%%LINEBREAK%Una vez por ronda, después de que una nave aliada que tengas a alcance 1-2 ejecute una maniobra blanca, puedes quitar 1 ficha de Tensión de esa nave."""
'Reinforced Deflectors':
name: "Deflectores Reforzados"
text: """%LARGESHIPONLY%%LINEBREAK%Tras defenderte, su durante el ataque has sufrido una combinación de 3 o más puntos de daño normal y crítico, recuperas 1 ficha de Escudos (hast aun máximo igual a tu valor de Escudos)."""
'Dorsal Turret':
name: "<NAME>"
text: """<strong>Ataque:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).%LINEBREAK%Si el objetivo de este ataque está a alcance 1, tiras 1 dado de ataque adicional."""
'Targeting Astromech':
name: "Droide Astromecánico de Selección de Blancos"
text: '''Después de que ejecutes una maniobra roja, puedes fijar un blanco.'''
'Hera Syndull<NAME>':
text: """%REBELONLY%%LINEBREAK%Puedes revelar y ejectuar maniobras rojas incluso aunque estés bajo tensión."""
'<NAME>':
text: """%REBELONLY%%LINEBREAK%Cuando ataques, si estás bajo tensión puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
'<NAME>':
text: """%REBELONLY%%LINEBREAK%Tu barra de mejoras gana el icono %BOMB%. Una vez por ronda, antes de retirar una ficha de Bomba aliada, elige 1 nave enemiga situada a Alcance 1 de esa ficha. Esa nave sufre 1 de daño."""
'"Ch<NAME>"':
text: """%REBELONLY%%LINEBREAK%Puedes realizar acciones incluso aunque estés bajo tensión.%LINEBREAK%Después de que realices una acción mientras estás bajo tensión, sufres 1 de daño."""
'Construction Droid':
text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%When you perform a recover action, you may spend 1 energy to discard 1 facedown Damage card.'''
'Cluster Bombs':
text: '''After defending, you may discard this card. If you do, each other ship at Range 1 of the defending section rolls 2 attack dice, suffering all damage (%HIT%) and critical damage (%CRIT%) rolled.'''
"Adaptability":
name: "Adaptabilidad"
text: """<span class="card-restriction">Carta dual.</span>%LINEBREAK%<strong>Cara A:</strong> La Habilidad de tu piloto se incrementa en 1.%LINEBREAK%<strong>Cara B:</strong> La habilidad de tu piloto se reduce en 1."""
"Electronic Baffle":
name: "Regulador Electrónico"
text: """Cuando recibas una ficha de Tensión o una ficha de Iones, puedes sufrir 1 de daño para descartar esa ficha."""
"4-LOM":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, durante el paso "Modificar la tirada de ataque" puedes recibir 1 ficha de Iones para elegir 1 de las fichas de Concentración o Evasión del defensor. Esa ficha no se puede gastar durante este ataque."""
"<NAME>":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, si no estás tensionado, puedes recibir tantas fichas de Tensión como quieras para elegir una cantidad igual de dados de defensa. El defensor debe volver a tirar esos dados."""
'<NAME>':
name: "<NAME>"
text: """<strong>Acción:</strong> Asigna 1 ficha de Concentración a tu nave y recibe 2 fichas de Tensión. Hasta el final de la ronda, cuando ataques puedes volver a tirar hasta 3 dados de ataque."""
"<NAME>":
name: "<NAME>"
text: """%SCUMONLY%%LINEBREAK%Cada vez que se te asigne una ficha de Concentración o de Tensión, a todas las demás naves aliadas equipadas con "Enlace Mental Attani" se les debe asignar también una ficha de ese mismo tipo si es que no tienen ya una."""
"<NAME>":
text: """%SCUMONLY%%LINEBREAK%Después de que efectúes un ataque, si al defensor se le infligió una carta de Daño boca arriba, puedes descartar esta carta para elegir y descartar 1 de las cartas de Mejora del defensor."""
"<NAME>":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, puedes volver a tirar 1 dado de ataque. Si el defensor es un piloto único, en vez de eso puedes volver a tirar hasta 2 dados de ataque."""
'"<NAME>"':
name: '"<NAME>"'
text: """%SCUMONLY%%LINEBREAK%<strong>Acción:</strong> Coloca 1 ficha de Escudos sobre esta carta.%LINEBREAK%<strong>Acción:</strong> Quita 1 ficha de Escudos de esta carta para recupera 1 de Escudos (hast aun máximo igual a tu valor de Escudos)."""
"R5-P8":
text: """Una vez por ronda, después de que te defiendas puedes volver a tirar 1 dado de ataque. Si sacas %HIT%, el atacante sufre 1 de daño. Si sacas %CRIT%, tanto tú como el atacante sufrís 1 de daño."""
'Thermal Detonators':
name: "<NAME>onadores Térmicos"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Detonador térmico.%LINEBREAK%Esta ficha se <strong>detona</strong> al final de la fase de Activación.%LINEBREAK%<strong>Ficha de Detonador Térmico:</strong> Cuando esta bomba detona, cada nave a Alcance 1 de la ficha sufre 1 de daño y recibe 1 ficha de tensión. Después, descarta esta ficha."""
"Overclocked R4":
name: "Droide R4 trucado"
text: """Durante la fase de Combate, cuando gastes una ficha de Concentración puedes recibir 1 ficha de Tensión para asignar 1 ficha de Concentración a tu nave."""
'Systems Officer':
name: "Oficial de Sistemas"
text: '''%IMPERIALONLY%%LINEBREAK%Después de que ejecutes una maniobra verde, elige otra nave aliada que tengas a alcance 1. Esa nave puede fijar un blanco.'''
'<NAME>':
name: "<NAME>"
text: '''Cuando ataques desde tu arco de fuego auxiliar trasero, la Agilidad del defensor se reduce en 1 (hasta un mínimo de 0).'''
'R3 Astromech':
name: "Droide astromecánico R3"
text: '''Una vez por ronda, cuando ataques con un armamento principal, durante el paso "Modificar la tirada de ataque" puedes anular 1 de tus resultados %FOCUS% para asignar 1 ficha de Evasión a tu nave.'''
'Collision Detector':
name: "Detector de colisiones"
text: '''Cuando realices un impulso, un tonel volado o desactives tu camuflaje, tu nave y plantilla de maniobra se pueden solapar con obstáculos.%LINEBREAK%Cuando hagas una tirada de dados para determinar el daño causado por obstáculos, ignora todos tus resultados %CRIT%.'''
'Sensor Cluster':
name: "Conjunto de sensores"
text: '''Cuando te defiendas, puedes gastar una ficha de Concentración para cambiar 1 de tus resultados de car avacía por 1 resultado %EVADE%.'''
'Fearlessness':
name: "<NAME>repide<NAME>"
text: '''%SCUMONLY%%LINEBREAK%Cuando ataques, si estás dentro del arco de fuego del defensor a alcance 1 y el defensor está dentro de tu arco de fuego, puedes añadir 1 resultado %HIT% a tu tirada.'''
'Ketsu Onyo':
text: '''%SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes elegir 1 nave enemiga que tengas dentro de tu arco de fuego a alcance 1-2. Esa nave no retira sus fichas de Campo de tracción.'''
'Latts Razzi':
text: '''%SCUMONLY%%LINEBREAK%Cuando te defiendas, puedes quitarle al atacante 1 ficha de Tensión para añadir 1 resultado 1 %EVADE% a tu tirada.'''
'IG-88D':
text: '''%SCUMONLY%%LINEBREAK%Tu piloto tiene la misma capacidad especial que cualquier otra nave aliada equipada con la carta de Mejora <em>IG-2000</em> (además de su propia capacidad especial).'''
'Rigged Cargo Chute':
name: "Tolva de evacuación de carga"
text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Cargamento.'''
'Seismic Torpedo':
name: "Torpedo sísmico"
text: '''<strong>Acción:</strong> Descarta esta carta para elegir un obstáculo que tengas a alcance 1-2 y dentro de tu arco de fuego normal. Toda nave situada a alcance 1 del obstáculo tira 1 dado de ataque y sufre cualquier daño (%HIT%) o o daño crítico (%CRIT%) otenido. Luego retira el obstáculo.'''
'Black Market Slicer Tools':
name: "Sistemas ilegales de guerra electrónica"
text: '''<strong>Acción:</strong> Elige una nave enemiga bajo tensión que tengas a alcance 1-2 y tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, quítale 1 ficha de Tensión e inflíngele 1 carta de Daño boca abajo.'''
# Wave X
'Kylo Ren':
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Acción:</strong> Asigna la carta de Estado "Yo re mostraré el Lado Oscuro" a una nave enemiga que tengas a alcance 1-3.'''
'<NAME>':
text: '''%SCUMONLY%%LINEBREAK%Después de que ejecutes una maniobra que te haga solaparte con una nave enemiga, puedes sufrir 1 de daño para realizar 1 acción gratuita.'''
'A Score to Settle':
name: "Una cuenta pendiente"
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", elige 1 nave enemiga y asígnale la carta de Estado "Una deuda por saldar"%LINEBREAK%Cuando ataques a una nave que tiene asignada la carta de Estado "Una deuda por saldar", puedes cambair 1 resultado %FOCUS% por un resultado %CRIT%.'''
'<NAME>':
text: '''%REBELONLY%%LINEBREAK%<strong>Acción:</strong> Elige 1 nave aliada que tengas a alcance 1-2. Asigna 1 ficha de Concentración a esa nave por cada nave enemiga que tengas dentro de tu arco de fuego a alcance 1-3. No puedes asignar más de 3 fichas de esta forma.'''
'<NAME>':
text: '''%REBELONLY%%LINEBREAK%Al final de la fase de Planificación, puedes elegir una nave enemiga que tengas a alcance 1-2. Di en voz alta la dirección y velocidad que crees que va a tener esa nave, y luego mira su selector d emaniobras. Si aciertas, puedes girar la rueda de tu selector para asignarle otra maniobra.'''
'Fin<NAME>':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques con un armamento principal o te defiendas, si la nave enemiga está dentro de tu arco de fuego, puedes añadir 1 resultado de cara vacía a tu tirada.'''
'Rey':
text: '''%REBELONLY%%LINEBREAK%Al comienzo de la fase Final, puedes colocar 1 de las fichas de Concentración de tu nave sobre esta carta. Al comienzo de la fase de Combate, puedes asignar 1 de esas fichas a tu nave.'''
'Burnout SLAM':
name: "Superacelerador de emergencia"
text: '''%LARGESHIPONLY%%LINEBREAK%Tu barra de acciones gana el icono %SLAM%.%LINEBREAK%Después de que realices una acción de MASA, descarta esta carta.'''
'Primed Thrusters':
name: "Propulsores sobrealimentados"
text: '''%SMALLSHIPONLY%%LINEBREAK%Las fichas de Tensión no te impiden realizar acciones de impulso o de tonel volado a menos que tengas asignadas 3 fichas de Tensión o más.'''
'Pattern Analyzer':
name: "Analizador de patrones"
text: '''Cuando ejecutes una maniobra, puedes resolver el paso "Comprobar Tensión del piloto" después del paso "Realizar una acción" (en vez de antes de ese paso).'''
'Snap Shot':
name: "Disparo de reacción"
text: '''Después de que una nave enemiga ejecute una maniobra, puedes efectuar este ataque contra esa nave. <strong>Ataque:</strong> Ataca a 1 nave. No puedes modificar tus dados de ataque y no puedes volver a atacar en esta fase.'''
'M9-G8':
text: '''%REBELONLY%%LINEBREAK%Cuando una nave que tengas fijada como blanco esté atacando, puedes elegir 1 dado de ataque. El atacante debe volver a tirar ese dado.%LINEBREAK%Puedes fijar como blanco otras naves aliadas.'''
'EMP Device':
name: "Dispositivo de pulso electromagnético"
text: '''Durante la fase de Combate, en vez de efecturas ningún ataque, puedes descartar esta carta para asignar 2 fichas de Iones a toda nave que tengas a alcance 1.'''
'<NAME>':
name: "<NAME>"
text: '''%REBELONLY%%LINEBREAK%Después de que efectúes un ataque no impacte, puedes asignar 1 ficha de Concentración a tu nave.'''
'General Hux':
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Acción:</strong> Elige hasta 3 naves aliadas que tengas a alcance 1-2. Asigna 1 ficha de Concentración a cada una de esas naves y asigna la carta de Estado "Lealtad fanática" a 1 de ellas. Luego recibes 1 ficha de Tensión.'''
'Operations Specialist':
name: "Especialista en operaciones"
text: '''%LIMITED%%LINEBREAK%Después de que una nave aliada que tengas a alcance 1-2 efectúe un ataque que no impacte, puedes asignar 1 ficha de Concentración a una nave aliada situada a alcance 1-3 del atacante.'''
'Targeting Synchronizer':
name: "Sincronizador de disparos"
text: '''Cuando una nave aliada que tengas a alcance 1-2 ataque a una nave que tienes fijada como blanco, esa nave aliada considera el encabezado "<strong>Ataque (Blanco fijado):</strong> como si fuera "<strong>Ataque:</strong>." Si un efecto de juego indica a esa nave que gaste una ficha de Blanco fijada, en vez de eso puede gastar tu ficha de Blanco fijado.'''
'Hyperwave Comm Scanner':
name: "Escáner de frecuencias hiperlumínicas"
text: '''Al comienzo del paso "Desplegar fuerzas", puedes elegir considerar la Habilidad de tu piloto como si fuera 0, 6 o 12 hasta el final del paso. Durante la preparación de la partida, después de que otra nave aliada sea colocada a alcance 1-2 de ti, puedes asignar 1 ficha de Concentración o Evasión a esa nave.'''
'Trick Shot':
name: "Dis<NAME>"
text: '''Cuando ataques, si el ataque se considera obstruido, puedes tirar 1 dado de ataque adicional.'''
'Hotshot Co-pilot':
name: "Cop<NAME> extraord<NAME>"
text: '''Cuando ataques con un armamento princnipal, el defensor debe gastar 1 ficha de Concentración si le es posible.%LINEBREAK%Cuando te defiendas, el atacante debe gastar 1 ficha de Concentración si le es posible.'''
'''Scavenger Crane''':
name: "<NAME> de <NAME>"
text: '''Después de que una nave que tengas a alcance 1-2 sea destruida, puedes elegir una carta de Mejora %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, o Modificación que estuviera equipada en tu nave y ponerla boca arriba. Luego tira 1 dado de ataque. Si sacas una cara vacía, descarta tu "Grúa de salvamento".'''
'B<NAME>':
text: '''%REBELONLY%%LINEBREAK%Cuando fijes un blanco, puedes fijarlo sobre una nave enemiga que esté situada a alcance 1-3 de cualquier nave aliada.'''
'Baze Malbus':
text: '''%REBELONLY%%LINEBREAK%Después de que efectúes un ataque que no impacte, puedes realizar inmediatamente un ataque con tu armamento principal contra una nave diferente. No podrás realizar ningún otro ataque en esta misma ronda.'''
'Inspiring Recruit':
name: "<NAME>"
text: '''Una vez por ronda, cuando una nave aliada que tengas a alcance 1-2 se quite una ficha de Tensión, puede quitarse 1 ficha de Tensión adicional.'''
'Swarm Leader':
name: "<NAME>"
text: '''Cuando ataques con un armamento principal, elige hasta 2 ortas naves aliadas que tengan al defensor dentro de sus arcos de fuego a alcance 1-3. Quita 1 ficha de Evasión de cada nave elegida para tirar 1 dado de ataque adicional por cada ficha quitada.'''
'Bistan':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques a alcance 1-2, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%.'''
'Expertise':
name: "<NAME>"
text: '''Cuando ataques, si no estás bajo tensión, puedes cambair todos tus resultados %FOCUS% por resultados %HIT%.'''
'BoShek':
text: '''Cuando una nave con la que estás en contacto se activa, puedes mirar la maniobra que ha elegido. Si lo haces, el jugador que controla esa nave <strong>debe</strong> elegir en el selector una maniobra adyacente. La nave puede revelar y efectuar esa maniobra incluso aunque esté bajo tensión.'''
# C-ROC
'Heavy Laser Turret':
ship: "Crucero C-ROC"
name: "Torreta de láser pesado"
text: '''<span class="card-restriction">Sólo crucero C-ROC</span>%LINEBREAK%<strong>Ataque (energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque contra 1 nave (incluso contra una nave fuera de tu arco de fuego).'''
'Cikat<NAME>':
text: '''%SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes descartar esta carta pare reemplazar una carta de Mejora %ILLICIT% o %CARGO% que tengas equipada boca arriba por otra carta de Mejora de ese mismo tipo con un coste en puntos de escuadrón igual o inferior.'''
'Azmorigan':
text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes gastar 1 de Energía para reemplazar una carta de Mejora %CREW% o %TEAM% que tengas equipada boca arriba por otra carta de Mejora de ese mismo tipo con un coste en puntos de escuadrón igual o inferior.'''
'Quick-release Cargo Locks':
name: "Enganches de carga de apertura rápida"
text: '''%LINEBREAK%Al final de la fase de Activación puedes descartar esta carta para <strong>colocar</strong> 1 indicador de Contenedores.'''
'Supercharged Power Cells':
name: "Células de energía sobrealimentadas"
text: '''Cuando ataques, puedes descartar esta carta para tirar 2 dados de ataque adicionales.'''
'ARC Caster':
name: "Proyector ARC"
text: '''<span class="card-restriction">Sólo Escoria y Rebelde.</span>%DUALCARD%%LINEBREAK%<strong>Cara A:</strong>%LINEBREAK%<strong>Ataque:</strong> Ataca a 1 nave. Si este ataque impacta, debes elegir 1 otra nave a alcance 1 del defensor para que sufra 1 punto de daño.%LINEBREAK%Luego dale la vuelta a esta carta.%LINEBREAK%<strong>Cara B:</strong>%LINEBREAK%(Recargándose) Al comienzo de la fase de Combate, puedes recibir una ficha de Armas inutilizadas para darle la vuelta a esta carta.'''
'Wookiee Commandos':
name: "Comandos wookiees"
text: '''Cuando ataques, puedes volver a tirar tus resultados %FOCUS%.'''
'Synced Turret':
name: "Torreta sincronizada"
text: '''<strong>Ataque (Blanco fijado:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).%LINEBREAK%Si el defensor está dentro de tu arco de fuego principal, puedes volver a tirar tantos dados de ataque como tu valor de Armamento principal.'''
'Unguided Rockets':
name: "Cohetes no guiados"
text: '''<strong>Ataque (Concentración):</strong> Ataca a 1 nave.%LINEBREAK%Tus dados de ataque solo pueden ser modificados mediante el gasto de una ficha de Concentración para su efecto normal.'''
'Intensity':
name: "<NAME>"
text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Cara A:</strong> Después de que realices una acción de impulso o de tonel volado, puedes asignar 1 ficha de Concentración o de Evasión a tu nave. Si lo haces, dale la vuelta a esta carta.%LINEBREAK%<strong>Cara B:</strong> (Agotada) Al final de la fase de Combate, puedes gasta 1 ficha de Concentración o de Evasión para darle la vuelta a esta carta.'''
'J<NAME>ba the Hutt':
name: "<NAME>"
text: '''%SCUMONLY%%LINEBREAK%Cuando equipes esta carta, coloca 1 ficha de Material Ilícito encima de cada carta de Mejora %ILLICIT% en tu escuadrón. Cuando debas descartar una carta de Mejora, en vez de eso puedes descartar 1 ficha de Material ilícito que esté encima de esa carta.'''
'IG-RM Thug Droids':
name: "Droides matones IG-RM"
text: '''Cuando ataques, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%.'''
'Selflessness':
name: "Autos<NAME>"
text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%Cuando una nave aliada que tengas a alcance 1 sea impactada por un ataque, puedes descartar esta carta para sufrir todos los resultados %HIT% no anulados en vez de la nave objetivo.'''
'Breach Specialist':
name: "Especialista en brechas"
text: '''Cuando recibas una carta de Daño boca arriba, puedes gastar 1 ficha de Refuerzo para darle la vuelta y ponerla boca abajo (sin resolver su efecto). Si lo haces, hasta el final de la ronda, cuando recibas una carta de Daño boca arriba, dale la vuelta par aponerla boca abajo (sin resolver su efecto).'''
'Bomblet Generator':
name: "Generador de minibombas"
text: '''Cuando reveles tu maniobra, puedes <strong>soltar</strong> 1 ficha de Minibomba%LINEBREAK%Esta ficha se <strong>detona</strong> al final de la fase de Activación.%LINEBREAK%<strong>Ficha de Minibomba:</strong> Cuando esta ficha detone, cada nave a Alcance 1 tira 2 dados de ataque y sufre todo el daño (%HIT%) y daño crítico (%CRIT%) obtenido en la tirada. Después se descarta esta ficha.'''
'Cad Bane':
text: '''%SCUMONLY%%LINEBREAK%Tu barra de mejoras gana el icono %BOMB%. Una vez por ronda, cuando una nave enemiga tire dados de ataque debido a la detonación de una bomba aliada, puedes elegir cualquier cantidad de resultados %FOCUS% y de cara vacía. La nave enemiga debe volver a tirar esos resultados.'''
'Minefield Mapper':
name: "Trazador de campos de minas"
text: '''Durante la preparación de la partida, después del paso "Desplegar fuerzas", puedes descartar cualquier cantidad de tus cartas de Mejora %BOMB% equipadas. Coloca las correspondientes fichas de Bomba en la zona de juego más allá de alcance 3 de las naves enemigas.'''
'R4-E1':
text: '''Puedes realizar acciones que figuren en tus cartas de Mejora %TORPEDO% y %BOMB% incluso aunque estés bajo tensión. Después de que realices una acción de esta manera, puedes descartar esta carta para retirar 1 ficha de Tensión de tu nave.'''
'Cruise Missiles':
name: "Misiles de crucero"
text: '''<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque. %LINEBREAK%Puedes tirar tantos dados de ataque adicionales como la velocidad de la maniobra que has ejecutado en esta ronda, hasta un máximo de 4 dados adicionales.'''
'Ion Dischargers':
name: "Descargadores de iones"
text: '''Después de que recibas una ficha de Iones, puedes elegir una nave enemiga que tengas a alcance 1. Si lo haces retira esa ficha de Iones. A continuación, esa nave puede elegir recibir 1 ficha de Iones. Si lo hace, descarta esta carta.'''
'Harpoon Missiles':
name: "Misiles arpón"
text: '''<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efcetuar este ataque.%LINEBREAK%Si este ataque impacta, después de resolver el ataque, asigna el estado "¡Arponeado!" al defensor.'''
'Ordnance Silos':
name: "<NAME>"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando te equipes con esta carta, coloca 3 fichas de Munición de artillería encima de cada otra carta de mejora %BOMB% que tengas equipada. Cuando debas descartar una carta de Mejora, en vez de eso puedes descartar 1 ficha de Munición de artillería que esté encima de esa carta.'''
'Trajectory Simulator':
name: "Simulador de trayectorias"
text: '''Puedes lanzar bombas utilizando la plantilla de maniobra (%STRAIGHT% 5) en vez de soltarlas. No puedes lanzar de esta manera bombas que tengan el encabezado "<strong>Acción:</strong>".'''
'Jamming Beam':
name: "Haz de interferencias"
text: '''<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, asígnale al defensor 1 ficha de Interferencia. Luego se anulan <strong>todos</strong> los resultados de los dados.'''
'Linked Battery':
name: "Batería enlazada"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando ataques con tu armament principal o con un armamento secundario %CANNON%, puedes volver a tirar 1 dado de ataque.'''
'Saturation Salvo':
name: "Andanada de saturación"
text: '''Después de que efectúes un ataque con un armamento secundario %TORPEDO% o %MISSILE% que no impacte, toda nave que esté situada a alcance 1 del defensor y que tenga una puntuación de Agilidad inferior al coste en puntos de escuadrón de la carta de Meora %TORPEDO% o %MISSILE% debe tirar 1 dado de ataque y sufrir cualquier daño normal (%HIT%) o daño crítico (%CRIT%) obtenido.'''
'Contraband Cybernetics':
name: "Ciberimplantes ilícitos"
text: '''Cuando pases a ser la nave activa durante la fase de Activación, puedes descartar esta carta y recibir 1 ficha de Tensión. Si lo haces, hasta el final de la ornda, puedes llevar a cabo acciones y maniobras rojas incluso aunque estés bajo tensión.'''
'Maul':
text: '''%SCUMONLY% <span class="card-restriction">Ignora esta restricción si tu escuadrón contiene a "Ezra Bridger."</span>%LINEBREAK%Cuando ataques, si no estás bajo tensión, puedes recibir cualquier cantidad de fichas de Tensión para volver a tirar esa misma cantidad de dados de ataque.%LINEBREAK% Después de que realices un ataque que impacte, puedes retirar 1 de tus fichas de Tensión.'''
'Courier Droid':
name: "D<NAME>"
text: '''Al comienzo del paso "Desplegar fuerzas", puedes elegir que la puntuación de Habilidad de tu piloto se considere 0 u 8 hasta el final de este paso.'''
'"Chopper" (Astromech)':
text: '''<strong>Acción: </strong>Descarta 1 de tus otras cartas de Mejora equipadas para recuperar 1 ficha de Escudos.'''
'Flight-Assist Astromech':
name: "Droide astromecánico de ayuda al pilotaje"
text: '''No puedes efectuar ataques ataques contra naves que estén situadas fuera de tu arco de fuego.%LINEBREAK%Después de que ejecutes una maniobra, si no te has solapado con una nave ni con un obstáculo, y no tienes ninguna nave enemiga a alcance 1-3 situada dentro de tu arco de fuego, puedes realizar una acción gratuita de impulso o tonel volado.'''
'Advanced Optics':
name: "Sensores ópticos avanzados"
text: '''No puedes tener más de 1 ficha de Concentración.%LINEBREAK%Durante la fase Final, no retires de tu nave las fichas de Concentración que no hayas usado.'''
'Scrambler Missiles':
name: "Misiles interferidores"
text: '''<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efectuar este ataque.%LINEBREAK%Si este ataque impacta, el defensor y toda otra nave que tenga a alcance 1 recibe 1 ficha de Interferencia. Luego se anulan <strong>todos</strong> los resultados de dados.'''
'R5-TK':
text: '''Puedes fijar como blanco naves aliadas.%LINEBREAK%Puedes efectuar ataques contra naves aliadas.'''
'Threat Tracker':
name: "<NAME>"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando una nave enemiga que tengas a alcance 1-2 y dentro de tu arco de fuego se convierta en la nave activa durante la fase de Combate, puedes gastar la ficha de Blanco fijado que tengas sobre esa nave para realizar una acción gratuita de impulso o tonel volado, si esa acción figura en tu barra de acciones.'''
'Debris Gambit':
name: "Treta de los desechos"
text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Acción:</strong> Asigna 1 ficha de Evasión a tu nave por cada obstáculo que tengas a alcance 1, hast aun máximo de 2 fichas de Evasión.'''
'Targeting Scrambler':
name: "Interferidor de sistemas de puntería"
text: '''Al comienzo de la fase de Planificación, puedes recibir una ficha de Armas bloqueadas para elegir una nave que tengas a alcance 1-3 y asignarle el Estado "Sistemas interferidos".'''
'Death Troopers':
name: "Soldados de la muerte"
text: '''Después de que otra nave aliada que tengas a alcance 1 se convierta en el defensor, si estás situado a alcance 1-3 del atacante y dentro de su arco de fuego, el atacante recibe 1 ficha de Tensión.'''
'ISB Slicer':
name: "Técnico en guerra electrónica de la OSI"
text: '''%IMPERIALONLY%%LINEBREAK%Después de que realices una acción de interferencia contra una nave enemiga, puedes elegir una nave que esté situada a alcance 1 de esa nave enemiga y no esté interferida, y asignarle 1 ficha de Interferencia.'''
'Tactical Officer':
name: "Oficial táctico"
text: '''%IMPERIALONLY%%LINEBREAK%Tu barra de acciones gana el icono %COORDINATE%.'''
'Saw Gerrera':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques, puedes sufrir 1 de daño para cambiar todos tus resultados %FOCUS% por resultados %CRIT%.'''
'<NAME> <NAME>':
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", asigna el Estado "Prototipo optimizado" a una nave aliada del Imperio Galáctico que tenga un valor de Escudos igual o inferior a 3.'''
'<NAME>':
text: '''%REBELONLY%%LINEBREAK%Después de que te defiendas, puedes fijar como blanco al atacante.'''
'Renegade Refit':
name: "Reequipado por los Renegados"
text: '''<span class="card-restriction">Sólo T-65 Ala-X y Ala-U.</span>%LINEBREAK%Te puedes equipar con un máximo de 2 mejoras de Modificación distintas.%LINEBREAK%El coste en puntos de escuadrón de cada una de las mejoras %ELITE% que tengas equipadas en tu nave se reduce en 1 (hasta un mínimo de 0).'''
'Thrust Corrector':
name: "<NAME>"
text: '''Cuando te defiendas, si no tienes asignadas más de 3 fichas de Tensión, puedes recibir 1 ficha de Tensión para anular todos los resultados de tus dados. Si lo haces, añade 1 resultado %EVADE% a tu tirada. No podrás volver a modificar tus dados durante este ataque.%LINEBREAK%Sólo puedes equipar esta Mejora en naves con una puntuación de Casco 4 o inferior.'''
modification_translations =
"Stealth Device":
name: "Dispositivo de Sigilo"
text: """Tu Agilidad se incrementa en 1. Descarta esta carta si eres alcanzado por un ataque."""
"Shield Upgrade":
name: "Escudos Mejorados"
text: """Tu valor de Escudos se incrementa en 1."""
"Engine Upgrade":
name: "Motor Mejorado"
text: """Tu barra de acciones gana el ícono %BOOST%."""
"Anti-Pursuit Lasers":
name: "Cañones Láser Antipersecución"
text: """Después de que una nave enemiga ejecute una maniobra que le cause solapar su peana con la tuya, lanza un dado de ataque. Si el resultado es %HIT% o %CRIT%, el enemigo sufre 1 de daño."""
"Targeting Computer":
name: "Computadora de Selección de Blancos"
text: """Tu barra de acciones gana el icono %TARGETLOCK%."""
"Hull Upgrade":
name: "Blindaje mejorado"
text: """Tu valor de Casco se incrementa en 1."""
"Munitions Failsafe":
name: "Sistema de Munición a Prueba de Fallos"
text: """Cuando ataques con un armamento secundario que requiera descartarlo para efectuar el ataque, no se descarta a menos que el ataque impacte al objetivo."""
"Stygium Particle Accelerator":
name: "Acelerador de Partículas de Estigio"
text: """<span class="card-restriction">Soo TIE Fantasma.</span><br /><br />Cuando realices una acción de camuflaje o desactives tu camuflaje, puedes realizar una acción gratuita de Evasión."""
"Advanced Cloaking Device":
name: "Dispositivo de Camuflaje Avanzado"
text: """Despues de que efectúes un ataque, puedes realizar una acción gratuita de camuflaje."""
ship: "TIE Fantasma"
"Combat Retrofit":
name: "Equipamiento de Combate"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Tu valor de casco se incrementa en 2 y tu valor de escudos se incrementa en 1."""
ship: 'Transporte mediano GR-75'
"B-Wing/E2":
text: """<span class="card-restriction">Solo Ala-B.</span><br /><br />Tu barra de mejoras gana el icono de mejora %CREW%."""
ship: "Ala-B"
"Countermeasures":
name: "Contramedidas"
text: """Al comienzo de la fase de Combate, puedes descartar esta carta para aumentar en 1 tu Agilidad hasta el final de la ronda. Después puedes quitar 1 ficha enemiga de Blanco Fijado de tu nave."""
"Experimental Interface":
name: "Interfaz Experimental"
text: """Una vez por ronda, después de que realices una acción, puedes llevar a cabo 1 acción gratuita de una carta de Mejora equipada que tenga el encabezado "<strong>Acción:</strong>". Después recibes 1 ficha de Tension."""
"Tactical Jammer":
name: "Inhibidor Táctico"
text: """Tu nave puede obstruir ataques enemigos."""
"Autothrusters":
name: "Propulsores Automatizados"
text: """Cuando te defiendas, si estás fuera del arco de fuego del atacante, o dentro de su arco de fuego pero más allá de alcance 2, puedes cambiar 1 de tus resultados de cara vacía por un resultado %EVADE%. Sólo puedes equiparte con esta carta si tienes el icono de acción %BOOST%."""
"Twin Ion Engine Mk. II":
name: "Motor Iónico Doble Modelo II"
text: """<span class="card-restriction">Solo TIE.</span>%LINEBREAK%Puedes tratar todas las maniobras de inclinación (%BANKLEFT% y %BANKRIGHT%) como si fueran maniobras verdes."""
"Maneuvering Fins":
name: "Alerones de Estabilización"
text: """<span class="card-restriction">Solo YV-666.</span>%LINEBREAK%Cuando reveles una maniobra de giro (%TURNLEFT% o %TURNRIGHT%), puedes rotar tu selector para elegir en su lugar la maniobra de inclinación correspondiente (%BANKLEFT% o %BANKRIGHT%) de igual velocidad."""
"Ion Projector":
name: "Proyector de Iones"
text: """%LARGESHIPONLY%%LINEBREAK%Después de que una nave enemiga ejecute una maniobra que la solape con tu nave, tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, la nave enemiga recibe 1 ficha de Iones."""
"Advanced SLAM":
name: "Motor Sublumínico Avanzado"
text: """Después de efectuar una acción de MASA, si no te has solapado con un obstáculo ni con otra nave, puedes llevar a cabo una acctión gratuita."""
'Integrated Astromech':
name: "Droide Astromecánico Integrado"
text: '''<span class="card-restriction">Solo X-wing.</span>%LINEBREAK%Cuando recibas una carta de Daño, puedes descartar 1 de tus cartas de Mejora %ASTROMECH% para descartar esa carta de Daño (sin resolver su efecto).'''
'Optimized Generators':
name: "Generadores optimizados"
text: '''%HUGESHIPONLY%%LINEBREAK%Una vez por ronda, cuando asignes Energía a una carta de Mejora equipada, obtienes 2 de Energía.'''
'Automated Protocols':
name: "Procedimientos automatizados"
text: '''%HUGESHIPONLY%%LINEBREAK%OUna vez por ronda, después de que realices una acción que no sea una acción de recuperación o de refuerzo, puedes gastar 1 de Energía para realizar una acción gratuita de recuperación o de refuerzo.'''
'Ordnance Tubes':
text: '''%HUGESHIPONLY%%LINEBREAK%You may treat each of your %HARDPOINT% upgrade icons as a %TORPEDO% or %MISSILE% icon.%LINEBREAK%When you are instructed to discard a %TORPEDO% or %MISSILE% Upgrade card, do not discard it.'''
'Long-Range Scanners':
name: "Sensores de Largo Alcance"
text: '''Puedes fijar como blanco naves que tengas a alcance 3 o superior. No puedes fijar como blanco naves que tengas a alcance 1-2. Para poder equipar esta carta has de tener los iconos de mejora %TORPEDO% y %MISSILE% en tu barra de mejoras.'''
"Guidance Chips":
name: "Chips de Guiado"
text: """Una vez por ronda, cuando ataques con un sistema de armamento secundario %TORPEDO% o %MISSILE%, puedes cambiar 1 de tus resultados de dado por un resultado %HIT% (o por un resultad %CRIT% si tu valor de Armamento principal es de 3 o más)."""
'Vectored Thrusters':
name: "Propulsores vectoriales"
text: '''%SMALLSHIPONLY%%LINEBREAK%Tu barra de acciones gana el icono de acción %BARRELROLL%.'''
'Smuggling Compartment':
name: "Compartimento para contrabando"
text: '''<span class="card-restriction">Sólo YT-1300 y YT-2400.</span>%LINEBREAK%Tu barra de mejoras gana el icono %ILLICIT%.%LINEBREAK%Puedes equipar 1 mejora de Modificación adicional que no cueste más de 3 puntos de escuadrón.'''
'Gyroscopic Targeting':
name: "Estabilización giroscópica"
ship: "Nave de persecución clase Lancero"
text: '''<span class="card-restriction">Sólo Nave de persecución clase Lancero.</span>%LINEBREAK%Al final de la fase de Combate, si en esta ronda ejecutaste una maniobra de velocidad 3, 4 o 5, puedes reorientar tu arco de fuego móvil.'''
'Captured TIE':
ship: "Caza TIE"
name: "TIE capturado"
text: '''<span class="card-restriction">Sólo Caza TIE.</span>%REBELONLY%%LINEBREAK%Las naves enemigas cuyos pilotos tengan una Habilidad más baja que la tuya no pueden declararte como blanco de un ataque. Después de que efectúes un ataque o cuando seas la única nave aliada que queda en juego, descarta esta carta.'''
'Spacetug Tractor Array':
name: "Campos de tracción de remolque"
ship: "Saltador Quad"
text: '''<span class="card-restriction">Sólo Saltador Quad.</span>%LINEBREAK%<strong>Acción:</strong> Elige una nave que tengas dentro de tu arco de fuego a distancia 1 y asígnale una ficha de Campo de tracción. Si es una nave aliada, resuelve el efecto de la ficha de Campo de tracción como si se tratara de una nave enemiga.'''
'Lightweight Frame':
name: "Fuselaje ultraligero"
text: '''<span class="card-restriction">Sólo TIE.</span>%LINEBREAK%Cuando te defiendas, tras tirar los dados de defensa, si hay más dados de ataque que dados de defensa, tira 1 dado de defensa adicional.%LINEBREAK%Esta mejora no puede equiparse en naves con puntuación de Agilidad 3 o superior.'''
'Pulsed Ray Shield':
name: "Escudo de rayos pulsátil"
text: '''<span class="card-restriction">Sólo Escoria y Rebelde.</span>%LINEBREAK%Durante la fase Final, puedes recibir 1 ficha de Iones para recuperar 1 ficha de Escudos (pero no puedes exceder tu valor de Escudos). Sólo puedes equipar esta carta si tu valor de Escudos es 1.'''
'Deflective Plating':
name: "Blindaje deflector de impactos"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando una bomba aliada se detone, puedes elegir no sufrir sus efectos. Si lo haces, tira un dado de ataque. Si sacas %HIT%, descarta esta carta.'''
'Servomotor S-Foils':
name: "<NAME>"
text: '''<span class="card-restriction">Sólo T-65 Ala-X.</span> %DUALCARD%%LINEBREAK%<strong>Cara A (Ataque):</strong>Tu barra de acciones gana el icono %BARRELROLL%. Si no estás bajo tensión, cuando reveles una maniobra (%TURNLEFT% 3) o (%TURNRIGHT% 3), puedes considerarla como si fuera una maniobra roja (%TROLLLEFT% 3) o (%TROLLRIGHT% 3) con la misma dirección.%LINEBREAK%Al comienzo de la fase de Activación, puedes darle la vuelta a esta carta.%LINEBREAK%<strong>Cara B (Cerrada):</strong>Tu valor de Armamento principal se reduce en 1. Tu barra de acciones gana el icono %BOOST%. Tus maniobras (%BANKLEFT% 2) y (%BANKRIGHT% 2 ) se consideran verdes.%LINEBREAK%Al comienzo de la fase de Activacion, puedes darle la vuelta a esta carta.'''
'Multi-spectral Camouflage':
name: "Camuflaje multiespectral"
text: '''%SMALLSHIPONLY%%LINEBREAK%Después de que recibas una ficha roja de Blanco fijado, si sólo tienes asignada 1 ficha roja de Blanco fijado, tira 1 dado de defensa. Si obtienes un resultado %EVADE%, retira esa ficha roja de Blanco fijado.'''
title_translations =
"Slave I":
name: "Esclavo 1"
text: """<span class="card-restriction">Solo Firespray-31.</span><br /><br />Tu barra de mejoras gana el icono %TORPEDO%."""
"Millennium Falcon":
name: "<NAME>"
text: """<span class="card-restriction">Solo YT-1300.</span><br /><br />Tu barra de acciones gana el icono %EVADE%."""
"<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Solo HWK-290.</span><br /><br />Durante la fase Final, no retires de tu nave las fichas de Concentración que no hayas usado."""
"ST-321":
text: """<span class="card-restriction">Solo Lanzadera clase <em>Lambda</em>.</span><br /><br />Cuando fijas un blanco, puedes hacerlo con cualquier nave enemiga de la zona de juego."""
ship: "Lanzadera clase Lambda"
"Royal Guard TIE":
name: "TIE de la Guardia Real"
ship: "Interceptor TIE"
text: """<span class="card-restriction">Solo TIE Interceptor.</span><br /><br />Puedes equipar un máximo de 2 mejoras distintas de Modificación (en vez de 1).<br /><br />Esta mejora no puede equiparse en naves con pilotos de Habilidad 4 o inferior."""
"Dod<NAME>'s Pride":
name: "<NAME>"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />Cuando realices una accion de Coordinación, puedes elegir 2 naves aliadas en vez de 1. Cada una de estas naves pueden realizar 1 accion gratuita."""
ship: "Corbeta CR90 (Proa)"
"A-Wing Test Pilot":
name: "Piloto de Ala-A experimental"
text: """<span class="card-restriction">Solo Ala-A.</span><br /><br />Tu barra de mejoras gana 1 icono de mejora %ELITE%.<br /><br />No puedes equipar 2 cartas de Mejora %ELITE% iguales. Tampoco te puedes equipar con esta carta si la Habilidad de tu piloto es 1 o inferior."""
ship: "Ala-A"
"Tantive IV":
name: "<NAME>"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />La barra de mejoras de tu sección de proa gana 1 icono adicional de %CREW% y 1 icono adicional de %TEAM%."""
ship: "Corbeta CR90 (Proa)"
"B<NAME> Hope":
name: "<NAME>"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Una ficha de Refuerzo asignada a tu seccion de proa añade 2 resultados de %EVADE% en vez de 1."""
ship: 'Transporte mediano GR-75'
"Quantum Storm":
name: "<NAME>"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Al principio de la fase Final, si tienes 1 ficha de Energía o menos, ganas 1 ficha de Energía."""
ship: 'Transporte mediano GR-75'
"Dutyfree":
name: "<NAME>"
text: """<span class="card-restriction">Solo GR-75./span><br /><br />Cuando realices una acción de Interferencia, puedes elegir una nave enemiga situada a alcance 1-3 en lugar de 1-2."""
ship: 'Transporte mediano GR-75'
"Jaina's Light":
name: "<NAME>"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />Cuando te defiendas, una vez por ataque, si recibes una carta de Daño boca arriba, puedes descartarla y robar otra carta de Daño boca arriba."""
"Outrider":
name: "<NAME>"
text: """<span class="card-restriction">Solo YT-2400.</span><br /><br />Mientras tu nave tenga equipada una mejora de %CANNON%, <strong>no puedes</strong> atacar con tu armamento principal y puedes atacar con armamentos secundarios %CANNON% contra naves enemigas fuera de tu arco de fuego."""
"Andrasta":
name: "<NAME>"
text: """<span class="card-restriction">Solo Firespray-31.</span><br /><br />Tu barra de mejoras gana 2 iconos %BOMB% adicionales."""
"TIE/x1":
ship: "TIE Avanzado"
text: """<span class="card-restriction">Solo TIE Avanzado.</span>%LINEBREAK%Tu barra de mejoras gana el icono %SYSTEM%.%LINEBREAK%Si te equipas con una mejora %SYSTEM%, su coste en puntos de escuadrón se reduce en 4 (hasta un mínimo de 0)."""
"BTL-A4 Y-<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Solo Ala-Y.</span><br /><br />No puedes atacar naves que estén fuera de tu arco de fuego. Después de que efectúes un ataque con tu armamento principal, puedes realizar inmediatamente un ataque con arma secundaria %TURRET%."""
ship: "Ala-Y"
"IG-2000":
name: "IG-2000"
text: """<span class="card-restriction">Solo Agresor.</span><br /><br />Tu piloto tiene la misma capacidad especial que cualquier otra nave aliada equipada con la carta de Mejora <em>IG-2000</em> (además de su propia capacidad especial)."""
ship: "Agresor"
"Virago":
name: "<NAME>"
text: """<span class="card-restriction">Solo Víbora Estelar.</span><br /><br />Tu barra de mejoras gana los iconos %SYSTEM% y %ILLICIT%.<br /><br />Esta mejora no puede equiparse en naves con pilotos de Habilidad 3 o inferior."""
ship: 'Víbora Estelar'
'"Heavy Scyk" Interceptor (Cannon)':
name: 'Interceptor "Scyk Pesado" (Cañón)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %CANNON%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
'"Heavy Scyk" Interceptor (Missile)':
name: 'Interceptor "Scyk Pesado" (Misil)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %MISSILE%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
'"Heavy Scyk" Interceptor (Torpedo)':
name: 'Interceptor "Scyk Pesado" (Torpedo)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %TORPEDO%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
"Dauntless":
name: "<NAME>"
text: """<span class="card-restriction">Solo VT-49 Diezmador.</span><br /><br />Después de que ejecutes una maniobra que te solape con otra nave, puedes realizar 1 acción gratuita. Luego recibes 1 ficha de Tensión."""
ship: 'VT-49 Diezmador'
"Ghost":
name: "<NAME>"
text: """<span class="card-restriction">Sólo VCX-100.</span>%LINEBREAK%Equipa la carta de Título <em>Fantasma</em> a una Lanzadera de ataque aliada y acóplala a esta nave.%LINEBREAK%Después de que ejecutes una maniobra, puedes desplegar la Lanzadera de ataque desde los salientes de la parte trasera de tu peana."""
"Phantom":
name: "<NAME>"
text: """Mientras estás acoplado, el <em>Espíritu</em> puede efectuar ataques de armamento principal desde su arco de fuego especial y, al final de la fase de Combate, puede efectuar un ataque adicional con una %TURRET% equipada. Si efectúa este ataque, no puede volver a atacar durante esta ronda."""
ship: 'Lanzadera de Ataque'
"TIE/v1":
text: """<span class="card-restriction">Solo Prototipo de TIE Av.</span>%LINEBREAK%Después de que fijes a un blanco, puedes realizar una acción gratuita de evasión."""
ship: 'Prototipo de TIE Avanzado'
"<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Solo Caza Estelar G-1A.</span>%LINEBREAK%Tu barra de acción gana el icono %BARRELROLL%.%LINEBREAK%<strong>Debes</strong> equiparte con 1 carta de Mejora "Proyector de Campo de Tracción" (pagando su coste normal en puntos de escuadrón)."""
ship: 'Caza Estelar G-1A'
"Punishing One":
name: "<NAME>"
text: """<span class="card-restriction">Solo Saltador Maestro 5000.</span>%LINEBREAK%Tu valor de Armamento principal se incrementa en 1."""
ship: 'Saltador Maestro 5000'
"<NAME>ound's Tooth":
name: "<NAME>"
text: """<span class="card-restriction">Solo YV-666.</span>%LINEBREAK%Después de que seas destruido, y antes de retirarte de la zona de juego, puedes <strong>desplegar</strong> al Piloto del <span>Cachorro de Nashtah</span>.%LINEBREAK%El <span>Cachorro de Nashtah</span> no puede atacar en esta ronda."""
"Ass<NAME>":
name: "<NAME>"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%Cuando te defiendas, si la sección atacada tiene asginada una ficha de Refuerzo, puedes cambiar 1 resultado de %FOCUS% por 1 resultado %EVADE%."""
"Instigator":
name: "<NAME>"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%ADespués de que hayas llevado a cabo una acción de recuperación, recuperas 1 de Escudos adicional."""
"Impetuous":
name: "<NAME>"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%Después de que hayas efectuado un ataque que destruya una nave enemiga, puedes fijar un blanco."""
'TIE/x7':
text: '''<span class="card-restriction">Sólo TIE Defensor.</span>%LINEBREAK%Tu barra de mejoras pierde los iconos de mejora %CANNON% y %MISSILE%.%LINEBREAK%Después de que ejecutes una maniobra de velocidad 3, 4 o 5, si no te solapaste con un obstáculo o nave, puedes realizar una acción gratuita de evasión.'''
ship: 'Defensor TIE'
'TIE/D':
text: '''<span class="card-restriction">Sólo TIE Defensor.</span>%LINEBREAK%Una vez por ronda, después de que efectúes un ataque con un armamento secundario %CANNON% con un coste en puntos de escuadrón inferior a 4, puedes efcetuar un ataque con tu armamento principal.'''
ship: 'Defensor TIE'
'TIE Shuttle':
name: "<NAME>"
text: '''<span class="card-restriction">Sólo TIE Bombardero.</span>%LINEBREAK%Tu barra de mejoras pierde todos los iconos de mejora %TORPEDO%, %MISSILE% y %BOMB% y gana 2 iconos de mejora %CREW%. No puedes equipar ninguna carta de Mejora %CREW% con un coste en puntos de escuadrón superior a 4.'''
ship: 'Bombardero TIE'
'Requiem':
text: '''%GOZANTIONLY%%LINEBREAK%When you deploy a ship, treat its pilot skill value as "8" until the end of the round.'''
'Vector':
text: '''%GOZANTIONLY%%LINEBREAK%After you execute a maneuver, you may deploy up to 4 attached ships (instead of 2).'''
'Suppressor':
text: '''%GOZANTIONLY%%LINEBREAK%Once per round, after you acquire a target lock, you may remove 1 focus, evade, or blue target lock token from that ship.'''
'Black One':
name: "<NAME>"
text: '''Después de que realices una acción de impulso o de tonel volado, puedes quitar 1 ficha de Blanco fijado enemiga de una nave aliada que tengas a alcance 1. Esta mejora no puede equiparse en naves con pilotos de Habilidad 6 o inferior.'''
ship: "T-70 Ala-X"
'Millennium Falcon (TFA)':
name: "<NAME> (TFA)"
text: '''Después de que ejecutes una maniobra de inclinación (%BANKLEFT% o %BANKRIGHT%) de velocidad 3, si no estás en contacto con otra nave y no estás bajo tensión, puedes recibir 1 ficha de Tensión para cambiar la orientación de tu nave 180°.'''
'Alliance Overhaul':
name: "Reacondicionado por la Alianza"
text: '''<span class="card-restriction">Sólo ARC-170.</span>%LINEBREAK%Cuando ataques con un armamento principal desde tu arco de fuego normal, puedes tirar 1 dado de ataque adicional. Cuando ataques desde tu arco de fuego auxiliar, puedes cambiar 1 de tus resultados %FOCUS% por 1 resultado %CRIT%.'''
'Special Ops Training':
ship: "Caza TIE/sf"
name: "Entrenamiento de operaciones especiales"
text: '''<span class="card-restriction">Sólo TIE/sf.</span>%LINEBREAK%Cuando ataques con un armamento principal desde tu arco de fuego normal, puedes tirar 1 dado adicional de ataque. Si decides no hacerlo, puedes realizar un ataque adicional desde tu arco de fuego aixiliar.'''
'Concord Dawn Protector':
name: "Protector de Concord Dawn"
ship: "Caza Estelar del Protectorado"
text: '''<span class="card-restriction">Sólo Caza estelar del Protectorado.</span>%LINEBREAK%Cuando te defiendas, si estás dentro del arco de fuego del atacante y a alcance 1 y el atacante está dentro de tu arco de fuego, añade 1 resultado %EVADE%.'''
'Shadow Caster':
name: "<NAME>"
ship: "Nave de persecución clase Lancero"
text: '''<span class="card-restriction">Sólo Nave de persecución clase Lancero</span>%LINEBREAK%Después de que efectúes un ataque que impacte, si el defensor está dentro de tu arco de fuego móvil y a alcance 1-2, puedes asignarle 1 ficha de Campo de tracción.'''
# Wave X
'''Sabine's Masterpiece''':
ship: "Caza TIE"
name: "O<NAME>est<NAME>"
text: '''<span class="card-restriction">Sólo Caza TIE.</span>%REBELONLY%%LINEBREAK%Tu barra de mejoras gana los iconos %CREW% y %ILLICIT%.'''
'''<NAME> Shuttle''':
ship: "Lanzadera clase Ípsilon"
name: "<NAME> <NAME>"
text: '''<span class="card-restriction">Sólo Lanzadera clase Ípsilon.</span>%LINEBREAK%Al final de la fase de Combate, elige una nave enemiga que tengas a alcance 1-2 y no esté bajo tensión. El jugador que la controla debe asignarle una ficha de Tensión o asignar una ficha de Tensión a otra d esus naves que esté situada a alcance 1-2 de ti.'''
'''Pivot Wing''':
name: "<NAME>"
ship: "Ala-U"
text: '''<span class="card-restriction">Sólo Ala-U.</span> %DUALCARD%%LINEBREAK%<strong>Cara A (Ataque):</strong> Tu Agilidad se incrementa en 1.%LINEBREAK%Después de que ejecutes una maniobra, puedes darle la vuelta a esta carta.%LINEBREAK%<strong>Cara B (Aterrizaje):</strong> Cuando reveles una maniobra (%STOP% 0), puedes cambiar la orientación de tu nave en 180°.%LINEBREAK%Después de que ejecutes una maniobra, puedes darle la vuelta a esta carta.'''
'''Adaptive Ailerons''':
name: "<NAME>"
ship: "Fustigador TIE"
text: '''<span class="card-restriction">Sólo Fustigador TIE.</span>%LINEBREAK%Inmediatamente antes de revelar tu selector de maniobras, si no estás bajo tensión, debes ejecutar una manibora blanca (%BANKLEFT% 1), (%STRAIGHT% 1) o (%BANKRIGHT% 1).'''
# C-ROC
'''Merchant One''':
name: "<NAME>"
ship: "Crucero C-ROC"
text: '''<span class="card-restriction">Sólo C-ROC Cruiser.</span>%LINEBREAK%Tu barra de mejoras gana 1 icono %CREW% adicional y 1 icono %TEAM% adicional y pierde 1 icono %CARGO%.'''
'''"Light Scyk" Interceptor''':
name: 'Interceptor "<NAME>"'
ship: "Interceptor M3-A"
text: '''<span class="card-restriction">Sólo Interceptor M3-A.</span>%LINEBREAK%Toda slas cartas de Daño que te inflijan se te asignan boca arriba. Puedes ejecutar todas las maniobras de inclinación (%BANKLEFT% o %BANKRIGHT%) como maniobras verdes. No puedes equiparte con mejoras de Modificación.s.'''
'''Insatiable Worrt''':
name: "<NAME>"
ship: "Crucero C-ROC"
text: '''Después de que realices la acción de recuperación, ganas 3 de energía.'''
'''Broken Horn''':
name: "<NAME>"
ship: "Crucero C-ROC"
text: '''Cuando te defiendas, si tienes asignada una ficha de Refuerzo, puedes añadir 1 resultado %EVADE% adicional. Si lo haces, tras defenderte, descarta tu ficha de Refuerzo.'''
'<NAME>':
name: "<NAME>"
ship: "Bombardero Scurrg H-6"
text: '''<span class="card-restriction">Sólo Bombarder Scurrg H-6.</span>%LINEBREAK%Tu barra de mejoras gana los iconos %SYSTEM% y %SALVAGEDASTROMECH% y pierde el icono %CREW%.%LINEBREAK%No puedes equiparte con cartas de mejora %SALVAGEDASTROMECH% que no sean únicas.'''
'Vaksai':
ship: "Caza Kihraxz"
text: '''<span class="card-restriction">Sólo Caza Kihraxz.</span>%LINEBREAK%El coste en puntos de escuadrón de cada una de tus mejoras equipadas se reduce en 1 (hast aun mínimo de 0).%LINEBREAK%Puedes equipar un máximo de 3 mejoras distintas de Modificación.'''
'StarViper Mk. II':
name: "<NAME>"
ship: "Víbora Estelar"
text: '''<span class="card-restriction">Sólo Víbora Estelar.</span>%LINEBREAK%Puedes equipar un máximo de 2 mejoras distintas de Título.%LINEBREAK%Cuando realices una acción de tonel volado <strong>debes</strong> utilizar la plantilla (%BANKLEFT% 1) o (%BANKRIGHT% 1) en vez de la plantilla (%STRAIGHT% 1).'''
'XG-1 Assault Configuration':
ship: "Ala Estelar clase Alfa"
name: "Configuración de asalto Xg-1"
text: '''<span class="card-restriction">Sólo Ala Estelar clase Alfa.</span>%LINEBREAK%Tu barra de mejoras gana 2 iconos %CANNON%.%LINEBREAK%Puedes efectuar ataques con sistemas de armamento secundario %CANNON% con un coste igual o inferior a 2 puntos de escuadrón incluso aunque tengas asignada una ficha de Armas bloqueadas.'''
'Enforcer':
name: "<NAME>"
ship: "Caza M12-L Kimogila"
text: '''<span class="card-restriction">Sólo Caza M12-L Kimogila.</span>%LINEBREAK%Después de que te defiendas, si el atacante está situado dentro de tu arco de fuego centrado, recibe 1 fciha de Tensión.'''
'Ghost (Phantom II)':
name: "<NAME> (<NAME>)"
text: '''<span class="card-restriction">Sólo VCX-100.</span>%LINEBREAK%Equipa la carta de Título <em>Fantasma II</em> a una Lanzadera clase <em>Sheathipede</em> aliada y acóplala a esta nave.%LINEBREAK%Después de que ejecutes una maniobra, puedes desplegar la nave que tienes acoplada desde los salientes de la parte trasera de tu peana.'''
'Phantom II':
name: "<NAME>"
ship: "Lanzadera clase Sheathipede"
text: '''Mientras estés acoplado, el <em>Espíritu</em> puede efectuar ataques con su armamento principal desde su arco de fuego especial.%LINEBREAK%Mientras estés acoplado, al final de la fase de Activación, el <em>Espíritu</em> puede efectuar una acción gratuita de coordinación.'''
'First Order Vanguard':
name: "<NAME>"
ship: "Silenciador TIE"
text: '''<span class="card-restriction">Sólo Silenciador TIE.</span>%LINEBREAK%Cuando ataques, si el defensor es la única nave que tienes dentro de tu arco de fuego a alcance 1-3, puedes volver a tirar 1 dado de ataque.%LINEBREAK%Cuando te defiendas, puedes descartar esta carta para volver a tirar todos tus dados de defensa.'''
'Os-1 Arsenal Loadout':
name: "Configuración de Arsenal Os-1"
ship: "Ala Estelar clase Alfa"
text: '''<span class="card-restriction">Sólo Ala Estelar clase Alfa.</span>%LINEBREAK%Tu barra de mejoras gana los iconos %TORPEDO% y %MISSILE%.%LINEBREAK%Puedes efectuar ataques con sistemas de armamento secundario %TORPEDO% y %MISSILE% contra naves que hayas fijado como blanco incluso aunque tengas asignada una ficha de Armas bloqueadas.'''
'Crossfire Formation':
name: "Formación de fuego cruzado"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando te defiendas, si hay por lo menos 1 otra nave aliada de la Reistencia situada a alcance 1-2 del atacante, puedes añadir 1 resultado %FOCUS% a tu tirada.'''
'Advanced Ailerons':
name: "Alerones avanzados"
ship: "Segador TIE"
text: '''<span class="card-restriction">Sólo Segador TIE.</span>%LINEBREAK%Tus maniobras (%BANKLEFT% 3) y (%BANKRIGHT% 3) se consideran blancas.%LINEBREAK%Inmediatamente antes de revelar tu selector de maniobras, si no estás bajo tensión, debes ejecutar una manibora blanca (%BANKLEFT% 1), (%STRAIGHT% 1) o (%BANKRIGHT% 1).'''
condition_translations =
'''I'll Show You the Dark Side''':
name: "Yo te mostraré el Lado Oscuro"
text: '''Cuando esta carta es asignada, si no está ya en juego, el jugador que la ha asignado busca en el mazo de Daño 1 carta de Daño que tenga el atributo <strong><em>Piloto</em></strong> y puede colocarla boca arriba sobre esta carta de Estado. Luego vuelve a barajar el mazo de Daño.%LINEBREAKCuando sufras daño crítico durante un ataque, en vez de eso recibes la carta de Daño boca arriba que has elegido.%LINEBREAK%Cuando no haya ninguna carta de Daño sobre esta carta de Estado, retírala.'''
'Suppressive Fire':
name: "Fuego de supresión"
text: '''Cuando ataques a una nave que no sea el "Capitán Rex", tira 1 dado de ataque menos.%LINEBREAK% Cuando declares un ataque que tenga como blanco al "Capitán Rex" o cuando el "Capitán Rex" sea destruido, retira esta carta.%LINEBREAK%Al final de la fase de Combate, si el "Capitán Rex" no ha efectuado un ataque en esta fase, retira esta carta.'''
'Fanatical Devotion':
name: "<NAME>"
text: '''Cuando te defiendas, no pudes gastar fichas de Concentración.%LINEBREAK%Cuando ataques, si gastas una ficha de Concentración parar cambiar todos los resultados %FOCUS% por resultados %HIT%, deja aparte el primer resultado %FOCUS% que has cambiado. El resultado %HIT% que has dejado aparte no puede ser anulado por dados de defensa, pero el defensor puede anular resultados %CRIT% antes que él.%LINEBREAK%Durante la fase Final, retira esta carta.'''
'A Debt to Pay':
name: "Una deuda por saldar"
text: '''Cuando ataques a una nave que tiene la carta de Mejora "Una cuenta pendiente", puedes cambiar 1 resultado %FOCUS% por un resultado %CRIT%.'''
'Shadowed':
name: "<NAME>"
text: '''Se considera que "Thweek" tiene el mismo valor de Habilidad que tu piloto tenía después de la preparación de la partida.%LINEBREAK%El valor de Habilidad de "Thweek" no cambia si el valor de Habilidad de tu piloto se modifica o eres destruido.'''
'Mimicked':
name: "<NAME>"
text: '''Se considera que "Thweek" tiene tu misma capacidad especial de piloto.%LINEBREAK%"Thweek" no puede utilizar tu capacidad especial de piloto para asignar una carta de Estado.%LINEBREAK%"Thweek" no pierde tu capacidad especial de piloto si eres destruido.'''
'Harpooned!':
name: "<NAME>¡<NAME>!"
text: '''Cuando seas impactado por un ataque, si hay al menos 1 resultad %CRIT% sin anular, toda otra nave que tengas a alcance 1 sufre 1 punto de daño. Luego descarta esta carta y recibe 1 carta de Daño boca abajo.%LINEBREAK%Cuando seas destruido, toda nave que tengas a alcance 1 sufre 1 punto de daño.%LINEBREAK%<strong>Acción:</strong> Descarta esta carta. Luego tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, sufres 1 punto de daño.'''
'Rattled':
name: "<NAME>"
text: '''Cuando sufras daño normal o daño crítico causado por una bomba, sufres 1 punto adicional de daño crítico. Luego, retira esta carta%LINEBREAK%<strong>Acción:</strong> Tira 1 dado de ataque. Si sacas %FOCUS% o %HIT%, retira esta carta.'''
'Scrambled':
name: "Sistemas interferidos"
text: '''Cuando ataques a una nave que tengas a alcance 1 y esté equipada con la mejora "Interferidor de sistemas de puntería", no puedes modificar tus dados de ataque.%LINEBREAK%Al final de la fase de Combate, retira esta carta.'''
'Optimized Prototype':
name: "Prototipo optimizado"
text: '''Tu valor de Escudos se incrementa en 1.%LINEBREAK%Una vez por ronda, cuando efectúes un ataque con tu armamento principal, puedes gastar 1 resultado de dado para retirar 1 ficha de Escudos del defensor.%LINEBREAK%Después de que efectúes un ataque con tu armamento principal, una nave aliada que tengas a alcance 1-2 y esté equipada con la carta de Mejora "<NAME>" puede fijar como blanco al defensor.'''
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations
| true | exportObj = exports ? this
exportObj.codeToLanguage ?= {}
exportObj.codeToLanguage.es = 'Español'
exportObj.translations ?= {}
# This is here mostly as a template for other languages.
exportObj.translations['Español'] =
action:
"Barrel Roll": "Tonel Volado"
"Boost": "Impulso"
"Evade": "Evadir"
"Focus": "Concentración"
"Target Lock": "Blanco Fijado"
"Recover": "Recuperar"
"Reinforce": "Reforzar"
"Jam": "Interferir"
"Coordinate": "Coordinar"
"Cloak": "Camuflaje"
slot:
"Astromech": "Droide Astromech"
"Bomb": "Bomba"
"Cannon": "Cañón"
"Crew": "Tripulación"
"Elite": "Élite"
"Missile": "Misiles"
"System": "Sistemas"
"Torpedo": "Torpedos"
"Turret": "Torreta"
"Cargo": "Carga"
"Hardpoint": "Hardpoint"
"Team": "Equipo"
"Illicit": "Ilícita"
"Salvaged Astromech": "Droide Astromech Remendado"
"Tech": "Tecnología"
sources: # needed?
"Core": "Caja Básica"
"A-Wing Expansion Pack": "Pack de Expansión Ala-A"
"B-Wing Expansion Pack": "Pack de Expansión Ala-B"
"X-Wing Expansion Pack": "Pack de Expansión Ala-X"
"Y-Wing Expansion Pack": "Pack de Expansión Ala-Y"
"Millennium Falcon Expansion Pack": "Pack de Expansión Halcón Milenario"
"HWK-290 Expansion Pack": "Pack de Expansión HWK-290"
"TIE Fighter Expansion Pack": "Pack de Expansión Caza TIE"
"TIE Interceptor Expansion Pack": "Pack de Expansión Interceptor TIE"
"TIE Bomber Expansion Pack": "Pack de Expansión Bombardero TIE"
"TIE Advanced Expansion Pack": "Pack de Expansión TIE Avanzado"
"Lambda-Class Shuttle Expansion Pack": "Pack de Expansión Lanzadera clase LAmbda"
"Slave I Expansion Pack": "Pack de Expansión Esclavo 1"
"Imperial Aces Expansion Pack": "Pack de Expansión Ases Imperiales"
"Rebel Transport Expansion Pack": "Pack de Expansión Transporte Rebelde"
"Z-95 Headhunter Expansion Pack": "Pack de Expansión Z-95 Cazacabezas"
"TIE Defender Expansion Pack": "Pack de Expansión Defensor TIE"
"E-Wing Expansion Pack": "Pack de Expansión Ala-E"
"TIE Phantom Expansion Pack": "Pack de Expansión TIE Fantasma"
"Tantive IV Expansion Pack": "Pack de Expansión Tantive IV"
"Rebel Aces Expansion Pack": "Pack de Expansión Ases Rebeldes"
"YT-2400 Freighter Expansion Pack": "Pack de Expansión Carguero YT-2400"
"VT-49 Decimator Expansion Pack": "Pack de Expansión VT-49 Diezmador"
"StarViper Expansion Pack": "Pack de Expansión Víbora Estelar"
"M3-A Interceptor Expansion Pack": "Pack de Expansión Interceptor M3-A"
"IG-2000 Expansion Pack": "Pack de Expansión IG-2000"
"Most Wanted Expansion Pack": "Pack de Expansión Los Más Buscados"
"Imperial Raider Expansion Pack": "Pack de Expansión Incursor Imperial"
"K-Wing Expansion Pack": "Pack de Expansión Ala-K"
"TIE Punisher Expansion Pack": "Pack de Expansión Castigador TIE"
"Kihraxz Fighter Expansion Pack": "Pack de Expansión Caza Kihraxz"
"Hound's Tooth Expansion Pack": "Pack de Expansión Diente de Perro"
"The Force Awakens Core Set": "Caja Básica El Despertar de la Fuerza"
"T-70 X-Wing Expansion Pack": "Pack de Expansión T-70 Ala-X"
"TIE/fo Fighter Expansion Pack": "Pack de Expansión Caza TIE/fo"
"Imperial Assault Carrier Expansion Pack": "Pack de Expansión Portacazas de Asalto Imperial"
"Ghost Expansion Pack": "Pack de Expansión Espíritu"
"Inquisitor's TIE Expansion Pack": "Pack de Expansión TIE del Inquisidor"
"Mist Hunter Expansion Pack": "Pack de Expansión Cazador de la Niebla"
"Punishing One Expansion Pack": "Pack de Expansión Castigadora"
"Imperial Veterans Expansion Pack": "Pack de Expansión Veteranos Imperiales"
"Protectorate Starfighter Expansion Pack": "Pack de Expansión Caza estelar del Protectorado"
"Shadow Caster Expansion Pack": "Pack de Expansión Sombra Alargada"
"Special Forces TIE Expansion Pack": "Pack de Expansión TIE de las Fuerzas Especiales"
"ARC-170 Expansion Pack": "Pack de Expansión ARC-170"
"U-Wing Expansion Pack": "Pack de Expansión Ala-U"
"TIE Striker Expansion Pack": "Pack de Expansión Fustigador TIE"
"Upsilon-class Shuttle Expansion Pack": "Pack de Expansión Lanzadera clase Ípsilon"
"Sabine's TIE Fighter Expansion Pack": "Pack de Expansión Caza TIE de Sabine"
"Quadjumper Expansion Pack": "Pack de Expansión Saltador Quad"
"C-ROC Cruiser Expansion Pack": "Pack de Expansión Crucero C-ROC"
"TIE Aggressor Expansion Pack": "Pack de Expansión Tie Agresor"
"Scurrg H-6 Bomber Expansion Pack": "Pack de Expansión Bombardero Scurrg H-6"
"Auzituck Gunship Expansion Pack": "Pack de Expansión Cañonera Auzituck"
"TIE Silencer Expansion Pack": "Pack de Expansión Silenciador TIE"
"Alpha-class Star Wing Expansion Pack": "Pack de Expansión Ala Estelar clase Alfa"
"Resistance Bomber Expansion Pack": "Pack de Expansión Bombardero de la Resistencia"
"Phantom II Expansion Pack": "Pack de Expansión Fantasma II"
"Kimogila Fighter Expansion Pack": "Pack de Expansión Caza M12-L Kimogila"
"Saw's Renegades Expansion Pack": "Pack de Expansión Renegados de Saw"
"TIE Reaper Expansion Pack": "Pack de Expansión Segador TIE"
ui:
shipSelectorPlaceholder: "Selecciona una nave"
pilotSelectorPlaceholder: "Selecciona un piloto"
upgradePlaceholder: (translator, language, slot) ->
switch slot
when 'Elite'
"Sin Talento de Élite"
when 'Astromech'
"Sin Droide Astromecánico"
when 'Illicit'
"Sin Mejora Ilícita"
when 'Salvaged Astromech'
"Sin Droide Astromech Remendado"
else
"Sin Mejora de #{translator language, 'slot', slot}"
modificationPlaceholder: "Sin Modificación"
titlePlaceholder: "Sin Título"
upgradeHeader: (translator, language, slot) ->
switch slot
when 'Elite'
"Talento de Élite"
when 'Astromech'
"Droide Astromecánico"
when 'Illicit'
"Mejora Ilícita"
when 'Salvaged Astromech'
"Droide Astromech Remendado"
else
"Mejora de #{translator language, 'slot', slot}"
unreleased: "inédito"
epic: "épico"
byCSSSelector:
# Warnings
'.unreleased-content-used .translated': 'This squad uses unreleased content!'
'.epic-content-used .translated': 'This squad uses Epic content!'
'.illegal-epic-too-many-small-ships .translated': 'You may not field more than 12 of the same type Small ship!'
'.illegal-epic-too-many-large-ships .translated': 'You may not field more than 6 of the same type Large ship!'
'.collection-invalid .translated': 'You cannot field this list with your collection!'
# Type selector
'.game-type-selector option[value="standard"]': 'Standard'
'.game-type-selector option[value="custom"]': 'Custom'
'.game-type-selector option[value="epic"]': 'Epic'
'.game-type-selector option[value="team-epic"]': 'Team Epic'
'.xwing-card-browser .translate.sort-cards-by': 'Ordenar cartas por'
'.xwing-card-browser option[value="name"]': 'Nombre'
'.xwing-card-browser option[value="source"]': 'Fuente'
'.xwing-card-browser option[value="type-by-points"]': 'Tipo (por Puntos)'
'.xwing-card-browser option[value="type-by-name"]': 'Tipo (por Nombre)'
'.xwing-card-browser .translate.select-a-card': 'Selecciona una carta del listado de la izquierda.'
# Info well
'.info-well .info-ship td.info-header': 'Nave'
'.info-well .info-skill td.info-header': 'Habilidad'
'.info-well .info-actions td.info-header': 'Acciones'
'.info-well .info-upgrades td.info-header': 'Mejoras'
'.info-well .info-range td.info-header': 'Alcance'
# Squadron edit buttons
'.clear-squad' : 'Nuevo Escuadron'
'.save-list' : 'Grabar'
'.save-list-as' : 'Grabar como...'
'.delete-list' : 'Eliminar'
'.backend-list-my-squads' : 'Cargar Escuadron'
'.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i> Imprimir/Ver como </span>Text'
'.randomize' : 'Aleatorio!'
'.randomize-options' : 'Opciones de aleatoriedad…'
'.notes-container > span' : 'Squad Notes'
# Print/View modal
'.bbcode-list' : 'Copia el BBCode de debajo y pegalo en el post de tu foro.<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.html-list' : '<textarea></textarea><button class="btn btn-copy">Copia</button>'
'.vertical-space-checkbox' : """Añade espacio para cartas de daño/mejora cuando imprima. <input type="checkbox" class="toggle-vertical-space" />"""
'.color-print-checkbox' : """Imprima en color. <input type="checkbox" class="toggle-color-print" />"""
'.print-list' : '<i class="fa fa-print"></i> Imprimir'
# Randomizer options
'.do-randomize' : 'Genera Aleatoriamente!'
# Top tab bar
'#empireTab' : 'Imperio Galactico'
'#rebelTab' : 'Alianza Rebelde'
'#scumTab' : 'Escoria y Villanos'
'#browserTab' : 'Explorador de Cartas'
'#aboutTab' : 'Acerca de'
singular:
'pilots': 'Piloto'
'modifications': 'Modificación'
'titles': 'Título'
types:
'Pilot': 'Piloto'
'Modification': 'Modificación'
'Title': 'Título'
exportObj.cardLoaders ?= {}
exportObj.cardLoaders['Español'] = () ->
exportObj.cardLanguage = 'Español'
# Assumes cards-common has been loaded
basic_cards = exportObj.basicCardData()
exportObj.canonicalizeShipNames basic_cards
exportObj.ships = basic_cards.ships
# ship translations
exportObj.renameShip 'Lambda-Class Shuttle', 'Lanzadera clase Lambda'
exportObj.renameShip 'TIE Advanced', 'TIE Avanzado'
exportObj.renameShip 'TIE Bomber', 'Bombardero TIE'
exportObj.renameShip 'TIE Fighter', 'Caza TIE'
exportObj.renameShip 'TIE Interceptor', 'Interceptor TIE'
exportObj.renameShip 'TIE Phantom', 'TIE Fantasma'
exportObj.renameShip 'TIE Defender', 'Defensor TIE'
exportObj.renameShip 'TIE Punisher', 'Castigador TIE'
exportObj.renameShip 'TIE Advanced Prototype', 'Prototipo de TIE Avanzado'
exportObj.renameShip 'VT-49 Decimator', 'VT-49 Diezmador'
exportObj.renameShip 'TIE/fo Fighter', 'Caza TIE/fo'
exportObj.renameShip 'TIE/sf Fighter', 'Caza TIE/sf'
exportObj.renameShip 'TIE Striker', 'Fustigador TIE'
exportObj.renameShip 'Upsilon-class Shuttle', 'Lanzadera clase Ípsilon'
exportObj.renameShip 'TIE Aggressor', 'TIE Agresor'
exportObj.renameShip 'TIE Silencer', 'Silenciador TIE'
exportObj.renameShip 'Alpha-class Star Wing', 'Ala Estelar clase Alfa'
exportObj.renameShip 'TIE Reaper', 'Segador TIE'
exportObj.renameShip 'A-Wing', 'Ala-A'
exportObj.renameShip 'B-Wing', 'Ala-B'
exportObj.renameShip 'E-Wing', 'Ala-E'
exportObj.renameShip 'X-Wing', 'Ala-X'
exportObj.renameShip 'Y-Wing', 'Ala-Y'
exportObj.renameShip 'K-Wing', 'Ala-K'
exportObj.renameShip 'Z-95 Headhunter', 'Z-95 Cazacabezas'
exportObj.renameShip 'Attack Shuttle', 'Lanzadera de Ataque'
exportObj.renameShip 'CR90 Corvette (Aft)', 'Corbeta CR90 (Popa)'
exportObj.renameShip 'CR90 Corvette (Fore)', 'Corbeta CR90 (Proa)'
exportObj.renameShip 'GR-75 Medium Transport', 'Transporte mediano GR-75'
exportObj.renameShip 'T-70 X-Wing', 'T-70 Ala-X'
exportObj.renameShip 'U-Wing', 'Ala-U'
exportObj.renameShip 'Auzituck Gunship', 'Cañonera Auzituck'
exportObj.renameShip 'B/SF-17 Bomber', 'Bombardero B/SF-17'
exportObj.renameShip 'Sheathipede-class Shuttle', 'Lanzadera clase Sheathipede'
exportObj.renameShip 'M3-A Interceptor', 'Interceptor M3-A'
exportObj.renameShip 'StarViper', 'Víbora Estelar'
exportObj.renameShip 'Aggressor', 'Agresor'
exportObj.renameShip 'Kihraxz Fighter', 'Caza Kihraxz'
exportObj.renameShip 'G-1A Starfighter', 'Caza Estelar G-1A'
exportObj.renameShip 'JumpMaster 5000', 'Saltador Maestro 5000'
exportObj.renameShip 'Protectorate Starfighter', 'Caza Estelar del Protectorado'
exportObj.renameShip 'Lancer-class Pursuit Craft', 'Nave de persecución clase Lancero'
exportObj.renameShip 'Quadjumper', 'Saltador Quad'
exportObj.renameShip 'C-ROC Cruiser', 'Crucero C-ROC'
exportObj.renameShip 'Scurrg H-6 Bomber', 'BPI:NAME:<NAME>END_PI H-6'
exportObj.renameShip 'M12-L Kimogila Fighter', 'Caza M12-L Kimogila'
pilot_translations =
"Wedge Antilles":
text: """Cuando ataques, la Agilidad del piloto se reduce en 1 (hasta un mínimo de 0)."""
ship: "Ala-X"
"PI:NAME:<NAME>END_PI":
text: """Después de gastar una ficha de Concentración, en vez de descartarla puedes asignar esa ficha a cualquier otra nave aliada que tengas a alcance 1-2."""
ship: "Ala-X"
"Red Squadron Pilot":
name: "Piloto del escuadrón Rojo"
ship: "Ala-X"
"PI:NAME:<NAME>END_PI Pilot":
name: "PI:NAME:<NAME>END_PI"
ship: "Ala-X"
"Biggs Darklighter":
text: """Las demás naves aliadas que tengas a alcance 1 no pueden ser seleccionadas como objetivo de ataques si en vez de eso el atacante pudiese seleccionarte a tí como objetivo."""
ship: "Ala-X"
"PI:NAME:<NAME>END_PIwalker":
text: """Cuando te defiendas en combate puedes cambiar 1 de tus resultados %FOCUS% por un resultado %EVADE%."""
ship: "Ala-X"
"Gray Squadron Pilot":
name: "Piloto del escuadrón Gris"
ship: "Ala-Y"
'"Dutch" Vander':
text: """Después de que fijes un blanco, elige otra nave aliada que tengas a alcance 1-2. La nave elegida podrá fijar un blanco inmediatamente."""
ship: "Ala-Y"
"PI:NAME:<NAME>END_PI":
text: """Cuando ataques a alcance 2-3, puedes volver a lanzar cualesquier dados en los que hayas sacado caras vacías."""
ship: "Ala-Y"
"Gold Squadron Pilot":
name: "Piloto del escuadrón Oro"
ship: "Ala-Y"
"Academy Pilot":
name: "Piloto de la Academia"
ship: "Caza TIE"
"Obsidian Squadron Pilot":
name: "Piloto del escuadrón Obsidiana"
ship: "Caza TIE"
"Black Squadron Pilot":
name: "Piloto del escuadrón Negro"
ship: "Caza TIE"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Cuando ataques a alcance 1, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%"""
ship: "Caza TIE"
'"Night Beast"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Después de que ejecutes una maniobra verde, puedes realizar una acción gratuita de Concentración"""
ship: "Caza TIE"
'"Backstabber"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Cuando ataques desde fuera del arco de fuego del defensor, tira 1 dado de ataque adicional."""
ship: "Caza TIE"
'"Dark PI:NAME:<NAME>END_PIse"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Cuando te defiendas en combate, las naves que te ataquen no podrán gastar fichas de Concentración ni volver a tirar dados de ataque."""
ship: "Caza TIE"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Si atacas a alcance 1, tira 1 dado de ataque adicional."""
ship: "Caza TIE"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Cuando otra nave aliada que tengas a alcance 1 ataque con su armamento principal, podrá volver a tirar 1 dado de ataque."""
ship: "Caza TIE"
"Tempest Squadron Pilot":
name: "Piloto del escuadrón Tempestad"
ship: "TIE Avanzado"
"Storm Squadron Pilot":
name: "Piloto del escuadrón Tormenta"
ship: "TIE Avanzado"
"PI:NAME:<NAME>END_PI":
text: """Cuando tu ataque inflija una carta de Daño boca arriba al defensor, en vez de eso roba 3 cartas de Daño, elige 1 de ellas a tu elección y luego descarta las otras."""
ship: "TIE Avanzado"
"PI:NAME:<NAME>END_PI":
text: """Puedes llevar a cabo dos acciones durante tu paso de acción."""
ship: "TIE Avanzado"
"Alpha Squadron Pilot":
name: "Piloto del escuadrón Alfa"
ship: "Interceptor TIE"
"Avenger Squadron Pilot":
name: "Piloto del escuadrón Vengador"
ship: "Interceptor TIE"
"Saber Squadron Pilot":
name: "Piloto del escuadrón Sable"
ship: "Interceptor TIE"
"\"Fel's Wrath\"":
name: '"PI:NAME:<NAME>END_PI"'
ship: "Interceptor TIE"
text: """Cuando tengas asignadas tantas cartas de Daño como tu Casco o más, no serás destruido hasta el final de la fase de Combate."""
"PI:NAME:<NAME>END_PI":
ship: "Interceptor TIE"
text: """Después de que efectúes un ataque, puedes llevar a cabo una acción gratuita de impulso o tonel volado."""
"PI:NAME:<NAME>END_PI":
ship: "Interceptor TIE"
text: """Cuando recibas una ficha de Tensión, puedes asignar 1 ficha de Concentración a tu nave."""
"PI:NAME:<NAME>END_PI":
text: """Puedes realizar acciones incluso aunque tengas fichas de Tensión."""
ship: "Ala-A"
"Arvel Crynyd":
text: """Puedes designar como objetivo de tu ataque a una nave enemiga que esté dentro de tu arco de ataque y en contacto contigo."""
ship: "Ala-A"
"Green Squadron Pilot":
name: "Piloto del escuadrón Verde"
ship: "Ala-A"
"Prototype Pilot":
name: "Piloto de pruebas"
ship: "Ala-A"
"Outer Rim Smuggler":
name: "Contrabandista del Borde Exterior"
"ChePI:NAME:<NAME>END_PI":
text: """Cuando recibas una carta de Daño boca arriba, ponla boca abajo inmediatamente sin resolver su texto de reglas."""
"PI:NAME:<NAME>END_PI":
text: """Después de que ejecutes una maniobra verde, elige otra nave aliada que tengas a alcance 1. Esa nave podrá realizar una acción gratuita de las indicadas en su barra de acciones."""
"PI:NAME:<NAME>END_PI":
text: """Cuando ataques, puedes volver a tirar todos tus dados. Si decides hacerlo, debes volver a tirar tantos como te sea posible."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI":
text: """Cuando ataques, el defensor recibe 1 ficha de Tensión si anula al menos 1 resultado %CRIT%."""
"PI:NAME:<NAME>END_PI":
text: """Cuando realices una maniobra de inclinación (%BANKLEFT% o %BANKRIGHT%), puedes girar tu selector de maniobras para escoger la otra maniobra de inclinación de la misma velocidad."""
"PI:NAME:<NAME>END_PI":
text: """Cuando ataques con un armamento secundario, puedes volver a tirar 1 dado de ataque."""
"Ten Numb":
text: """Cuando atacas, 1 de tus resultados %CRIT% no puede ser anulado por los dados de defensa."""
ship: "Ala-B"
"Ibtisam":
text: """Cuando atacas o te defiendes, si tienes al menos 1 ficha de Tensión, puedes volver a tirar 1 de tus dados."""
ship: "Ala-B"
"Dagger Squadron Pilot":
name: "Piloto del escuadrón Daga"
ship: "Ala-B"
"Blue Squadron Pilot":
name: "Piloto del escuadrón Azul"
ship: "Ala-B"
"Rebel Operative":
name: "PI:NAME:<NAME>END_PI"
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
text: """Al comienzo de la fase de Combate, elige otra nave aliada que tengas a alcance 1-3. Hasta el final de la fase, se considera que el piloto de esa nave tiene habilidad 12."""
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
text: """Al comienzo de la fase de Combate, puedes asignar 1 de tus fichas de Concentración a otra nave aliada que tengas a alcance 1-3."""
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
text: """Cuando otra nave aliada que tengas a alcance 1-3 efectúe un ataque, si no tienes fichas de Tensión puedes recibir 1 ficha de Tensión para que esa nave tire 1 dado de ataque adicional."""
ship: "HWK-290"
"Scimitar Squadron Pilot":
name: "Piloto del escuadrón Cimitarra"
ship: "Bombardero TIE"
"Gamma Squadron Pilot":
name: "Piloto del escuadrón Gamma"
ship: "Bombardero TIE"
"Gamma Squadron Veteran":
name: "PI:NAME:<NAME>END_PI escuadrón PI:NAME:<NAME>END_PI"
ship: "Bombardero TIE"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero TIE"
text: """Cuando otra nave aliada que tengas a alcance 1 ataque con un sistema de armamento secundario, puede volver a tirar un máximo de 2 dados de ataque."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero TIE"
text: """Cuando atacas con un sistema de armamento secundario, puedes incrementar o reducir en 1 el alcance del arma (hasta un límite de alcance comprendido entre 1 y 3)."""
"Omicron Group Pilot":
name: "PiPI:NAME:<NAME>END_PIto del grupo ÓPI:NAME:<NAME>END_PI"
ship: "Lanzadera clase Lambda"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando una nave enemiga fije un blanco, deberá fijar tu nave como blanco (si es posible)."""
ship: "Lanzadera clase Lambda"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al comienzo de la fase de Combate, puedes asignar 1 de tus fichas azules de Blanco Fijado a una nave aliada que tengas a alcance 1 si no tiene ya una ficha azul de Blanco Fijado."""
ship: "Lanzadera clase Lambda"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando otra nave aliada que tengas a alcance 1-2 vaya a recibir una ficha de Tensión, si tienes 2 fichas de Tensión o menos puedes recibirla tú en su lugar."""
ship: "Lanzadera clase Lambda"
"PI:NAME:<NAME>END_PI":
ship: "Interceptor TIE"
text: """Cuando realices una acción de tonel volado, puedes recibir 1 ficha de Tensión para utilizar la plantilla (%BANKLEFT% 1) o la de (%BANKRIGHT% 1) en vez de la plantilla de (%STRAIGHT% 1)."""
"Royal Guard Pilot":
name: "PI:NAME:<NAME>END_PI la GuardPI:NAME:<NAME>END_PI"
ship: "Interceptor TIE"
"PI:NAME:<NAME>END_PI":
ship: "Interceptor TIE"
text: """Cuando reveles una maniobra %UTURN%, puedes ejecutarla como si su velocidad fuese de 1, 3 ó 5."""
"PI:NAME:<NAME>END_PI":
ship: "Interceptor TIE"
text: """Cuando ataques desde alcance 2-3, puedes gastar 1 ficha de Evasión para añadir 1 resultado %HIT% a tu tirada."""
"PI:NAME:<NAME>END_PI":
ship: "Interceptor TIE"
text: """Las naves enemigas que tengas a alcance 1 no pueden realizar acciones de Concentración o Evasión, y tampoco pueden gastar fichas de Concentración ni de Evasión."""
"GR-75 Medium Transport":
name: "Transporte mediano GR-75"
ship: "Transporte mediano GR-75"
"Bandit Squadron Pilot":
name: "Piloto del escuadrón BPI:NAME:<NAME>END_PIo"
ship: "Z-95 Cazacabezas"
"Tala Squadron Pilot":
name: "Piloto del escuadrón Tala"
ship: "Z-95 Cazacabezas"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques, el defensor es alcanzado por tu ataque, incluso aunque no sufra ningún daño."""
ship: "Z-95 Cazacabezas"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Después de que realices un ataque, puedes elegir otra nave aliada a alcance 1. Esa nave puede llevar a cabo 1 acción gratuita."""
ship: "Z-95 Cazacabezas"
"Delta Squadron Pilot":
name: "Piloto del escuadrón Delta"
ship: "Defensor TIE"
"Onyx Squadron Pilot":
name: "Piloto del escuadrón Ónice"
ship: "Defensor TIE"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques, inmediatamente después de tirar los dados de ataque puedes fijar al defensor como blanco si éste ya tiene asignada una ficha de Blanco Fijado."""
ship: "Defensor TIE"
"PI:NAME:<NAME>END_PI":
text: """Después de que efectúes un ataque que inflinja al menos 1 carta de Daño al defensor, puedes gastar 1 ficha de Concentración para poner esas cartas boca arriba."""
ship: "Defensor TIE"
"Knave Squadron Pilot":
name: "Piloto del escuadrón Canalla"
ship: "Ala-E"
"Blackmoon Squadron Pilot":
name: "Piloto del escuadrón LPI:NAME:<NAME>END_PI"
ship: "Ala-E"
"PI:NAME:<NAME>END_PI":
text: """Cuando una nave neemiga situada dentro de tu arco de fuego a alcance 1-3 se defienda, el atacante puede cambiar 1 de sus resultados %HIT% por 1 resultado %CRIT%."""
ship: "Ala-E"
"PI:NAME:<NAME>END_PI":
text: """Puedes efectuar 1 ataque al comienzo de la fase Final, pero si lo haces no podrás atacar en la ronda siguiente."""
ship: "Ala-E"
"Sigma Squadron Pilot":
name: "Piloto del escuadrón PI:NAME:<NAME>END_PI"
ship: "TIE Fantasma"
"Shadow Squadron Pilot":
name: "Piloto del escuadrón Sombra"
ship: "TIE Fantasma"
'"Echo"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Cuando desactives tu camuflaje, debes usar la plantilla de maniobra (%BANKLEFT% 2) o la de (%BANKRIGHT% 2) en lugar de la plantilla (%STRAIGHT% 2)."""
ship: "TIE Fantasma"
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Después de que efectúes un ataque que impacte, puedes asignar una ficha de Concentración a tu nave."""
ship: "TIE Fantasma"
"CR90 Corvette (Fore)":
name: "PI:NAME:<NAME>END_PIbeta CR90 (Proa)"
ship: "Corbeta CR90 (Proa)"
text: """Cuando ataques con tu armamento principal, puedes gastar 1 de Energía para tirar 1 dado de ataque adicional."""
"CR90 Corvette (Aft)":
name: "PI:NAME:<NAME>END_PI CR90 (Popa)"
ship: "Corbeta CR90 (Popa)"
"PI:NAME:<NAME>END_PI":
text: """Después de que efectúes un ataque, puedes eliminar 1 ficha de Concentración, Evasión o Blanco Fijado (azul) del defensor."""
ship: "Ala-X"
"PI:NAME:<NAME>END_PI":
text: """Cuando recibas una ficha de Tensión, puedes descartarla y tirar 1 dado de ataque. Si sacas %HIT%, esta nave recibe 1 carta de Daño boca abajo."""
ship: "Ala-X"
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
text: """Cuando fijes un blanco o gastes una ficha de Blanco Fijado, puedes quitar 1 ficha de Tensión de tu nave."""
ship: "Ala-X"
"PI:NAME:<NAME>END_PI":
text: """Cuando una nave enemiga te declare como objetivo de un ataque, puedes fijar esa nave como blanco."""
ship: "Ala-X"
"PI:NAME:<NAME>END_PI":
text: """Después de que realices una acción de Concentración o te asignen una ficha de Concentración, puedes efectuar una acción gratuita de impulso o tonel volado."""
ship: "Ala-A"
"PI:NAME:<NAME>END_PI":
text: """Mientras te encuentres a alcance 1 de al menos 1 nave enemiga, tu Agilidad aumenta en 1."""
ship: "Ala-A"
"PI:NAME:<NAME>END_PI":
text: """Cuando ataques, puedes quitarte 1 ficha de Tensión para cambiar todos tus resultados %FOCUS% por %HIT%."""
ship: "Ala-B"
"PI:NAME:<NAME>END_PI":
text: """Puedes efectuar ataques con armamentos secundarios %TORPEDO% contra naves enemigas fuera de tu arco de fuego."""
ship: "Ala-B"
# "CR90 Corvette (Crippled Aft)":
# name: "CR90 Corvette (Crippled Aft)"
# ship: "Corbeta CR90 (Popa)"
# text: """No puedes seleccionar ni ejecutar maniobras (%STRAIGHT% 4), (%BANKLEFT% 2), o (%BANKRIGHT% 2)."""
# "CR90 Corvette (Crippled Fore)":
# name: "CR90 Corvette (Crippled Fore)"
# ship: "Corbeta CR90 (Proa)"
"Wild Space Fringer":
name: "Fronterizo del Espacio Salvaje"
ship: "YT-2400"
"Dash Rendar":
text: """Puedes ignorar obstáculos durante la fase de Activación y al realizar acciones."""
'"Leebo"':
text: """Cuando recibas una carta de Daño boca arriba, roba 1 carta de Daño adicional, resuelve 1 de ellas a tu elección y descarta la otra."""
"PI:NAME:<NAME>END_PI":
text: """Si efectúas un ataque con un armamento principal contra una nave que tenga fichas de Tensión, tiras 1 dado de ataque adicional."""
"Patrol Leader":
name: "PI:NAME:<NAME>END_PI"
ship: "VT-49 Diezmador"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando atacas a alcance 1-2, puedes cambiar 1 de tus resultados de %FOCUS% por un resultado %CRIT%."""
ship: "VT-49 Diezmador"
"PI:NAME:<NAME>END_PI":
ship: "VT-49 Diezmador"
name: "PI:NAME:<NAME>END_PI"
text: """Si no te quedan escudos y tienes asignada al menos 1 carta de Daño, tu Agilidad aumenta en 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Después de ejecutar un maniobra, toda nave enemiga con la que estés en contacto sufre 1 daño."""
ship: "VT-49 Diezmador"
"Black Sun Enforcer":
name: "Ejecutor del Sol Negro"
ship: "Víbora Estelar"
"Black Sun Vigo":
name: "Vigo del Sol Negro"
ship: "Víbora Estelar"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando te defiendas, una nave aliada que tengas a alcance 1 puede sufrir en tu lugar 1 resultado %HIT% o %CRIT% no anulado."""
ship: "Víbora Estelar"
"PI:NAME:<NAME>END_PI":
text: """Al comienzo de la fase de Combate, si tienes alguna nave enemiga a alcance 1 puedes asignar 1 ficha de Concentración a tu nave."""
ship: "Víbora Estelar"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Interceptor M3-A"
"Tansarii Point Veteran":
name: "PI:NAME:<NAME>END_PI"
ship: "Interceptor M3-A"
"PI:NAME:<NAME>END_PI":
text: """Cuando otra nave aliada situada a alcance 1 se defienda, puede volver a tirar 1 dado de defensa."""
ship: "Interceptor M3-A"
"PI:NAME:<NAME>END_PI":
text: """Después de que te hayas defendido de un ataque, si el ataque no impactó, puedes asignar 1 ficha de Evasión a tu nave."""
ship: "Interceptor M3-A"
"IG-88A":
text: """Después de que efectúes un ataque que destruya al defensor, puedes recuperar 1 ficha de Escudos."""
ship: "Agresor"
"IG-88B":
text: """Una vez por ronda, después de que efectúes un ataque y lo falles, puedes efectuar un ataque con un sistema de armamento secundario %CANNON% que tengas equipado."""
ship: "Agresor"
"IG-88C":
text: """Después de que realices una acción de impulso, puedes llevar a cabo una acción gratuita de Evasión."""
ship: "Agresor"
"IG-88D":
text: """Puedes ejecutar la maniobra (%SLOOPLEFT% 3) o (%SLOOPRIGHT% 3) utilizando la plantilla (%TURNLEFT% 3) o (%TURNRIGHT% 3) correspondiente."""
ship: "Agresor"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI (Scum)":
text: """Cuando ataques o te defiendas, puedes volver a tirar 1 de tus dados por cada nave enemiga que tengas a alcance 1."""
"PI:NAME:<NAME>END_PI (Scum)":
text: """Cuando ataques una nave que esté dentro de tu arco de fuego auxiliar, tira 1 dado de ataque adicional."""
"PI:NAME:<NAME>END_PI":
text: """Cuando sueltes una bomba, puedes utilizar la plantilla de maniobra [%TURNLEFT% 3], [%STRAIGHT% 3] o [%TURNRIGHT% 3] en vez de la plantilla de [%STRAIGHT% 1]."""
"PI:NAME:<NAME>END_PI":
ship: "Ala-Y"
text: """Cuando ataques una nave que esté fuera de tu arco de fuego, tira 1 dado de ataque adicional."""
"PI:NAME:<NAME>END_PI":
ship: "Ala-Y"
text: """Después de gastar una ficha de Blanco Fijado, puedes recibir 1 ficha de Tensión para fijar un blanco."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Ala-Y"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Ala-Y"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
text: """Cuando una nave enemiga a alcance 1-3 reciba como mínimo 1 ficha de iones, si no tienes fichas de Tensión puedes recibir 1 ficha de Tensión para que esa nave sufra 1 de daño."""
ship: "HWK-290"
"PI:NAME:<NAME>END_PI":
text: """Al comienzo de la fase de Combate, puedes quitar 1 ficha de Concentración o Evasión de una nave enemiga a alcance 1-2 y asignar esa ficha a tu nave."""
"PI:NAME:<NAME>END_PI":
text: """Al final de la fase de Activación, elige 1 nave enemiga a alcance 1-2. Hasta el final de la fase de Combate, se considera que el piloto de esa nave tiene Habilidad 0."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Z-95 Cazacabezas"
"Black PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Z-95 Cazacabezas"
"PI:NAME:<NAME>END_PI":
text: """Cuando ataques, si no tienes ninguna otra nave aliada a alcance 1-2, tira 1 dado de ataque adicional."""
ship: "Z-95 Cazacabezas"
"PI:NAME:<NAME>END_PI":
text: """Al comienzo de la fase de Combate, puedes quitar 1 ficha de Concentración o Evasión de otra nave aliada que tengas a alcance 1-2 y asignar esa ficha a tu nave."""
ship: "Z-95 Cazacabezas"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE Avanzado"
text: """Al comienzo de la fase de Combate, puedes fijar como blanco una nave enemiga que tengas a alcance 1."""
"PI:NAME:<NAME>END_PI":
ship: "TIE Avanzado"
text: """Cuando reveles tu maniobra, puedes incrementar o reducir en 1 la velocidad de la maniobra (hasta un mínimo de 1)."""
"PI:NAME:<NAME>END_PI":
ship: "TIE Avanzado"
text: """Las naves enemigas que tengas a alcance 1 no pueden aplicar su modificador al combate por alcance cuando ataquen."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "TIE Avanzado"
text: """Al comienzo de la fase Final, puedes gastar una de tus fichas de Blanco fijado asignadas a una nave enemiga para seleccionar al azar y poner boca arriba 1 carta de Daño que esa nave tenga asignada boca abajo."""
"PI:NAME:<NAME>END_PI":
text: """Cuando una nave aliada declare un ataque, puedes gastar una ficha de Blanco Fijado que hayas asignado al defensor para reducir su Agilidad en 1 contra el ataque declarado."""
"PI:NAME:<NAME>END_PI":
ship: 'Ala-K'
text: """Una vez por ronda, cuando ataques, puedes elegir entre gastar 1 de Escudos para tirar 1 dado de ataque adicional <strong>o bien</strong> tirar 1 dado de ataque menos para recuperar 1 de Escudos."""
"PI:NAME:<NAME>END_PI":
ship: 'Ala-K'
text: """Cuando otra nave aliada que tengas a alcance 1-2 esté atacando, puede usar tus fichas de Concentración."""
"Guardian Squadron Pilot":
name: "PiPI:NAME:<NAME>END_PIto del Escuadrón Guardián"
ship: 'Ala-K'
"Warden Squadron Pilot":
name: "Piloto del Escuadrón Custodio"
ship: 'Ala-K'
'"Redline"':
name: '"PI:NAME:<NAME>END_PI"'
ship: 'Castigador TIE'
text: """Puedes mantener 2 blancos fijados sobre una misma nave. Cuando fijes un blanco, puedes fijar la misma nave como blanco por segunda vez."""
'"Deathrain"':
name: '"PI:NAME:<NAME>END_PI"'
ship: 'Castigador TIE'
text: """Cuando sueltes una bomba, puedes usar los salientes frontales de la peana de tu nave. Puedes realizar una acción gratuita de tonel volado después de soltar una bomba."""
'Black Eight Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: 'Castigador TIE'
'Cutlass Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: 'Castigador TIE'
"Moralo Eval":
text: """Puedes efectuar ataques con sistemas de armamento secundarios %CANNON% contra naves que estén dentro de tu arco de fuego auxiliar."""
'Gozanti-class Cruiser':
text: """After you execute a maneuver, you may deploy up to 2 attached ships."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza TIE"
text: """Cuando ataques a un defensor que tiene 1 o más cartas de Daño, tira 1 dado de ataque adicional."""
"The InPI:NAME:<NAME>END_PIitor":
name: "PI:NAME:<NAME>END_PI"
ship: "Prototipo de TIE Avanzado"
text: """Cuando ataques con tu armamento principal a alcance 2-3, el alcance del ataque se considera 1."""
"PI:NAME:<NAME>END_PI":
ship: "Caza Estelar G-1A"
text: """Cuando ataques, puedes tirar 1 dado de ataque adicional. Si decides hacerlo, el defensor tira 1 dado de defensa adicional."""
"RPI:NAME:<NAME>END_PIless PI:NAME:<NAME>END_PIelancer":
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Estelar G-1A"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Estelar G-1A"
"PI:NAME:<NAME>END_PI":
ship: "Saltador Maestro 5000"
text: """Una vez por ronda, después de que te defiendas, si el atacante está dentro de tu arco de fuego, puedes efectuar un ataque contra esa nave."""
"Talonbane Cobra":
ship: "Caza Kihraxz"
text: """Cuando ataques o te defiendas, duplica el efecto de tus bonificaciones al combate por alcance."""
"GrPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Kihraxz"
text: """Cuando te defiendas, tira 1 dado de defensa adicional si el atacante está situado dentro de tu arco de fuego."""
"Black Sun Ace":
name: "As del Sol Negro"
ship: "Caza Kihraxz"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Kihraxz"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "YV-666"
"PI:NAME:<NAME>END_PI":
ship: "YV-666"
text: """Cuando realices un ataque con éxito, antes de inflingir el daño puedes anular 1 de tus resultados %CRIT% para añadir 2 resultados %HIT%."""
# T-70
"PI:NAME:<NAME>END_PI":
ship: "T-70 Ala-X"
text: """Cuando ataques o te defiendas, si tienes una ficha de Concentración, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%."""
'"Blue Ace"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "T-70 Ala-X"
text: """Cuando realices una acción de impulso, puedes utilizar la plantilla de maniobra (%TURNLEFT% 1) o (%TURNRIGHT% 1)."""
"Red Squadron Veteran":
name: "PI:NAME:<NAME>END_PI"
ship: "T-70 Ala-X"
"Blue Squadron Novice":
name: "Novato del Esc. Azul"
ship: "T-70 Ala-X"
'"Red Ace"':
name: "PI:NAME:<NAME>END_PI"
ship: "T-70 Ala-X"
text: '''La primera vez que quites una ficha de Escudos de tu nave en cada ronda, asigna 1 ficha de Evasión a tu nave.'''
# TIE/fo
'"Omega Ace"':
name: '"As Omega"'
ship: "Caza TIE/fo"
text: """Cuando ataques a un defensor que has fijado como blanco, puedes gastar las fichas de Blanco Fijado y una ficha de Concentración para cambiar todos tus resultados de dados por resultados %CRIT%."""
'"Epsilon Leader"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Caza TIE/fo"
text: """Al comienzo de la fase de Combate, retira 1 ficha de Tensión de cada nave aliada que tengas a alcance 1."""
'"Zeta Ace"':
name: '"As Zeta"'
ship: "Caza TIE/fo"
text: """Cuando realices una acción de tonel volado, puedes utilizar la plantilla de maniobra (%STRAIGHT% 2) en vez de la plantilla (%STRAIGHT% 1)."""
"Omega Squadron Pilot":
name: "Piloto del Esc. Omega"
ship: "Caza TIE/fo"
"Zeta Squadron Pilot":
name: "Piloto del Esc. Zeta"
ship: "Caza TIE/fo"
"Epsilon Squadron Pilot":
name: "Piloto del Esc. Epsilon"
ship: "Caza TIE/fo"
'"Omega Leader"':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza TIE/fo"
text: '''Las naves enemigas que tienes fijadas como blanco no pueden modificar ningún dado cuando te atacan o se defienden de tus ataques.'''
'PI:NAME:<NAME>END_PI':
text: '''Cuando reveles una maniobra verde o roja, puedes girar tu selector de maniobras para escoger otra maniobra del mismo color.'''
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza TIE"
text: """Los Cazas TIE aliados que tengas a alcance 1-3 pueden realizar la acción de tu carta de Mejora %ELITE% equipada."""
'"PI:NAME:<NAME>END_PI"':
ship: "Caza TIE"
text: """Cuando ataques, al comienzo del paso "Comparar los resultados", puedes anular todos los resultados de los dados. Si anulas al menos un resultado %CRIT%, inflinge 1 carta de Daño boca abajo al defensor."""
'"PI:NAME:<NAME>END_PI"':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza TIE"
text: """Cuando otra nave aliada que tengas a alcance 1 gaste una ficha de Concentración, asigna 1 ficha de Concentración a tu nave."""
'PI:NAME:<NAME>END_PI':
ship: "Lanzadera de Ataque"
text: """Cuando te defiendas, si estás bajo tensión, puedes cambiar hasta 2 de tus resultados %FOCUS% por resultados %EVADE%."""
'"PI:NAME:<NAME>END_PI Leader"':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando ataques, si no estás bajo tensión, puedes recibir 1 ficha de Tensión para tirar 1 dado de ataque adicional.'''
ship: "Caza TIE/fo"
'"Epsilon Ace"':
name: "PI:NAME:<NAME>END_PI"
text: '''Mientras no tengas ninguna carta de Daño asignada, se considera que tienes Habilidad 12.'''
ship: "Caza TIE/fo"
"PI:NAME:<NAME>END_PI":
text: """Cuando una nave enemiga que tengas a alcance 1-2 efectúe un ataque, puedes gastar una ficha de Concentración. Si decides hacerlo, el atacante tira 1 dado de ataque menos."""
'"PI:NAME:<NAME>END_PI"':
text: """Al comienzo de la fase de Combate, toda nave enemiga con la que estés en contacto recibe 1 ficha de Tensión."""
'HPI:NAME:<NAME>END_PI Syndulla (Attack Shuttle)':
name: "PI:NAME:<NAME>END_PI (Lanzadera de Ataque)"
ship: "Lanzadera de Ataque"
text: """Cuando reveles una maniobra verde o roja, puedes girar tu selector de maniobras para escoger otra maniobra del mismo color."""
'PI:NAME:<NAME>END_PI':
ship: "Lanzadera de Ataque"
text: """Inmediatamente antes de revelar tu maniobra, puedes realizar una acción gratuita de impulso o tonel volado."""
'"PI:NAME:<NAME>END_PI':
ship: "Lanzadera de Ataque"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
ship: "VCX-100"
'PI:NAME:<NAME>END_PI':
text: '''Una vez por ronda, después de que te descartes de una carta de Mejora %ELITE%, dale la vuelta a esa carta para ponerla boca arriba.'''
ship: "Bombardero TIE"
'PI:NAME:<NAME>END_PI':
text: '''Mientras no estés bajo tensión, puedes ejecutar tus maniobras %TROLLLEFT% y %TROLLRIGHT% como maniobras blancas.'''
ship: "T-70 Ala-X"
"PI:NAME:<NAME>END_PI":
text: """Después de que te defiendas, puedes ralizar una acción gratuita."""
ship: "Prototipo de TIE Avanzado"
"4-LOM":
ship: "Caza Estelar G-1A"
text: """Al comienzo de la fase Final, puedes asignar 1 de tus fichas de Tensión a otra nave que tengas a alcance 1."""
"Tel PI:NAME:<NAME>END_PI":
ship: "Saltador Maestro 5000"
text: """La primrea vez que seas destruido, en vez de eso anula todo el daño restante, descarta todas tus cartas de Daño e inflinge 4 cartas de Daño boca abajo a esta nave."""
"PI:NAME:<NAME>END_PI":
ship: "Saltador Maestro 5000"
text: """Al comienzo de la fase de Combate, puedes asignar a otra nave aliada a alcance 1 todas las fichas de Concentración, Evasión y Blanco Fijado que tengas asignadas."""
"Contracted Scout":
name: "PI:NAME:<NAME>END_PI"
ship: "Saltador Maestro 5000"
'"Deathfire"':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando reveles tu selector de maniobras o después de que realices una acción, puedes realizar una acción de carta de Mejora %BOMB% como acción gratuita.'''
ship: "Bombardero TIE"
"Sienar Test Pilot":
name: "Piloto de pruebas de Sienar"
ship: "Prototipo de TIE Avanzado"
"Baron of the Empire":
name: "PI:NAME:<NAME>END_PI"
ship: "Prototipo de TIE Avanzado"
"PI:NAME:<NAME>END_PI Stele (TIE Defender)":
name: "PI:NAME:<NAME>END_PI (Defensor TIE)"
text: """Cuando tu ataque inflija una carta de Daño boca arriba al defensor, en vez de eso roba 3 cartas de Daño, elige 1 de ellas a tu elección y luego descarta las otras."""
ship: "Defensor TIE"
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando reveles una maniobra %STRAIGHT%, puedes considerarla como una maniobra %KTURN%."""
ship: "Defensor TIE"
"Glaive Squadron Pilot":
name: "PI:NAME:<NAME>END_PI del escuPI:NAME:<NAME>END_PI"
ship: "Defensor TIE"
"PI:NAME:<NAME>END_PI (PS9)":
text: """Cuando ataques o te defiendas, si tienes una ficha de Concentración, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%."""
ship: "T-70 Ala-X"
"Resistance Sympathizer":
name: "PI:NAME:<NAME>END_PIatizante de la Resistencia"
ship: "YT-1300"
"Rey":
text: """Cuando ataques o te defiendas, si la nave enemiga está dentro de tu arco de fuego, puedes volver a tirar hasta 2 dados en los que hayas sacado caras vacías."""
'Han PI:NAME:<NAME>END_PI (TFA)':
text: '''En el momento de desplegarte durante la preparación de la partida, se te puede colocar en cualquier parte de la zona de juego que esté más allá de alcance 3 de las naves enemigas.'''
'ChePI:NAME:<NAME>END_PI (TFA)':
text: '''Después de que otra nave aliada que tengas a alcance 1-3 sea destruida (pero no hay aabandonado el campo de batalla), puedes efectuar un ataque.'''
'PI:NAME:<NAME>END_PI':
ship: "ARC-170"
text: '''Cuando ataques o te defiendas, puedes gastar una ficha de Blanco fijado que tengas sobre la nave enemiga para añadir 1 resultado %FOCUS% a tu tirada.'''
'PI:NAME:<NAME>END_PI':
ship: "ARC-170"
text: '''Cuando otra nave aliada que tengas a alcance 1-2 esté atacando, puede usar tus fichas azules de Blanco fijado como si fuesen suyas.'''
'PI:NAME:<NAME>END_PI':
ship: "ARC-170"
text: '''Después de que una nave enemiga que tengas dentro de tu arco de fuego a alcance 1-3 ataque a otra nave aliada, puedes realizar una acción gratuita.'''
'PI:NAME:<NAME>END_PI':
ship: "ARC-170"
text: '''Después de que ejecutes una maniobra, puedes tirar 1 dado de ataque. Si sacas %HIT% o %CRIT%, quita 1 ficha de Tensión de tu nave.'''
'"Quickdraw"':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza TIE/sf"
text: '''Una vez por ronda, cuando pierdas una ficha de Escudos, puedes realizar un ataque de armamento principal.'''
'"Backdraft"':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza TIE/sf"
text: '''Cuando ataques a una nave que esté dentro de tu arco de fuego auxiliar, puedes añadir 1 resultado %CRIT%.'''
'Omega Specialist':
name: "Especialista del Escuadrón Omega"
ship: "Caza TIE/sf"
'Zeta Specialist':
name: "Especialista del Escuadrón Zeta"
ship: "Caza TIE/sf"
'PI:NAME:<NAME>END_PI':
ship: "Caza Estelar del Protectorado"
text: '''Cuando ataques o te defiendas, si tienes la nave enemiga a alcance 1, puedes tirar 1 dado adicional.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Estelar del Protectorado"
text: '''Al comienzo de la fase de Combate, puedes elegir 1 nave enemiga que tengas a alcance 1. Si estás dentro de su arco de fuego, esa nave descarta todas sus fichas de Concentración y Evasión.'''
'PI:NAME:<NAME>END_PI':
ship: "Caza Estelar del Protectorado"
text: '''Después de que ejecutes una maniobra roja, asigna 2 fichas de Concentración a tu nave.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Estelar del Protectorado"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Estelar del Protectorado"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Estelar del Protectorado"
'PI:NAME:<NAME>END_PI':
ship: "Nave de persecución clase Lancero"
text: '''Al comienzo de la fase de Combate, puedes elegir una nave que tengas a alcance 1. Si esa nave está dentro de tus arcos de fuego normal <strong>y</strong> móvil, asígnale 1 ficha de Campo de tracción.'''
'PI:NAME:<NAME>END_PI':
ship: "Nave de persecución clase Lancero"
text: '''Al comienzo de la fase de Combate, puedes elegir una nave que tengas a alcance 1-2. Si esa nave está dentro de tu arco de fuego móvil, asígnale 1 ficha de Tensión.'''
'PI:NAME:<NAME>END_PI (Scum)':
ship: "Nave de persecución clase Lancero"
text: '''Cuando te defiendas contra una nave enemiga que tengas dentro de tu arco de fuego móvil a alcance 1-2, puedes añadir 1 resultado %FOCUS% a tu tirada.'''
'PI:NAME:<NAME>END_PI':
name: "Cazador de puerto clandestPI:NAME:<NAME>END_PI"
ship: "Nave de persecución clase Lancero"
'PI:NAME:<NAME>END_PI (TIE Fighter)':
ship: "Caza TIE"
text: '''Inmediatametne antes de revelar tu maniobra, puedes realizar una acción gratuita de impulso o tonel volado.'''
'"Zeb" Orrelios (TIE Fighter)':
ship: "Caza TIE"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
'PI:NAME:<NAME>END_PI':
ship: "Lanzadera clase Ípsilon"
text: '''La primera vez que seas impactado por un ataque en cada ronda, asigna la carta de Estad "Yo te mostraré el Lado Oscuro" al atacante.'''
'PI:NAME:<NAME>END_PI':
ship: "Saltador Quad"
text: '''Al final de la fase de Activación, <strong>debes</strong> asignar una ficha de Campo de tracción a toda nave con la que estés en contacto.'''
'PI:NAME:<NAME>END_PI':
ship: "Ala-U"
text: '''Al comienzo de la fase de Activación, puedes quitar 1 ficha de Tensión de 1 otra nave aliada que tengas a alcance 1-2.'''
'PI:NAME:<NAME>END_PI':
ship: "Ala-U"
text: '''Cuando una nave aliada fije un blanco, esa nave puede fijarlo sobre una nave enemiga que esté situada a alcance 1-3 de cualquier nave aliada.'''
'PI:NAME:<NAME>END_PI':
ship: "Ala-U"
text: '''Después de que una nave enemiga ejecute una maniobra que la haga solaparse con tu nave, puedes realizar una acción gratuita.'''
'''"PI:NAME:<NAME>END_PI"''':
ship: "Fustigador TIE"
name: '"PI:NAME:<NAME>END_PI"'
text: '''Cuando tengas equipada la carta de Mejora "Alreones adaptativos", puedes elegir ignorar su capacidad de carta.'''
'''"Pure Sabacc"''':
ship: "Fustigador TIE"
name: '"PI:NAME:<NAME>END_PI"'
text: '''Cuando ataques, si tienes 1 o menos cartas de Daño, tira 1 dado de ataque adicional.'''
'''"Countdown"''':
ship: "Fustigador TIE"
name: '"PI:NAME:<NAME>END_PI"'
text: '''Cuando te defiendas, si no estás bajo tensión, durante el paso "Comparar los resultados", puedes sufrir 1 punto de daño para anular <strong>todos</strong> los resultados de los dados. Si lo haces, recibes 1 ficha de Tensión.'''
'PI:NAME:<NAME>END_PI':
ship: "T-70 Ala-X"
text: '''Cuando recibas una ficha de Tensión, si hay alguna nave enemiga dentro de tu arco de fuego a alcance 1, puedes descartar esa ficha de Tensión.'''
'"Snap" PI:NAME:<NAME>END_PI':
ship: "T-70 Ala-X"
text: '''Después de que ejecutes una maniobra de velocidad 2, 3 ó 4, si no estás en contacto con ninguna nave, puedes realizar una acción gratuita de impulso.'''
'PI:NAME:<NAME>END_PI':
ship: "T-70 Ala-X"
text: '''Cuando ataques o te defiendas, puedes volver a tirar 1 de tus dados por cada otra nave aliada que tengas a Alcance 1.'''
'PI:NAME:<NAME>END_PI':
ship: "Caza TIE"
text: '''Al comienzo de la fase de Combate, puedes gastar 1 ficha de Concentración para elegir una nave aliada que tengas a alcance 1. Esa nave puede realizar 1 acción gratuita.'''
'PI:NAME:<NAME>END_PI':
ship: "Caza TIE"
name: "PI:NAME:<NAME>END_PI"
text: '''Después de que efectúes un ataque, asigna la carta de Estado "Fuego de supresión" al defensor.'''
'Major StrPI:NAME:<NAME>END_PIan':
ship: "Lanzadera clase Ípsilon"
name: "PI:NAME:<NAME>END_PI"
text: '''A efectos de tus acciones y cartas de Mejora, puedes considerar las naves aliadas que tengas a alcance 2-3 como si estuvieran a alcance 1.'''
'PI:NAME:<NAME>END_PI':
ship: "Lanzadera clase Ípsilon"
name: "PI:NAME:<NAME>END_PI"
text: '''Durante la preparación de la partida, las naves aliadas pueden ser colocadas en cualquier lugar de la zona de juego que esté situado a alcance 1-2 de ti.'''
'PI:NAME:<NAME>END_PI':
ship: "Saltador Quad"
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando reveles una maniobra de retroceso, puedes soltar una bomba usando los salientes de la parte frontal de tu peana (incluso una bomba con el encabezado "<strong>Acción:</strong>").'''
'PI:NAME:<NAME>END_PI':
ship: "Saltador Quad"
text: '''Cuando te defiendas, en vez de usar tu valor de Agilidad, puedes tirar tantos dados de defensa como la velocidad de la maniobra que has ejecutado en esta ronda.'''
"Blue Squadron Pathfinder":
name: "Infiltrador del Escuadrón Azul"
ship: "Ala-U"
"Black Squadron Scout":
name: "Explorador del Escuadrón Negro"
ship: "Fustigador TIE"
"Scarif Defender":
name: "Defensor de Scarif"
ship: "Fustigador TIE"
"Imperial Trainee":
name: "Cadete Imperial"
ship: "Fustigador TIE"
"Starkiller Base Pilot":
ship: "Lanzadera clase Ípsilon"
name: "Piloto de la base Starkiller"
"PI:NAME:<NAME>END_PI":
ship: "Saltador Quad"
name: "Traficante de armas de PI:NAME:<NAME>END_PI"
'Genesis Red':
ship: "Interceptor M3-A"
text: '''Después de que fijes un blanco, asigna fichas de Concentración y fichas de Evasión a tu nave hasta que tengas tantas fichas de cada tipo como la nave que has fijado.'''
'PI:NAME:<NAME>END_PI':
ship: "Interceptor M3-A"
text: '''Al comienzo de la fase de Combate, puedes recibir una ficha de Armas inutilizadas para poner boca arriba una de tus cartas de Mejora %TORPEDO% o %MISSILE% descartadas.'''
'PI:NAME:<NAME>END_PI':
ship: "Interceptor M3-A"
text: '''Cuando ataques o te defiendas, puedes gastar 1 ficha de Escudos para volver a tirar cualquier cantidad de tus dados.'''
'SunPI:NAME:<NAME>END_PI':
ship: "Interceptor M3-A"
text: '''Una vez por ronda, después de que tires o vuelvas a tirar los dados, si has sacado el mismo resultado en cada uno de tus dados, puedes añadir 1 más de esos resultados a la tirada.'''
'C-ROC CPI:NAME:<NAME>END_PIiser':
ship: "Crucero C-ROC"
name: "PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI"
'PI:NAME:<NAME>END_PI':
ship: "TIE Agresor"
text: '''Cuando ataques, puedes gastar 1 ficha de Concentración para anular todos los resultados %FOCUS% y de cara vacía del defensor.'''
'"Double Edge"':
ship: "TIE Agresor"
name: "PI:NAME:<NAME>END_PI"
text: '''Una vez por ronda, después de que efectúes un ataque con un armamento secundario que no impacte, puedes efectuar un ataque con un arma diferente.'''
'Onyx Squadron Escort':
ship: "TIE Agresor"
name: "PI:NAME:<NAME>END_PI"
'Sienar Specialist':
ship: "TIE Agresor"
name: "Especialista de PI:NAME:<NAME>END_PI"
'PI:NAME:<NAME>END_PI':
ship: "Caza Kihraxz"
text: '''Después de que te defiendas, si la tirada que realizaste no consistió exactamente en 2 dados de defensa, el atacante recibe 1 ficha de Tensión.'''
'PI:NAME:<NAME>END_PI':
ship: "Cañonera Auzituck"
text: '''Cuando otra nave aliada que tengas a alcance 1 se esté defendiendo, puedes gastar 1 ficha de Refuerzo. Si lo haces, el defensor añade 1 resultado %EVADE%.'''
'PI:NAME:<NAME>END_PI':
ship: "Cañonera Auzituck"
text: '''Cuando ataques, si no tienes ninguna ficha de Escudos y tienes asignada como mínimo 1 carta de Daño, tira 1 dado de ataque adicional.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Cañonera Auzituck"
'Kashyyyk Defender':
name: "Defensor de PI:NAME:<NAME>END_PI"
ship: "Cañonera Auzituck"
'CaptPI:NAME:<NAME>END_PI (Scum)':
name: "PI:NAME:<NAME>END_PI (Scum)"
ship: "Bombardero Scurrg H-6"
text: '''Puedes ignorar las bombas aliadas. Cuando una nave aliada se está defendiendo, si el atacante mide el alcance a través de una ficha de Bomba aliada, el defensor puede añadir 1 resultado%EVADE%.'''
'Captain Nym (Rebel)':
name: "PI:NAME:<NAME>END_PI (Rebelde)"
ship: "Bombardero Scurrg H-6"
text: '''Una vez por ronda, puedes impedir que una bomba aliada detone.'''
'LPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero Scurrg H-6"
'KPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero Scurrg H-6"
'Sol PI:NAME:<NAME>END_PI':
ship: "Bombardero Scurrg H-6"
text: '''Cuando sueltes una bomba, puedes utilizar la plantilla de maniobra (%TURNLEFT% 1) o (%TURNRIGHT% 1) en vez de la plantilla de (%STRAIGHT% 1).'''
'PI:NAME:<NAME>END_PI':
ship: 'Víbora Estelar'
text: '''Si no estás bajo tensión, cuando reveles una maniobra de giro, inclinación o giro de Segnor, puedes ejecutarla como si fuera una maniobra roja de giro Tallon con la misma dirección (izquierda o derecha) utilizando la plantilla de maniobra revelada originalmente.'''
'ThPI:NAME:<NAME>END_PI':
ship: 'Víbora Estelar'
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", puedes elegir 1 nave enemiga y asignarle la carta de Estado "Vigilado" o "Imitado".'''
'Black PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: 'Víbora Estelar'
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza Kihraxz"
text: '''Una vez por ronda, después de que una nave enemiga que no se está defendiendo contra un ataque sufra daño normal o daño crítico, puedes efectuar un ataque contra esa nave.'''
'PI:NAME:<NAME>END_PI':
ship: "Ala Estelar clase Alfa"
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando te defiendas, si tienes asignada una ficha de Armas bloqueadas, tira 1 dado de defensa adicional.'''
'Nu Squadron Pilot':
name: "Piloto del Escuadrón Nu"
ship: "Ala Estelar clase Alfa"
'Rho Squadron Veteran':
name: "Veterano del Escuadrón Rho"
ship: "Ala Estelar clase Alfa"
'PI:NAME:<NAME>END_PI':
ship: "Ala Estelar clase Alfa"
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando recibas una ficha de Armas bloqueadas, si no estás bajo tensión, puedes recibir 1 ficha de Tensión para retirar esa ficha de Armas bloqueadas.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza M12-L Kimogila"
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza M12-L Kimogila"
'PI:NAME:<NAME>END_PI':
ship: "Caza M12-L Kimogila"
text: '''Después de que efectúes un ataque, toda nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego centrado debe elegir entre sufrir 1 daño o retirar todas sus fichas de Concrentración y Evasión.'''
'PI:NAME:<NAME>END_PI (Kimogila)':
ship: "Caza M12-L Kimogila"
text: '''Al comienzo de la fase de Combate, puedes fijar como blanco una nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego centrado.'''
'PI:NAME:<NAME>END_PIau (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando una nave enemiga que tengas a alcance 1-3 y esté situada dentro de tu arco de fuego pase a ser la nave activa durante la fase de Combate, si no estás bajo tensión, puedes recibir 1 ficha de Tensión. Si lo haces, esa nave no podrá gastar fichas para modificar sus dados cuando ataque en esta ronda.'''
'Ezra Bridger (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: """Cuando te defiendas, si estás bajo tensión, puedes cambiar hasta 2 de tus resultados %FOCUS% por resultados %EVADE%."""
'"Zeb" Orrelios (Sheathipede)':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando te defiendas, puedes anular resultados %CRIT% antes de anular resultados %HIT%.'''
'AP-5':
ship: "Lanzadera clase Sheathipede"
text: '''Cuando realices la acción de coordinación, después de que elijas a una nave aliada y antes de que esa nave realice su acción gratuita, puedes recibir 2 fichas de Tensión para quitarle 1 ficha de Tensión a esa nave.'''
'Crimson Squadron Pilot':
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero B/SF-17"
'"Crimson Leader"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Bombardero B/SF-17"
text: '''Cuando ataques, si el defensor está situado dentro de tu arco de fuego, puedes gastar 1 resultado %HIT% o %CRIT% para asignar el estado "Estremecido" al defensor.'''
'"Crimson Specialist"':
name: '"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"'
ship: "Bombardero B/SF-17"
text: '''Cuando coloques una ficha de Bomba que has soltado después de revelar tu selector de maniobras, puedes colocarla en cualquier lugar de la zona de juego donde quede en contacto con tu nave.'''
'"Cobalt Leader"':
name: '"PI:NAME:<NAME>END_PI"'
ship: "Bombardero B/SF-17"
text: '''Cuando ataques, si el defensor está situado a alcance 1 de una ficha de Bomba, el defensor tira 1 dado de defensa menos (hasta un mínimo de 0).'''
'SPI:NAME:<NAME>END_PIar-Jaemus Analyst':
name: "PI:NAME:<NAME>END_PI"
ship: "Silenciador TIE"
'First Order Test Pilot':
name: "Piloto de pruebas de la Primera Orden"
ship: "Silenciador TIE"
'PI:NAME:<NAME>END_PI (TIE Silencer)':
name: "PI:NAME:<NAME>END_PI (Silenciador TIE)"
ship: "Silenciador TIE"
text: '''La primera vez que seas impactado por un ataque en cada ronda, asigna la carta de Estado "Yo te mostraré el Lado Oscuro" al atacante.'''
'Test Pilot "Blackout"':
name: 'Piloto de pruebas "Apagón"'
ship: "Silenciador TIE"
text: '''Cuando ataques, si el ataque está obstruido, el defensor tira 2 dados de defensa menos (hasta un mínimo de 0).'''
'Partisan Renegade':
name: "Insurgente de los Partisanos"
ship: "Ala-U"
'Cavern Angels Zealot':
name: "Fanático de los Ángeles Cavernarios"
ship: "Ala-X"
'Kullbee Sperado':
ship: "Ala-X"
text: '''Después de que realices una acción de impulso o de tonel volado, puedes darle la vuelta a la carta de Mejora "Alas móviles" que tengas equipada en tu nave.'''
'Major Vermeil':
name: "PI:NAME:<NAME>END_PI"
ship: "Segador TIE"
text: '''Cuando ataques, si el defensor no tiene asignada ninguna ficha de Concentración ni de Evasión, puedes cambiar 1 de tus resultados %FOCUS% o de cara vacía por un resultado %HIT%.'''
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: '''Después de que una nave aliada ejecute una maniobra con una velocidad de 1, si esa nave está situada a alcance 1 de ti y no se ha solapado con ninguna nave, puedes asignarle 1 de tus fichas de Concentración o Evasión.'''
ship: "Segador TIE"
'PI:NAME:<NAME>END_PI':
name: 'PI:NAME:<NAME>END_PI'
ship: "Segador TIE"
text: '''Cuando te defiendas, si el atacante está interferido, añade 1 resultado %EVADE% a tu tirada.'''
'Scarif Base Pilot':
name: "PI:NAME:<NAME>END_PIto de la base de Scarif"
ship: "Segador TIE"
'PI:NAME:<NAME>END_PI':
ship: "Ala-X"
text: '''Después de que realices una acción de impulso, puedes recibir 1 ficha de Tensión para recibir 1 ficha de Evasión.'''
'PI:NAME:<NAME>END_PI':
ship: "Ala-U"
text: '''Cuando una nave aliada que tengas a alcance 1-2 efectúe un ataque, si esa nave está bajo tensión o tiene asignada por lo menos 1 carta de Daño, puede volver a tirar 1 dado de ataque.'''
'Benthic Two-Tubes':
name: "PI:NAME:<NAME>END_PI"
ship: "Ala-U"
text: '''Después de que realices una acción de concentración, puedes retirar 1 de tus fichas de Concentración para asignarla a una nave aliada que tengas a alcance 1-2.'''
'PI:NAME:<NAME>END_PI':
ship: "Ala-U"
text: '''Cuando otra nave aliada que tengas a alcance 1-2 se defienda, el atacante no puede volver a tirar más de 1 dado de ataque.'''
'Edrio Two-Tubes':
name: "PI:NAME:<NAME>END_PI"
ship: "Ala-X"
text: '''Cuando te conviertas en la nave activa durante la fase de Activación, si tienes asignadas 1 o más fichas de Concentración, puedes realizar una acción gratuita.'''
upgrade_translations =
"Ion Cannon Turret":
name: "Torreta de cañones de iones"
text: """<strong>Ataque:</strong> Ataca 1 nave (aunque esté fuera de tu arco de fuego).<br /><br />Si este ataque impacta, el defensor sufre 1 punto de daño y recibe 1 ficha de Iones. Después se anulan todos los resultados de los dados."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
"R2 Astromech":
name: "Droide Astromecánico R2"
text: """Puedes ejecutar todas las maniobras de velocidad 1 y 2 como maniobras verdes."""
"R2-D2":
text: """Después de que ejecutes una maniobra verde, puedes recuperar 1 ficha de Escudos (pero no puedes tener más fichas que tu valor de Escudos)."""
"R2-F2":
text: """<strong>Acción:</strong> Tu valor de agilidad aumenta en 1 hasta el final de esta ronda de juego."""
"R5-D8":
text: """<strong>Acción:</strong> Tira 1 dado de defensa.<br /><br />Si sacas %EVADE% o %FOCUS%, descarta 1 carta de Daño que tengas boca abajo."""
"R5-K6":
text: """Después de gastar tu ficha de Blanco Fijado, tira 1 dado de defensa.<br /><br />Si sacas un resultado %EVADE% puedes volver a fijar la misma nave como blanco inmediatamente. No puedes gastar esta nueva ficha de Blanco Fijado durante este ataque."""
"R5 Astromech":
name: "Droide Astromecánico R5"
text: """Durante la fase Final, puedes elegir 1 de las cartas de Daño con el atributo <strong>Nave</strong> que tengas boca arriba, darle la vuelta y dejarla boca abajo."""
"Determination":
name: "Determinación"
text: """Cuando se te asigne una carta de Daño boca arriba que tenga el atributo <strong>Piloto</strong>, descártala inmediatamente sin resolver su efecto."""
"Swarm Tactics":
name: "Táctica de Enjambre"
text: """Al principio de la fase de Combate, elige 1 nave aliada que tengas a alcance 1.<br /><br />Hasta el final de esta fase, se considera que el valor de Habilidad de la nave elejida es igual que el tuyo."""
"Squad Leader":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Elije una nave a alcance 1-2 cuyo pilioto tenga una Habilidad más baja que la tuya.<br /><br />La nave elegida puede llevar a cabo 1 acción gratuita de inmediato."""
"Expert Handling":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Realiza una acción gratuita de tonel volado. Si no tienes el icono de acción %BARRELROLL%, recibes una ficha de Tensión.<br /><br />Después puedes descartar 1 ficha enemiga de Blanco Fijado que esté asignada a tu nave."""
"Marksmanship":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Cuando ataques en esta ronda puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT% y tus demás resultados %FOCUS% por resultados %HIT%."""
"Concussion Missiles":
name: "Misiles de Impacto"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Puedes cambiar 1 resultado de cara vacía por un resultado %HIT%."""
"Cluster Missiles":
name: "Misiles de Racimo"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque <strong>dos veces</strong>."""
"DPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Ejecuta una maniobra blanca (%TURNLEFT% 1) o (%TURNRIGHT% 1) y luego recibe 1 ficha de Tensión.<br /><br />Después, si no tienes el ícono de acción %BOOST%, tira 2 dados de ataque y sufre todos los daños normales (%HIT%) y críticos (%CRIT%) obtenidos."""
"Elusiveness":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando te defiendas en combate, puedes recibir 1 ficha de Tensión para elegir 1 dado de ataque. El atacante deberá volver a lanzar ese dado.<br /><br />No puedes usar esta habilidad si ya tienes una ficha de Tensión."""
"Homing Missiles":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque.<br /><br />El defensor no puede gastar fichas de evasión durante este ataque."""
"Push the Limit":
name: "PI:NAME:<NAME>END_PIáPI:NAME:<NAME>END_PI"
text: """Una vez por ronda, después de que realices una acción podras realizar a cabo 1 acción gratuita de entre las que figuren en tu barra de acciones.<br /><br />Después recibes 1 ficha de Tensión."""
"Deadeye":
name: "PI:NAME:<NAME>END_PI"
text: """%SMALLSHIPONLY%%LINEBREAK%Puedes tratar la expresión <strong>"Ataque (blanco fijado)"</strong> como si dijera <strong>"Ataque (concentración)"</strong>.<br /><br />Cuando un ataque te obligue a gastar una ficha de Blanco Fijado, puedes gastar una ficha de Concentración en su lugar."""
"Expose":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Hasta el final de la ronda, el valor de tu armamento principal se incrementa en 1 y tu Agilidad se reduce en 1."""
"Gunner":
name: "PI:NAME:<NAME>END_PI"
text: """Después de que efectúes un ataque y lo falles, puedes realizar inmediatamente un ataque con tu armamento principal. No podrás realizar ningún otro ataque en esta misma ronda."""
"Ion Cannon":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Si este ataque impacta, el defensor sufre 1 de daño y recibe 1 ficha de Iones. Después se anulan <b>todos</b> los resultados de los dados."""
"Heavy Laser Cannon":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Inmediatamente después de lanzar los dados de ataque, debes cambiar todos tus resultados %CRIT% por resultados %HIT%."""
"Seismic Charges":
name: "Cargas Sísmicas"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Carga Sísmica.<br /><br />Esta ficha se <strong>detona</strong> al final de la fase de Activación."""
"Mercenary Copilot":
name: "CopiloPI:NAME:<NAME>END_PI MPI:NAME:<NAME>END_PI"
text: """Cuando ataques a alcance 3, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%."""
"Assault Missiles":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta al objetivo, toda otra nave que haya a alcance 1 del defensor sufre 1 daño."""
"Veteran Instincts":
name: "Instinto de Veterano"
text: """La Habilidad de tu piloto se incrementa en 2."""
"Proximity Mines":
name: "Minas de Proximidad"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Mina de Proximidad.<br /><br />Cuando la peana o la plantilla de maniobra de una nave se solape con esta ficha, ésta se <strong>detona</strong>.<br /><br /><strong>Ficha de Mina de proximidad:</strong> Cuando se detona una de estas fichas de Bomba, la nave que la haya atravesado o solapado tira 3 dados de ataque y sufre todo el daño (%HIT%) y daño crítico (%CRIT%) obtenido en la tirada. Después se descarta esta ficha."""
"Weapons Engineer":
name: "Ingeniero de Armamento"
text: """Puedes tener 2 Blancos Fijados a la vez (pero sólo 1 para cada nave enemiga).<br /><br />Cuando fijes un blanco, puedes fijar como blanco a dos naves distintas."""
"Draw Their Fire":
name: "Atraer su fuego"
text: """Cuando una nave aliada que tengas a alcance 1 sea alcanzada por un ataque, puedes sufrir tú 1 de sus resultados %CRIT% no anulados en vez de la nave objetivo."""
"Luke Skywalker":
text: """Después de que efectúes un ataque y lo falles, puedes realizar inmediatamente un ataque con tu armamento principal. Puedes cambiar 1 resultado %FOCUS% por 1 resultado %HIT%. No podrás realizar ningún otro ataque en esta misma ronda."""
"PI:NAME:<NAME>END_PI":
text: """Todas las maniobras %STRAIGHT% se consideran verdes para ti."""
"Chewbacca":
text: """Cuando recibas una carta de Daño, puedes descartarla de inmediato y recuperar 1 de Escudos.<br /><br />Luego descarta esta carta de Mejora."""
"Advanced Proton Torpedoes":
name: "Torpedos de protones avanzados"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque. Puedes cambiar hasta 3 resultados de caras vacías por resultados %FOCUS%."""
"Autoblaster":
name: "Cañón Blaster Automático"
text: """<strong>Ataque:</strong> Ataca a 1 nave.<br /><br />Tus resultados %HIT% no pueden ser anulados por los dados de defensa.<br /><br />El defensor puede anular tus resultados %CRIT% antes que los %HIT%."""
"Fire-Control System":
name: "Sistema de Control de Disparo"
text: """Después de que efectúes un ataque, puedes fijar al defensor como blanco."""
"Blaster Turret":
name: "Torreta Bláster"
text: """<strong>Ataque (Concentración):</strong> Gasta 1 ficha de Concentración para efectuar este ataque contra una nave (aunque esté fuera de tu arco de fuego)."""
"Recon Specialist":
name: "Especialista en Reconocimiento"
text: """Cuando realices una acción de Concentración, asigna 1 ficha de Concentración adicional a tu nave."""
"Saboteur":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Elige 1 nave enemiga que tengas a alcance 1 y tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, elige al azar 1 carta de Daño que esa nave tenga asignada boca abajo, dale la vuelta y resuélvela."""
"Intelligence Agent":
name: "Agente del Servicio de Inteligencia"
text: """Al comienzo de la fase de Activación, elige 1 nave enemiga que tengas a alcance 1-2. Puedes mirar el selector de maniobras de esa nave."""
"Proton Bombs":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Bombas de Protones.<br /><br />Esta ficha se <strong>detona</strong> al final de la fase de Activación."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando reveles una maniobra roja, puedes descartar esta carta para tratarla como si fuera una maniobra blanca hasta el final de la fase de Activación."""
"Advanced Sensors":
name: "Sensores Avanzados"
text: """Inmediatamente antes de que reveles tu maniobra, puedes realizar 1 acción gratuita.<br /><br />Si utilizas esta capacidad, debes omitir tu paso de "Realizar una acción" durante esta ronda."""
"Sensor Jammer":
name: "Emisor de Interferencias"
text: """Cuando te defiendas, puedes cambiar 1 de los resultados %HIT% por uno %FOCUS%.<br /><br />El atacante no puede volver a lanzar el dado cuyo resultado hayas cambiado."""
"PI:NAME:<NAME>END_PI":
text: """Después de que ataques a una nave enemiga, puedes sufrir 2 de daño para que esa nave reciba 1 de daño crítico."""
"Rebel Captive":
name: "PI:NAME:<NAME>END_PI"
text: """Una vez por ronda, la primera nave que te declare como objetivo de un ataque recibe inmediatamente 1 ficha de Tensión."""
"Flight Instructor":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando te defiendas, puedes volver a tirar 1 dado en el que hayas sacado %FOCUS%. Si la Habilidad del piloto atacante es de 2 o menos, puedes volver a tirar 1 dado en el que hayas sacado una cara vacía."""
"Navigator":
name: "Oficial de Navegación"
text: """Cuando reveles una maniobra, puedes rotar el selector para escoger otra maniobra que tenga la misma dirección.<br /><br />Si tienes alguna ficha de Tensión, no puedes rotar el selector para escoger una maniobra roja."""
"Opportunist":
name: "Oportunista"
text: """Cuando ataques, si el defensor no tiene fichas de Concentración o de Evasión, puedes recibir 1 ficha de Tensión para tirar 1 dado de ataque adicional.<br /><br />No puedes utilizar esta capacidad si tienes fichas de Tensión."""
"Comms Booster":
name: "Amplificador de Comunicaciones"
text: """<strong>Energía:</strong> Gasta 1 de Energía para descartar todas las fichas de Tensión de una nave aliada que tengas a alcance at Range 1-3. Luego asigna 1 ficha de Concentración a esa nave."""
"Slicer Tools":
name: "Sistemas de Guerra Electrónica"
text: """<strong>Acción:</strong> Elige 1 o mas naves enemigas situadas a alcance 1-3 y que tengan fichas de Tensión. Por cada nave elegida, puedes gastar 1 de Energía para que esa nave sufra 1 daño."""
"Shield Projector":
name: "Proyector de Escudos"
text: """Cuando una nave enemiga pase a ser la nave activa durante la fase de Combate, puedes gastar 3 de Energía para obligar a esa nave a atacarte (si puede) hasta el final de la fase."""
"Ion Pulse Missiles":
name: "Misiles de Pulso Iónico"
text: """<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta, el defensor sufre 1 daño y recibe 2 fichas de Iones. Después se anulan <strong>todos</strong> los resultados de los dados."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al comienzo de la fase de Combate, quita 1 ficha de tensión de otra nave aliada que tengas a alcance 1."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al comienzo de la fase de Combate, puedes elegir 1 nave aliada que tengas a alcance 1-2. Intercambia tu Habilidad de piloto por la Habilidad de piloto de esa nave hasta el final de la fase."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques a una nave situada dentro de tu arco de fuego, si tú no estás dentro del arco de fuego de esa nave, su Agilidad se reduce en 1 (hasta un mínimo de 0)."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques, puedes volver a tirar 1 dado de ataque. Si la Habilidad del piloto defensor es 2 o menor, en vez de eso puedes volver a tirar hasta 2 dados de ataque."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Después de que realices este ataque, el defensor recibe 1 ficha de Tensión si su Casco es de 4 o inferior."""
"RPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Una vez por ronda cuando te defiendas, si tienes al atacante fijado como blanco, puedes gastar esa ficha de Blanco Fijado para elegir algunos o todos sus dados de ataque. El atacante debe volver a tirar los dados que hayas elegido."""
"R7-T1":
name: "R7-T1"
text: """<strong>Acción:</strong> Elije 1 nave enemiga a alcance 1-2. Si te encuentras dentro de su arco de fuego, puedes fijarla como blanco. Después puedes realizar una acción gratuita de impulso."""
"Tactician":
name: "Estratega"
text: """%LIMITED%%LINEBREAK%Después de que efectúes un ataque contra una nave que esté situada dentro de tu arco de fuego a alcance 2, esa nave recibe 1 ficha de Tensión."""
"R2-D2 (Crew)":
name: "R2-D2 (Tripulante)"
text: """Al final de la fase Final, si no tienes Escudos, puedes recuperar 1 de Escudos y tirar 1 dado de ataque. Si sacas %HIT%, pon boca arriba 1 de las cartas de Daño que tengas boca abajo (elegida al azar) y resuélvela."""
"C-3PO":
name: "C-3PO"
text: """Una vez por ronda, antes de que tires 1 o mas dados de defensa, puedes decir en voz alta cuántos resultados %EVADE% crees que vas a sacar. Si aciertas (antes de modificar los dados), añade 1 %EVADE% al resultado."""
"Single Turbolasers":
name: "Batería de Turboláseres"
text: """<strong>Ataque (Energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque. La Agilidad del defensor se duplica contra este ataque. Puedes cambiar 1 de tus resultados de %FOCUS% por 1 resultado de %HIT%."""
"Quad Laser Cannons":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Energía):</strong> Gasta 1 de Energía de esta carta para efectuar este ataque. Si no impacta, puedes gastar inmediatamente 1 de Energía de esta carta para repetir el ataque."""
"Tibanna Gas Supplies":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Energía:</strong> Puedes descartar esta carta para obtener 3 de Energía."""
"Ionization Reactor":
name: "Reactor de Ionización"
text: """<strong>Energía:</strong> Gasta 5 de Energía de esta carta y descártala para para que todas las demás naves situadas a alcance 1 sufran 1 de daño y reciban 1 ficha de Iones."""
"Engine Booster":
name: "Motor Sobrepotenciado"
text: """Immediatamente antes de revelar tu selector de maniobras, puedes gastar 1 de Energía para ejecutar 1 maniobra blanca de (%STRAIGHT% 1). No puedes usar esta capacidad si al hacerlo te solapas con otra nave."""
"R3-A2":
name: "R3-A2"
text: """Cuando declares al objetivo de tu ataque, si el defensor está dentro de tu arco de fuego, puedes recibir 1 ficha de Tensión para hacer que el defensor reciba 1 ficha de Tensión."""
"R2-D6":
name: "R2-D6"
text: """Tu barra de mejoras gana el icono de mejora %ELITE%.<br /><br />No puedes equiparte esta mejora si ya tienes un icono de mejora %ELITE% o si la Habilidad de de tu piloto es de 2 o menos."""
"Enhanced Scopes":
name: "Radar Mejorado"
text: """La Habilidad de tu piloto se considera 0 durante la fase de Activación."""
"ChPI:NAME:<NAME>END_PI RePI:NAME:<NAME>END_PI":
name: "RePI:NAME:<NAME>END_PIado en ChPI:NAME:<NAME>END_PI"
ship: "Ala-A"
text: """<span class="card-restriction">Solo Ala-A.</span><br /><br />Esta carta tiene un coste negativo en puntos de escuadrón."""
"Proton Rockets":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Concentración):</strong> Descarta esta carta para efectuar este ataque.<br /><br />Puedes tirar tantos dados de ataque adicionales como tu puntuación de Agilidad, hasta un máximo de 3 dados adicionales."""
"PI:NAME:<NAME>END_PI":
text: """Despues de que quites una ficha de Tensión de tu nave, puedes asiganar una ficha de Concentración a tu nave."""
"PI:NAME:<NAME>END_PI":
text: """Una vez por ronda, cuando una nave aliada que tengas a alcance 1-3 realice una accion de Concentración o vaya a recibir una ficha de Concentración, en vez de eso puedes asignarle a esa nave una ficha de Evasión."""
"PI:NAME:<NAME>END_PI":
text: """<strong>Acción:</strong> Gasta cualquier cantidad de Energía para elegir ese mismo número de naves enemigas que tengas a alcance 1-2. Descarta todas las fichas de Concentración, Evasión y Blanco Fijado (azules) de las naves elegidas."""
# TODO Check card formatting
"R4-D6":
name: "R4-D6"
text: """Cuando seas alcanzado por un ataque y haya al menos 3 resultados %HIT% sin anular, puedes anular todos los que quieras hasta que solo queden 2. Recibes 1 ficha de Tensión por cada resultado que anules de este modo."""
"R5-P9":
name: "R5-P9"
text: """Al final de la fase de Combate, puedes gastar 1 de tus fichas de Concentración para recuperar 1 ficha de Escudos (hasta un máximo igual a tu puntuación de Escudos)."""
"WED-15 Repair Droid":
name: "Droide de Reparaciones WED-15"
text: """<strong>Acción:</strong> Gasta 1 de Energia para descartar 1 carta de Daño que tengas boca abajo, o bien gasta 3 de Energía para descartar 1 carta de Daño que tengas boca arriba."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al pincipio de la fase de Activación, puedes descartar esta carta para que la Habilidad de todas tus naves se considere 12 hasta el final de la fase."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando otra nave aliada que tengas a alcance 1 efectúe un ataque, podrá cambiar 1 de sus resultados de %HIT% por 1 resultado de %CRIT%."""
"Expanded Cargo Hold":
name: "Bodega de Carga Ampliada"
text: """<span class="card-restriction">Solo GR-75</span><br /><br />Una vez por ronda, cuando tengas que recibir una carta de Daño boca arriba, puedes robar esa carta del mazo de Daño de proa o del mazo de Daño de popa."""
ship: 'Transporte mediano GR-75'
"Backup Shield Generator":
name: "Generador de Escudos Auxiliar"
text: """Al final de cada ronda, puedes gastar 1 de Energía para recuperar 1 de Escudos (hasta el maximo igual a tu puntuación de Escudos)."""
"EM Emitter":
name: "Emisor de señal Electromagnética"
text: """Cuando obstruyas un ataque, el defensor tira 3 dados de defensa adicionales en vez de 1."""
"Frequency Jammer":
name: "Inhibidor de Frecuencias"
text: """Cuando lleves a cabo una acción de intereferencia, elige 1 nave enemiga que no tenga fichas de Tensión y se encuentre a alcance 1 de la nave interferida. La nave elegida recibe una ficha de Tension."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques, si tienes la defensor fijado como blanco, puedes gastar esa ficha de Blanco Fijado para cambiar todos tus resultados de %FOCUS% por resultados de %HIT%."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al comienzo de la fase de Activación, puedes descartar esta carta para que todas las naves aliadas que muestren una maniobra roja seleccionada la traten como si fuera una maniobra blanca hasta el final de la fase."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al comiuenzo de la fase de Activación, elige 1 nave enemiga que tengas a alcance 1-3. Puedes mirar su selector de maniobras. Si ha seleccionado una maniobra blanca, adjudica 1 ficha de Tensión a esa nave."""
"Gunnery Team":
name: "PI:NAME:<NAME>END_PI"
text: """Una vez por ronda, cuando ataques con un armamento secudario, puedes gastar 1 de Energía para cambiar 1 cara de dado vacía por 1 resultado de %HIT%."""
"Sensor Team":
name: "Equipo de Control de Sensores"
text: """Cuando fijes un blanco, puedes fijar como blanco una nave enemiga a alcance 1-5 (en lugar de 1-3)."""
"Engineering Team":
name: "Equipo de Ingeniería"
text: """Durante la fase de Activación, si enseñas una maniobra %STRAIGHT%, recibes 1 de Energía adicional durante el paso de "Obtener Energía"."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Tira 2 dados de defensa. Por cada %FOCUS% que saques, asigna 1 ficha de Concentración a tu nave. Por cada resultado de %EVADE% que saques, asigna 1 ficha de Evasión a tu nave."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Al final de la fase de Combate, toda nave enemiga situada a alcance 1 que no tenga 1 ficha de Tensión recibe 1 ficha de Tensión."""
"Fleet Officer":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Elige un máximo de 2 naves aliadas que tengas a alcance 1-2 y asigna 1 ficha de Concentración a cada una de ellas. Luego recibes 1 ficha de Tensión."""
"LPI:NAME:<NAME>END_PI Wolf":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques o defiendas, si no tienes ninguna otra nave aliada a alcance 1-2, pues volver a tirar 1 dado en el que hayas sacado una cara vacía."""
"Stay On Target":
name: "Seguir al Objetivo"
text: """Cuando reveles una maniobra, puedes girar tu selector para escoger otra maniobra que tenga la misma velocidad.<br /><br />Tu maniobra se considera roja."""
"Dash Rendar":
text: """Puedes efectuar ataques mientras estés solapado con un obstáculo.<br /><br />Tus ataques no pueden ser obstruidos."""
'"Leebo"':
text: """<strong>Acción:</strong> Realiza una acción gratuita de Impulso. Después recibes 1 marcador de Iones."""
"Ruthlessness":
name: "PI:NAME:<NAME>END_PI"
text: """Después de que efectúes un ataque que impacte, <strong>debes</strong> elegir otra nave situada a alcance 1 del defensor (exceptuando la tuya). Esa nave sufre 1 daño."""
"IntPI:NAME:<NAME>END_PIation":
name: "PI:NAME:<NAME>END_PI"
text: """Mientras estes en contacto con una nave enemiga, la Agilidad de esa nave se reduce en 1."""
"PI:NAME:<NAME>END_PI":
text: """Al comienzo de la fase de Combate, si no te quedan Escudos y tu nave tiene asignada al menos 1 carta de Daño, puedes realizar una acción gratuita de Evasión."""
"PI:NAME:<NAME>END_PI":
text: """Cuando recibas una carta de Daño boca arriba, puedes descartar esta carta de Mejora u otra carta de %CREW% para poner boca abajo esa carta de Daño sin resolver su efecto."""
"Ion Torpedoes":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco Fijado):</strong> Gasta tu ficha de Blanco Fijado y descarta esta carta para efectuar este ataque.<br /><br />Si este ataque impacta, el defensor y toda nave que esté a alcance 1 reciben 1 ficha de Iones cada una."""
"Bomb Loadout":
name: "Compartimento de Bombas"
text: """<span class="card-restriction">Solo ala-Y.</span><br /><br />Tu barra de mejoras gana el icono %BOMB%."""
ship: "Ala-Y"
"Bodyguard":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%<br /><br />Al principio de la fase de Combate, puedes gastar 1 ficha de Concentración para elegir 1 nave aliada situada a alcance 1 cuyo piloto tenga una Habilidad más alta que la tuya. Hasta el final de la ronda, la puntuación de Agilidad de esa nave se incrementa en 1."""
"Calculation":
name: "Planificación"
text: """Cuando ataques, puedes gastar 1 ficha de Concentración para cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
"Accuracy Corrector":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques, durante el paso "Modificar la tirada de ataque", puedes anular los resultados de todos tus dados. Después puedes añadir 2 resultados %HIT% a tu tirada.<br /><br />Si decides hacerlo, no podrás volver a modificar tus dados durante este ataque."""
"Inertial Dampeners":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando reveles tu maniobra, puedes descartar esta carta para ejecutar en su lugar una maniobra blanca [0%STOP%]. Después recibes 1 ficha de Tensión."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, el defensor sufre 1 de daño y, si no tiene asignada ninguna ficha de Tensión, recibe también 1 ficha de Tensión. Después se anulan <strong>todos</strong> los resultados de los dados."""
'"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI':
name: 'CaPI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI"'
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Durante este ataque, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%."""
"Dead Man's Switch":
name: "Dispositivo de Represalia"
text: """Cuando seas destruido, toda nave que tengas a alcance 1 sufre 1 daño."""
"Feedback Array":
name: "Transmisor de Sobrecargas"
text: """Durante la fase de Combate, en vez de efectuar ataques, puedes recibir 1 ficha de Iones y sufrir 1 daño para elegir 1 nave enemiga a alcance 1. Esa nave sufre 1 daño."""
'"Hot Shot" Blaster':
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque:</strong> Descarta esta carta para atacar a 1 nave (aunque esté fuera de tu arco de fuego)."""
"Greedo":
text: """%SCUMONLY%<br /><br />La primera vez que ataques cada ronda y la primera vez que te defiendas cada ronda, la primera carta de Daño inflingida será asignada boca arriba."""
"Outlaw Tech":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%<br /><br />Después de que ejecutes una maniobra roja, puedes asignar 1 ficha de Concentración a tu nave."""
"K4 Security Droid":
name: "Droide de Seguridad K4"
text: """%SCUMONLY%<br /><br />Después de que ejecutes una maniobra verde, puedes fijar un blanco."""
"Salvaged Astromech":
name: "Droide Astromecánico Remendado"
text: """Cuando recibas una carta de Daño boca arriba con el atributo <strong>Nave</strong>, puedes descartarla de inmediato (antes de resolver sus efectos).<br /><br />Luego descarta esta carta de Mejora."""
'"GenPI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """Si estás equipado con una bomba que puede soltarse cuando revelas tu selector de maniobras, puedes elegir soltar la bomba <strong>después</strong> de ejecutar tu maniobra."""
"Unhinged Astromech":
name: "Droide Astromecánico Desquiciado"
text: """Puedes ejecutar todas las maniobras de velocidad 3 como maniobras verdes."""
"R4 Agromech":
name: "Droide Agromecánico R4"
text: """Cuando ataques, después de gastar una ficha de Concentración puedes fijar al defensor como blanco."""
"R4-B11":
text: """Cuando ataques, si tienes al defensor fijado como blanco, puedes gastar la ficha de Blanco Fijado para elegir cualquier o todos sus dados de defensa. El defensor debe volver a tirar los dados elegidos."""
"Autoblaster Turret":
name: "Torreta de Bláster Automático"
text: """<strong>Ataque:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).<br /><br />Tus resultados %HIT% no pueden ser anulados por los dados de defensa.<br /><br />El defensor puede anular tus resultados %CRIT% antes que los %HIT%."""
"Advanced Targeting Computer":
ship: "TIE Avanzado"
name: "Computadora de Selección de Blancos Avanzada"
text: """<span class="card-restriction">Solo TIE Avanzado.</span>%LINEBREAK%Cuando ataques con tu armamento principal, si tienes al defensor fijado como blanco, puedes añadir 1 %CRIT% al resultado de tu tirada. Si decides hacerlo, no podrás gastar fichas de Blanco Fijado durante este ataque."""
"Ion Cannon Battery":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque. Si este ataque impacta, el defensor sufre 1 de daño crítico y recibe 1 ficha de Iones. Después se anulan <strong>todos<strong> los resultados de los dados."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%IMPERIALONLY%%LINEBREAK%Una vez por ronda, antes de que una nave aliada vaya a tirar dados, puedes decir un resultado de dado. Tras tirarlos, se debe cambiar 1 de los resultados obtenidos por el resultado elegido antes. El resultado de ese dado no podrá volver a ser modificado."""
"BossPI:NAME:<NAME>END_PI":
text: """%SCUMONLY%%LINEBREAK%Después de que realices un ataque y falles, si no tienes fichas de Tensión <strong>debes</strong> recibir 1 ficha de Tensión. Después asigna 1 ficha de Concentración a tu nave y fija al defensor como blanco."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%SMALLSHIPONLY%%LINEBREAK%Después de que ejecutes una maniobra blanca o verde en tu selector, puedes descartar esta carta para rotar tu nave 180º. Luego recibes 1 ficha de Tensión <strong>después</strong> del paso de "comprobar Tensión del piloto."""
"Twin Laser Turret":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque:</strong> Efectúa este ataque <strong>dos veces</strong> (incluso contra una nave situada fuera de tu arco de fuego).<br /><br />Cada vez que este ataque impacte, el defensor sufre 1 de daño. Luego se anulan <strong>todos</strong> los resultados de los dados."""
"Plasma Torpedoes":
name: "PI:NAME:<NAME>END_PI de PlPI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco fijado):</strong> Gasta tu ficha de Blanco fijado y descarta esta carta para efectuar este ataque.<br /><br />Si el ataque impacta, después de inflingir daños quita 1 ficha de Escudos del defensor."""
"Ion Bombs":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Bomba de iones.<br /><br />Esta ficha <strong>detona</strong> al final de la fase de Activación.<br /><br /><strong>Ficha de Bomba de iones:</strong> Cuando se detona esta ficha de Bomba, toda nave que se encuentre a alcance 1 de ella recibe 2 fichas de Iones. Después se descarta esta ficha."""
"Conner Net":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Red Conner.<br /><br />Esta ficha se <strong>detona</strong> cuando la peana o plantilla de maniobra de una nave se solape con ella.<br /><br /><strong>Ficha de Red Conner:</strong> Cuando es detona esta ficha de Bomba, la nave que la haya atravesado o solapado sufre 1 daño, recibe 2 fichas de Iones y se salta su paso de "Realizar una acción". Después se descarta esta ficha."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando sueltes una bomba, puedes usar la plantilla (%STRAIGHT% 2) en lugar de la plantilla (%STRAIGHT% 1)."""
"Cluster Mines":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 conjunto de Minas de racimo.<br /><br />Cada ficha de Mina de racimo se <strong>detona</strong> cuando la peana o plantilla de maniobra de una nave se solapa con ella.<br /><br /><strong>Ficha de Mina de racimo:</strong> Cuando se detona una de estas fichas de Bomba, la nave que la haya atravesado o solapado tira 2 dados de ataque y sufre 1 punto de daño por cada %HIT% o %CRIT% obtenido en la tirada. Después se descarta esta ficha."""
'PI:NAME:<NAME>END_PIack Shot':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando ataques a una nave situada dentro de tu arco de fuego, al comienzo del paso "Comparar los resultados", puedes descartar esta carta para anular 1 resultado %EVADE% del defensor.'''
"Advanced Homing Missiles":
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efectuar este ataque.%LINEBREAK%Si el ataque impacta, inflinge 1 carta de Daño boca arriba al defensor. Luego se anulan <strong>todos</strong> los resultados de los dados."""
'Agent KPI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%IMPERIALONLY%%LINEBREAK%Al comienzo de la primera ronda, elige 1 nave enemiga pequeña o grande. Cuando ataques a esa nave o te defiendas de esa nave, puedes cambiar 1 de tus resultados %FOCUS% por un resultado %HIT% o %EVADE%.'''
'XX-23 S-Thread Tracers':
name: "Hiperrastreadores XX-23"
text: """<strong>Ataque (Concentración):</strong> Descarta esta carta para efectuar este ataque. Si este ataque impacta, toda nave aliada que tengas a alcance 1-2 puede fijar al defensor como blanco. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Tractor Beam":
name: "Proyector de Campo de Tracción"
text: """<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, el defensor recibe 1 ficha de Campo de Tracción. Después se anulan <strong>todos</strong> los resultados de los dados."""
"Cloaking Device":
name: "Dispositivo de Camuflaje"
text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Acción:</strong> Realiza una acción gratuita de camuflaje.%LINEBREAK%Al final de cada ronda, si estás camuflado, tira 1 dado de ataque. Si sacas %FOCUS%, descarta esta carta y luego elige entre desactivar el camuflaje o retirar tu ficha de Camuflaje."""
"Shield Technician":
name: "Técnico de Escudos"
text: """%HUGESHIPONLY%%LINEBREAK%Cuando lleves a cabo una acción de recuperación, en vez de retirar todas tus fichas de Energía, puedes elegir qué cantidad de fichas de Energía deseas retirar."""
"Grand Moff Tarkin":
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Al comienzo de la fase de Combate, puedes elegir otra nave que tengas a alcance 1-4. Escoge entre retirar 1 ficha de Concentración de la nave elegida o asignarle 1 ficha de Concentración a esa nave."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%Si durante la fase de Activación te solapas con un obstáculo, en vez de recibir 1 carta de Daño boca arriba, tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, sufres 1 de daño."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%HUGESHIPONLY%%IMPERIALONLY%%LINEBREAK%<strong>ENERGÍA</strong>: Puedes descartar hasta 3 fichas de Escudos de tu nave. Por cada ficha de Escudos descartada, obtienes 1 de Energía."""
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """Al comienzo de la fase de Combate, puedes descartar esta carta y recibir 1 ficha de Tensión. Si lo haces, hasta el final de la ronda, cuando ataques o defiendes puedes cambiar todos tus resultados %FOCUS% por resultados %HIT% o %EVADE%."""
'Extra Munitions':
name: "MunicPI:NAME:<NAME>END_PI API:NAME:<NAME>END_PI"
text: """Cuando te equipas con esta carta, coloca 1 ficha de Munición de artillería sobre cada carta de Mejora %TORPEDO%, %MISSILE% y %BOMB% que tengas equipada. Cuando se te indique que descartes una carta de Mejora, en vez de eso puedes descartar 1 ficha de Munición de artillería que haya encima de esa carta."""
"Weapons Guidance":
name: "Sistema de Guiado de Armas"
text: """Cuando ataques, puedes gastar una ficha de Concentración para cambiar 1 de tus resultados de cara vacia por un resultado %HIT%."""
"BB-8":
text: """Cuando reveles una maniobra verde, puedes realizar una acción gratuita de tonel volado."""
"R5-X3":
text: """Antes de revelar tu maniobra, puedes descartar esta carta para ignorar todos los obstáculos hasta el final de la ronda."""
"Wired":
name: "PI:NAME:<NAME>END_PI"
text: """Cuando ataques o te defiendas, si estás bajo tensión, puedes volver a tirar 1 o más de tus resultados %FOCUS%."""
'Cool Hand':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando recibas una ficha de Tensión, puedes descartar esta carta para asignar 1 ficha de Concetración o de Evasión a tu nave.'''
'Juke':
name: "PI:NAME:<NAME>END_PI"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando ataques, si tienes una ficha de Evasión, puedes cambiar 1 de los resultados %EVADE% del defensor por un resultado %FOCUS%.'''
'Comm Relay':
name: "Repetidor de Comunicaciones"
text: '''No puedes tener más de 1 ficha de Evasión.%LINEBREAK%Durante la fase Final, no retires de tu nave las fichas de Evasión que no hayas usado.'''
'Dual Laser Turret':
text: '''%GOZANTIONLY%%LINEBREAK%<strong>Attack (energy):</strong> Spend 1 energy from this card to perform this attack against 1 ship (even a ship outside your firing arc).'''
'Broadcast Array':
text: '''%GOZANTIONLY%%LINEBREAK%Your action bar gains the %JAM% action icon.'''
'Rear Admiral ChPI:NAME:<NAME>END_PIaneau':
text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Execute a white (%STRAIGHT% 1) maneuver.'''
'Ordnance Experts':
text: '''Once per round, when a friendly ship at Range 1-3 performs an attack with a %TORPEDO% or %MISSILE% secondary weapon, it may change 1 of its blank results to a %HIT% result.'''
'Docking Clamps':
text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%You may attach 4 up to TIE fighters, TIE interceptors, TIE bombers, or TIE Advanced to this ship. All attached ships must have the same ship type.'''
'"Zeb" Orrelios':
text: """%REBELONLY%%LINEBREAK%Las naves enemigas dentro de tu arco de fuego que estén en contacto contigo no se consideran en contacto contigo cuando tú o ellas os activéis durante la fase de Combate."""
'PI:NAME:<NAME>END_PI':
text: """%REBELONLY%%LINEBREAK%Una vez por ronda, después de que una nave aliada que tengas a alcance 1-2 ejecute una maniobra blanca, puedes quitar 1 ficha de Tensión de esa nave."""
'Reinforced Deflectors':
name: "Deflectores Reforzados"
text: """%LARGESHIPONLY%%LINEBREAK%Tras defenderte, su durante el ataque has sufrido una combinación de 3 o más puntos de daño normal y crítico, recuperas 1 ficha de Escudos (hast aun máximo igual a tu valor de Escudos)."""
'Dorsal Turret':
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Ataque:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).%LINEBREAK%Si el objetivo de este ataque está a alcance 1, tiras 1 dado de ataque adicional."""
'Targeting Astromech':
name: "Droide Astromecánico de Selección de Blancos"
text: '''Después de que ejecutes una maniobra roja, puedes fijar un blanco.'''
'Hera SyndullPI:NAME:<NAME>END_PI':
text: """%REBELONLY%%LINEBREAK%Puedes revelar y ejectuar maniobras rojas incluso aunque estés bajo tensión."""
'PI:NAME:<NAME>END_PI':
text: """%REBELONLY%%LINEBREAK%Cuando ataques, si estás bajo tensión puedes cambiar 1 de tus resultados %FOCUS% por un resultado %CRIT%."""
'PI:NAME:<NAME>END_PI':
text: """%REBELONLY%%LINEBREAK%Tu barra de mejoras gana el icono %BOMB%. Una vez por ronda, antes de retirar una ficha de Bomba aliada, elige 1 nave enemiga situada a Alcance 1 de esa ficha. Esa nave sufre 1 de daño."""
'"ChPI:NAME:<NAME>END_PI"':
text: """%REBELONLY%%LINEBREAK%Puedes realizar acciones incluso aunque estés bajo tensión.%LINEBREAK%Después de que realices una acción mientras estás bajo tensión, sufres 1 de daño."""
'Construction Droid':
text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%When you perform a recover action, you may spend 1 energy to discard 1 facedown Damage card.'''
'Cluster Bombs':
text: '''After defending, you may discard this card. If you do, each other ship at Range 1 of the defending section rolls 2 attack dice, suffering all damage (%HIT%) and critical damage (%CRIT%) rolled.'''
"Adaptability":
name: "Adaptabilidad"
text: """<span class="card-restriction">Carta dual.</span>%LINEBREAK%<strong>Cara A:</strong> La Habilidad de tu piloto se incrementa en 1.%LINEBREAK%<strong>Cara B:</strong> La habilidad de tu piloto se reduce en 1."""
"Electronic Baffle":
name: "Regulador Electrónico"
text: """Cuando recibas una ficha de Tensión o una ficha de Iones, puedes sufrir 1 de daño para descartar esa ficha."""
"4-LOM":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, durante el paso "Modificar la tirada de ataque" puedes recibir 1 ficha de Iones para elegir 1 de las fichas de Concentración o Evasión del defensor. Esa ficha no se puede gastar durante este ataque."""
"PI:NAME:<NAME>END_PI":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, si no estás tensionado, puedes recibir tantas fichas de Tensión como quieras para elegir una cantidad igual de dados de defensa. El defensor debe volver a tirar esos dados."""
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: """<strong>Acción:</strong> Asigna 1 ficha de Concentración a tu nave y recibe 2 fichas de Tensión. Hasta el final de la ronda, cuando ataques puedes volver a tirar hasta 3 dados de ataque."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """%SCUMONLY%%LINEBREAK%Cada vez que se te asigne una ficha de Concentración o de Tensión, a todas las demás naves aliadas equipadas con "Enlace Mental Attani" se les debe asignar también una ficha de ese mismo tipo si es que no tienen ya una."""
"PI:NAME:<NAME>END_PI":
text: """%SCUMONLY%%LINEBREAK%Después de que efectúes un ataque, si al defensor se le infligió una carta de Daño boca arriba, puedes descartar esta carta para elegir y descartar 1 de las cartas de Mejora del defensor."""
"PI:NAME:<NAME>END_PI":
text: """%SCUMONLY%%LINEBREAK%Cuando ataques, puedes volver a tirar 1 dado de ataque. Si el defensor es un piloto único, en vez de eso puedes volver a tirar hasta 2 dados de ataque."""
'"PI:NAME:<NAME>END_PI"':
name: '"PI:NAME:<NAME>END_PI"'
text: """%SCUMONLY%%LINEBREAK%<strong>Acción:</strong> Coloca 1 ficha de Escudos sobre esta carta.%LINEBREAK%<strong>Acción:</strong> Quita 1 ficha de Escudos de esta carta para recupera 1 de Escudos (hast aun máximo igual a tu valor de Escudos)."""
"R5-P8":
text: """Una vez por ronda, después de que te defiendas puedes volver a tirar 1 dado de ataque. Si sacas %HIT%, el atacante sufre 1 de daño. Si sacas %CRIT%, tanto tú como el atacante sufrís 1 de daño."""
'Thermal Detonators':
name: "PI:NAME:<NAME>END_PIonadores Térmicos"
text: """Cuando reveles tu selector de maniobras, puedes descartar esta carta para <strong>soltar</strong> 1 ficha de Detonador térmico.%LINEBREAK%Esta ficha se <strong>detona</strong> al final de la fase de Activación.%LINEBREAK%<strong>Ficha de Detonador Térmico:</strong> Cuando esta bomba detona, cada nave a Alcance 1 de la ficha sufre 1 de daño y recibe 1 ficha de tensión. Después, descarta esta ficha."""
"Overclocked R4":
name: "Droide R4 trucado"
text: """Durante la fase de Combate, cuando gastes una ficha de Concentración puedes recibir 1 ficha de Tensión para asignar 1 ficha de Concentración a tu nave."""
'Systems Officer':
name: "Oficial de Sistemas"
text: '''%IMPERIALONLY%%LINEBREAK%Después de que ejecutes una maniobra verde, elige otra nave aliada que tengas a alcance 1. Esa nave puede fijar un blanco.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando ataques desde tu arco de fuego auxiliar trasero, la Agilidad del defensor se reduce en 1 (hasta un mínimo de 0).'''
'R3 Astromech':
name: "Droide astromecánico R3"
text: '''Una vez por ronda, cuando ataques con un armamento principal, durante el paso "Modificar la tirada de ataque" puedes anular 1 de tus resultados %FOCUS% para asignar 1 ficha de Evasión a tu nave.'''
'Collision Detector':
name: "Detector de colisiones"
text: '''Cuando realices un impulso, un tonel volado o desactives tu camuflaje, tu nave y plantilla de maniobra se pueden solapar con obstáculos.%LINEBREAK%Cuando hagas una tirada de dados para determinar el daño causado por obstáculos, ignora todos tus resultados %CRIT%.'''
'Sensor Cluster':
name: "Conjunto de sensores"
text: '''Cuando te defiendas, puedes gastar una ficha de Concentración para cambiar 1 de tus resultados de car avacía por 1 resultado %EVADE%.'''
'Fearlessness':
name: "PI:NAME:<NAME>END_PIrepidePI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%Cuando ataques, si estás dentro del arco de fuego del defensor a alcance 1 y el defensor está dentro de tu arco de fuego, puedes añadir 1 resultado %HIT% a tu tirada.'''
'Ketsu Onyo':
text: '''%SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes elegir 1 nave enemiga que tengas dentro de tu arco de fuego a alcance 1-2. Esa nave no retira sus fichas de Campo de tracción.'''
'Latts Razzi':
text: '''%SCUMONLY%%LINEBREAK%Cuando te defiendas, puedes quitarle al atacante 1 ficha de Tensión para añadir 1 resultado 1 %EVADE% a tu tirada.'''
'IG-88D':
text: '''%SCUMONLY%%LINEBREAK%Tu piloto tiene la misma capacidad especial que cualquier otra nave aliada equipada con la carta de Mejora <em>IG-2000</em> (además de su propia capacidad especial).'''
'Rigged Cargo Chute':
name: "Tolva de evacuación de carga"
text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Acción:</strong> Descarta esta carta para <strong>soltar</strong> 1 ficha de Cargamento.'''
'Seismic Torpedo':
name: "Torpedo sísmico"
text: '''<strong>Acción:</strong> Descarta esta carta para elegir un obstáculo que tengas a alcance 1-2 y dentro de tu arco de fuego normal. Toda nave situada a alcance 1 del obstáculo tira 1 dado de ataque y sufre cualquier daño (%HIT%) o o daño crítico (%CRIT%) otenido. Luego retira el obstáculo.'''
'Black Market Slicer Tools':
name: "Sistemas ilegales de guerra electrónica"
text: '''<strong>Acción:</strong> Elige una nave enemiga bajo tensión que tengas a alcance 1-2 y tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, quítale 1 ficha de Tensión e inflíngele 1 carta de Daño boca abajo.'''
# Wave X
'Kylo Ren':
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Acción:</strong> Asigna la carta de Estado "Yo re mostraré el Lado Oscuro" a una nave enemiga que tengas a alcance 1-3.'''
'PI:NAME:<NAME>END_PI':
text: '''%SCUMONLY%%LINEBREAK%Después de que ejecutes una maniobra que te haga solaparte con una nave enemiga, puedes sufrir 1 de daño para realizar 1 acción gratuita.'''
'A Score to Settle':
name: "Una cuenta pendiente"
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", elige 1 nave enemiga y asígnale la carta de Estado "Una deuda por saldar"%LINEBREAK%Cuando ataques a una nave que tiene asignada la carta de Estado "Una deuda por saldar", puedes cambair 1 resultado %FOCUS% por un resultado %CRIT%.'''
'PI:NAME:<NAME>END_PI':
text: '''%REBELONLY%%LINEBREAK%<strong>Acción:</strong> Elige 1 nave aliada que tengas a alcance 1-2. Asigna 1 ficha de Concentración a esa nave por cada nave enemiga que tengas dentro de tu arco de fuego a alcance 1-3. No puedes asignar más de 3 fichas de esta forma.'''
'PI:NAME:<NAME>END_PI':
text: '''%REBELONLY%%LINEBREAK%Al final de la fase de Planificación, puedes elegir una nave enemiga que tengas a alcance 1-2. Di en voz alta la dirección y velocidad que crees que va a tener esa nave, y luego mira su selector d emaniobras. Si aciertas, puedes girar la rueda de tu selector para asignarle otra maniobra.'''
'FinPI:NAME:<NAME>END_PI':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques con un armamento principal o te defiendas, si la nave enemiga está dentro de tu arco de fuego, puedes añadir 1 resultado de cara vacía a tu tirada.'''
'Rey':
text: '''%REBELONLY%%LINEBREAK%Al comienzo de la fase Final, puedes colocar 1 de las fichas de Concentración de tu nave sobre esta carta. Al comienzo de la fase de Combate, puedes asignar 1 de esas fichas a tu nave.'''
'Burnout SLAM':
name: "Superacelerador de emergencia"
text: '''%LARGESHIPONLY%%LINEBREAK%Tu barra de acciones gana el icono %SLAM%.%LINEBREAK%Después de que realices una acción de MASA, descarta esta carta.'''
'Primed Thrusters':
name: "Propulsores sobrealimentados"
text: '''%SMALLSHIPONLY%%LINEBREAK%Las fichas de Tensión no te impiden realizar acciones de impulso o de tonel volado a menos que tengas asignadas 3 fichas de Tensión o más.'''
'Pattern Analyzer':
name: "Analizador de patrones"
text: '''Cuando ejecutes una maniobra, puedes resolver el paso "Comprobar Tensión del piloto" después del paso "Realizar una acción" (en vez de antes de ese paso).'''
'Snap Shot':
name: "Disparo de reacción"
text: '''Después de que una nave enemiga ejecute una maniobra, puedes efectuar este ataque contra esa nave. <strong>Ataque:</strong> Ataca a 1 nave. No puedes modificar tus dados de ataque y no puedes volver a atacar en esta fase.'''
'M9-G8':
text: '''%REBELONLY%%LINEBREAK%Cuando una nave que tengas fijada como blanco esté atacando, puedes elegir 1 dado de ataque. El atacante debe volver a tirar ese dado.%LINEBREAK%Puedes fijar como blanco otras naves aliadas.'''
'EMP Device':
name: "Dispositivo de pulso electromagnético"
text: '''Durante la fase de Combate, en vez de efecturas ningún ataque, puedes descartar esta carta para asignar 2 fichas de Iones a toda nave que tengas a alcance 1.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
text: '''%REBELONLY%%LINEBREAK%Después de que efectúes un ataque no impacte, puedes asignar 1 ficha de Concentración a tu nave.'''
'General Hux':
text: '''%IMPERIALONLY%%LINEBREAK%<strong>Acción:</strong> Elige hasta 3 naves aliadas que tengas a alcance 1-2. Asigna 1 ficha de Concentración a cada una de esas naves y asigna la carta de Estado "Lealtad fanática" a 1 de ellas. Luego recibes 1 ficha de Tensión.'''
'Operations Specialist':
name: "Especialista en operaciones"
text: '''%LIMITED%%LINEBREAK%Después de que una nave aliada que tengas a alcance 1-2 efectúe un ataque que no impacte, puedes asignar 1 ficha de Concentración a una nave aliada situada a alcance 1-3 del atacante.'''
'Targeting Synchronizer':
name: "Sincronizador de disparos"
text: '''Cuando una nave aliada que tengas a alcance 1-2 ataque a una nave que tienes fijada como blanco, esa nave aliada considera el encabezado "<strong>Ataque (Blanco fijado):</strong> como si fuera "<strong>Ataque:</strong>." Si un efecto de juego indica a esa nave que gaste una ficha de Blanco fijada, en vez de eso puede gastar tu ficha de Blanco fijado.'''
'Hyperwave Comm Scanner':
name: "Escáner de frecuencias hiperlumínicas"
text: '''Al comienzo del paso "Desplegar fuerzas", puedes elegir considerar la Habilidad de tu piloto como si fuera 0, 6 o 12 hasta el final del paso. Durante la preparación de la partida, después de que otra nave aliada sea colocada a alcance 1-2 de ti, puedes asignar 1 ficha de Concentración o Evasión a esa nave.'''
'Trick Shot':
name: "DisPI:NAME:<NAME>END_PI"
text: '''Cuando ataques, si el ataque se considera obstruido, puedes tirar 1 dado de ataque adicional.'''
'Hotshot Co-pilot':
name: "CopPI:NAME:<NAME>END_PI extraordPI:NAME:<NAME>END_PI"
text: '''Cuando ataques con un armamento princnipal, el defensor debe gastar 1 ficha de Concentración si le es posible.%LINEBREAK%Cuando te defiendas, el atacante debe gastar 1 ficha de Concentración si le es posible.'''
'''Scavenger Crane''':
name: "PI:NAME:<NAME>END_PI de PI:NAME:<NAME>END_PI"
text: '''Después de que una nave que tengas a alcance 1-2 sea destruida, puedes elegir una carta de Mejora %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, o Modificación que estuviera equipada en tu nave y ponerla boca arriba. Luego tira 1 dado de ataque. Si sacas una cara vacía, descarta tu "Grúa de salvamento".'''
'BPI:NAME:<NAME>END_PI':
text: '''%REBELONLY%%LINEBREAK%Cuando fijes un blanco, puedes fijarlo sobre una nave enemiga que esté situada a alcance 1-3 de cualquier nave aliada.'''
'Baze Malbus':
text: '''%REBELONLY%%LINEBREAK%Después de que efectúes un ataque que no impacte, puedes realizar inmediatamente un ataque con tu armamento principal contra una nave diferente. No podrás realizar ningún otro ataque en esta misma ronda.'''
'Inspiring Recruit':
name: "PI:NAME:<NAME>END_PI"
text: '''Una vez por ronda, cuando una nave aliada que tengas a alcance 1-2 se quite una ficha de Tensión, puede quitarse 1 ficha de Tensión adicional.'''
'Swarm Leader':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando ataques con un armamento principal, elige hasta 2 ortas naves aliadas que tengan al defensor dentro de sus arcos de fuego a alcance 1-3. Quita 1 ficha de Evasión de cada nave elegida para tirar 1 dado de ataque adicional por cada ficha quitada.'''
'Bistan':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques a alcance 1-2, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%.'''
'Expertise':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando ataques, si no estás bajo tensión, puedes cambair todos tus resultados %FOCUS% por resultados %HIT%.'''
'BoShek':
text: '''Cuando una nave con la que estás en contacto se activa, puedes mirar la maniobra que ha elegido. Si lo haces, el jugador que controla esa nave <strong>debe</strong> elegir en el selector una maniobra adyacente. La nave puede revelar y efectuar esa maniobra incluso aunque esté bajo tensión.'''
# C-ROC
'Heavy Laser Turret':
ship: "Crucero C-ROC"
name: "Torreta de láser pesado"
text: '''<span class="card-restriction">Sólo crucero C-ROC</span>%LINEBREAK%<strong>Ataque (energía):</strong> Gasta 2 de Energía de esta carta para efectuar este ataque contra 1 nave (incluso contra una nave fuera de tu arco de fuego).'''
'CikatPI:NAME:<NAME>END_PI':
text: '''%SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes descartar esta carta pare reemplazar una carta de Mejora %ILLICIT% o %CARGO% que tengas equipada boca arriba por otra carta de Mejora de ese mismo tipo con un coste en puntos de escuadrón igual o inferior.'''
'Azmorigan':
text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%Al comienzo de la fase Final, puedes gastar 1 de Energía para reemplazar una carta de Mejora %CREW% o %TEAM% que tengas equipada boca arriba por otra carta de Mejora de ese mismo tipo con un coste en puntos de escuadrón igual o inferior.'''
'Quick-release Cargo Locks':
name: "Enganches de carga de apertura rápida"
text: '''%LINEBREAK%Al final de la fase de Activación puedes descartar esta carta para <strong>colocar</strong> 1 indicador de Contenedores.'''
'Supercharged Power Cells':
name: "Células de energía sobrealimentadas"
text: '''Cuando ataques, puedes descartar esta carta para tirar 2 dados de ataque adicionales.'''
'ARC Caster':
name: "Proyector ARC"
text: '''<span class="card-restriction">Sólo Escoria y Rebelde.</span>%DUALCARD%%LINEBREAK%<strong>Cara A:</strong>%LINEBREAK%<strong>Ataque:</strong> Ataca a 1 nave. Si este ataque impacta, debes elegir 1 otra nave a alcance 1 del defensor para que sufra 1 punto de daño.%LINEBREAK%Luego dale la vuelta a esta carta.%LINEBREAK%<strong>Cara B:</strong>%LINEBREAK%(Recargándose) Al comienzo de la fase de Combate, puedes recibir una ficha de Armas inutilizadas para darle la vuelta a esta carta.'''
'Wookiee Commandos':
name: "Comandos wookiees"
text: '''Cuando ataques, puedes volver a tirar tus resultados %FOCUS%.'''
'Synced Turret':
name: "Torreta sincronizada"
text: '''<strong>Ataque (Blanco fijado:</strong> Ataca a 1 nave (aunque esté fuera de tu arco de fuego).%LINEBREAK%Si el defensor está dentro de tu arco de fuego principal, puedes volver a tirar tantos dados de ataque como tu valor de Armamento principal.'''
'Unguided Rockets':
name: "Cohetes no guiados"
text: '''<strong>Ataque (Concentración):</strong> Ataca a 1 nave.%LINEBREAK%Tus dados de ataque solo pueden ser modificados mediante el gasto de una ficha de Concentración para su efecto normal.'''
'Intensity':
name: "PI:NAME:<NAME>END_PI"
text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Cara A:</strong> Después de que realices una acción de impulso o de tonel volado, puedes asignar 1 ficha de Concentración o de Evasión a tu nave. Si lo haces, dale la vuelta a esta carta.%LINEBREAK%<strong>Cara B:</strong> (Agotada) Al final de la fase de Combate, puedes gasta 1 ficha de Concentración o de Evasión para darle la vuelta a esta carta.'''
'JPI:NAME:<NAME>END_PIba the Hutt':
name: "PI:NAME:<NAME>END_PI"
text: '''%SCUMONLY%%LINEBREAK%Cuando equipes esta carta, coloca 1 ficha de Material Ilícito encima de cada carta de Mejora %ILLICIT% en tu escuadrón. Cuando debas descartar una carta de Mejora, en vez de eso puedes descartar 1 ficha de Material ilícito que esté encima de esa carta.'''
'IG-RM Thug Droids':
name: "Droides matones IG-RM"
text: '''Cuando ataques, puedes cambiar 1 de tus resultados %HIT% por un resultado %CRIT%.'''
'Selflessness':
name: "AutosPI:NAME:<NAME>END_PI"
text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%Cuando una nave aliada que tengas a alcance 1 sea impactada por un ataque, puedes descartar esta carta para sufrir todos los resultados %HIT% no anulados en vez de la nave objetivo.'''
'Breach Specialist':
name: "Especialista en brechas"
text: '''Cuando recibas una carta de Daño boca arriba, puedes gastar 1 ficha de Refuerzo para darle la vuelta y ponerla boca abajo (sin resolver su efecto). Si lo haces, hasta el final de la ronda, cuando recibas una carta de Daño boca arriba, dale la vuelta par aponerla boca abajo (sin resolver su efecto).'''
'Bomblet Generator':
name: "Generador de minibombas"
text: '''Cuando reveles tu maniobra, puedes <strong>soltar</strong> 1 ficha de Minibomba%LINEBREAK%Esta ficha se <strong>detona</strong> al final de la fase de Activación.%LINEBREAK%<strong>Ficha de Minibomba:</strong> Cuando esta ficha detone, cada nave a Alcance 1 tira 2 dados de ataque y sufre todo el daño (%HIT%) y daño crítico (%CRIT%) obtenido en la tirada. Después se descarta esta ficha.'''
'Cad Bane':
text: '''%SCUMONLY%%LINEBREAK%Tu barra de mejoras gana el icono %BOMB%. Una vez por ronda, cuando una nave enemiga tire dados de ataque debido a la detonación de una bomba aliada, puedes elegir cualquier cantidad de resultados %FOCUS% y de cara vacía. La nave enemiga debe volver a tirar esos resultados.'''
'Minefield Mapper':
name: "Trazador de campos de minas"
text: '''Durante la preparación de la partida, después del paso "Desplegar fuerzas", puedes descartar cualquier cantidad de tus cartas de Mejora %BOMB% equipadas. Coloca las correspondientes fichas de Bomba en la zona de juego más allá de alcance 3 de las naves enemigas.'''
'R4-E1':
text: '''Puedes realizar acciones que figuren en tus cartas de Mejora %TORPEDO% y %BOMB% incluso aunque estés bajo tensión. Después de que realices una acción de esta manera, puedes descartar esta carta para retirar 1 ficha de Tensión de tu nave.'''
'Cruise Missiles':
name: "Misiles de crucero"
text: '''<strong>Ataque (Blanco Fijado):</strong> Descarta esta carta para efectuar este ataque. %LINEBREAK%Puedes tirar tantos dados de ataque adicionales como la velocidad de la maniobra que has ejecutado en esta ronda, hasta un máximo de 4 dados adicionales.'''
'Ion Dischargers':
name: "Descargadores de iones"
text: '''Después de que recibas una ficha de Iones, puedes elegir una nave enemiga que tengas a alcance 1. Si lo haces retira esa ficha de Iones. A continuación, esa nave puede elegir recibir 1 ficha de Iones. Si lo hace, descarta esta carta.'''
'Harpoon Missiles':
name: "Misiles arpón"
text: '''<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efcetuar este ataque.%LINEBREAK%Si este ataque impacta, después de resolver el ataque, asigna el estado "¡Arponeado!" al defensor.'''
'Ordnance Silos':
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando te equipes con esta carta, coloca 3 fichas de Munición de artillería encima de cada otra carta de mejora %BOMB% que tengas equipada. Cuando debas descartar una carta de Mejora, en vez de eso puedes descartar 1 ficha de Munición de artillería que esté encima de esa carta.'''
'Trajectory Simulator':
name: "Simulador de trayectorias"
text: '''Puedes lanzar bombas utilizando la plantilla de maniobra (%STRAIGHT% 5) en vez de soltarlas. No puedes lanzar de esta manera bombas que tengan el encabezado "<strong>Acción:</strong>".'''
'Jamming Beam':
name: "Haz de interferencias"
text: '''<strong>Ataque:</strong> Ataca a 1 nave.%LINEBREAK%Si este ataque impacta, asígnale al defensor 1 ficha de Interferencia. Luego se anulan <strong>todos</strong> los resultados de los dados.'''
'Linked Battery':
name: "Batería enlazada"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando ataques con tu armament principal o con un armamento secundario %CANNON%, puedes volver a tirar 1 dado de ataque.'''
'Saturation Salvo':
name: "Andanada de saturación"
text: '''Después de que efectúes un ataque con un armamento secundario %TORPEDO% o %MISSILE% que no impacte, toda nave que esté situada a alcance 1 del defensor y que tenga una puntuación de Agilidad inferior al coste en puntos de escuadrón de la carta de Meora %TORPEDO% o %MISSILE% debe tirar 1 dado de ataque y sufrir cualquier daño normal (%HIT%) o daño crítico (%CRIT%) obtenido.'''
'Contraband Cybernetics':
name: "Ciberimplantes ilícitos"
text: '''Cuando pases a ser la nave activa durante la fase de Activación, puedes descartar esta carta y recibir 1 ficha de Tensión. Si lo haces, hasta el final de la ornda, puedes llevar a cabo acciones y maniobras rojas incluso aunque estés bajo tensión.'''
'Maul':
text: '''%SCUMONLY% <span class="card-restriction">Ignora esta restricción si tu escuadrón contiene a "Ezra Bridger."</span>%LINEBREAK%Cuando ataques, si no estás bajo tensión, puedes recibir cualquier cantidad de fichas de Tensión para volver a tirar esa misma cantidad de dados de ataque.%LINEBREAK% Después de que realices un ataque que impacte, puedes retirar 1 de tus fichas de Tensión.'''
'Courier Droid':
name: "DPI:NAME:<NAME>END_PI"
text: '''Al comienzo del paso "Desplegar fuerzas", puedes elegir que la puntuación de Habilidad de tu piloto se considere 0 u 8 hasta el final de este paso.'''
'"Chopper" (Astromech)':
text: '''<strong>Acción: </strong>Descarta 1 de tus otras cartas de Mejora equipadas para recuperar 1 ficha de Escudos.'''
'Flight-Assist Astromech':
name: "Droide astromecánico de ayuda al pilotaje"
text: '''No puedes efectuar ataques ataques contra naves que estén situadas fuera de tu arco de fuego.%LINEBREAK%Después de que ejecutes una maniobra, si no te has solapado con una nave ni con un obstáculo, y no tienes ninguna nave enemiga a alcance 1-3 situada dentro de tu arco de fuego, puedes realizar una acción gratuita de impulso o tonel volado.'''
'Advanced Optics':
name: "Sensores ópticos avanzados"
text: '''No puedes tener más de 1 ficha de Concentración.%LINEBREAK%Durante la fase Final, no retires de tu nave las fichas de Concentración que no hayas usado.'''
'Scrambler Missiles':
name: "Misiles interferidores"
text: '''<strong>Ataque (Blanco fijado):</strong> Descarta esta carta para efectuar este ataque.%LINEBREAK%Si este ataque impacta, el defensor y toda otra nave que tenga a alcance 1 recibe 1 ficha de Interferencia. Luego se anulan <strong>todos</strong> los resultados de dados.'''
'R5-TK':
text: '''Puedes fijar como blanco naves aliadas.%LINEBREAK%Puedes efectuar ataques contra naves aliadas.'''
'Threat Tracker':
name: "PI:NAME:<NAME>END_PI"
text: '''%SMALLSHIPONLY%%LINEBREAK%Cuando una nave enemiga que tengas a alcance 1-2 y dentro de tu arco de fuego se convierta en la nave activa durante la fase de Combate, puedes gastar la ficha de Blanco fijado que tengas sobre esa nave para realizar una acción gratuita de impulso o tonel volado, si esa acción figura en tu barra de acciones.'''
'Debris Gambit':
name: "Treta de los desechos"
text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Acción:</strong> Asigna 1 ficha de Evasión a tu nave por cada obstáculo que tengas a alcance 1, hast aun máximo de 2 fichas de Evasión.'''
'Targeting Scrambler':
name: "Interferidor de sistemas de puntería"
text: '''Al comienzo de la fase de Planificación, puedes recibir una ficha de Armas bloqueadas para elegir una nave que tengas a alcance 1-3 y asignarle el Estado "Sistemas interferidos".'''
'Death Troopers':
name: "Soldados de la muerte"
text: '''Después de que otra nave aliada que tengas a alcance 1 se convierta en el defensor, si estás situado a alcance 1-3 del atacante y dentro de su arco de fuego, el atacante recibe 1 ficha de Tensión.'''
'ISB Slicer':
name: "Técnico en guerra electrónica de la OSI"
text: '''%IMPERIALONLY%%LINEBREAK%Después de que realices una acción de interferencia contra una nave enemiga, puedes elegir una nave que esté situada a alcance 1 de esa nave enemiga y no esté interferida, y asignarle 1 ficha de Interferencia.'''
'Tactical Officer':
name: "Oficial táctico"
text: '''%IMPERIALONLY%%LINEBREAK%Tu barra de acciones gana el icono %COORDINATE%.'''
'Saw Gerrera':
text: '''%REBELONLY%%LINEBREAK%Cuando ataques, puedes sufrir 1 de daño para cambiar todos tus resultados %FOCUS% por resultados %CRIT%.'''
'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI':
text: '''Durante la preparación de la partida, antes del paso "Desplegar fuerzas", asigna el Estado "Prototipo optimizado" a una nave aliada del Imperio Galáctico que tenga un valor de Escudos igual o inferior a 3.'''
'PI:NAME:<NAME>END_PI':
text: '''%REBELONLY%%LINEBREAK%Después de que te defiendas, puedes fijar como blanco al atacante.'''
'Renegade Refit':
name: "Reequipado por los Renegados"
text: '''<span class="card-restriction">Sólo T-65 Ala-X y Ala-U.</span>%LINEBREAK%Te puedes equipar con un máximo de 2 mejoras de Modificación distintas.%LINEBREAK%El coste en puntos de escuadrón de cada una de las mejoras %ELITE% que tengas equipadas en tu nave se reduce en 1 (hasta un mínimo de 0).'''
'Thrust Corrector':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando te defiendas, si no tienes asignadas más de 3 fichas de Tensión, puedes recibir 1 ficha de Tensión para anular todos los resultados de tus dados. Si lo haces, añade 1 resultado %EVADE% a tu tirada. No podrás volver a modificar tus dados durante este ataque.%LINEBREAK%Sólo puedes equipar esta Mejora en naves con una puntuación de Casco 4 o inferior.'''
modification_translations =
"Stealth Device":
name: "Dispositivo de Sigilo"
text: """Tu Agilidad se incrementa en 1. Descarta esta carta si eres alcanzado por un ataque."""
"Shield Upgrade":
name: "Escudos Mejorados"
text: """Tu valor de Escudos se incrementa en 1."""
"Engine Upgrade":
name: "Motor Mejorado"
text: """Tu barra de acciones gana el ícono %BOOST%."""
"Anti-Pursuit Lasers":
name: "Cañones Láser Antipersecución"
text: """Después de que una nave enemiga ejecute una maniobra que le cause solapar su peana con la tuya, lanza un dado de ataque. Si el resultado es %HIT% o %CRIT%, el enemigo sufre 1 de daño."""
"Targeting Computer":
name: "Computadora de Selección de Blancos"
text: """Tu barra de acciones gana el icono %TARGETLOCK%."""
"Hull Upgrade":
name: "Blindaje mejorado"
text: """Tu valor de Casco se incrementa en 1."""
"Munitions Failsafe":
name: "Sistema de Munición a Prueba de Fallos"
text: """Cuando ataques con un armamento secundario que requiera descartarlo para efectuar el ataque, no se descarta a menos que el ataque impacte al objetivo."""
"Stygium Particle Accelerator":
name: "Acelerador de Partículas de Estigio"
text: """<span class="card-restriction">Soo TIE Fantasma.</span><br /><br />Cuando realices una acción de camuflaje o desactives tu camuflaje, puedes realizar una acción gratuita de Evasión."""
"Advanced Cloaking Device":
name: "Dispositivo de Camuflaje Avanzado"
text: """Despues de que efectúes un ataque, puedes realizar una acción gratuita de camuflaje."""
ship: "TIE Fantasma"
"Combat Retrofit":
name: "Equipamiento de Combate"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Tu valor de casco se incrementa en 2 y tu valor de escudos se incrementa en 1."""
ship: 'Transporte mediano GR-75'
"B-Wing/E2":
text: """<span class="card-restriction">Solo Ala-B.</span><br /><br />Tu barra de mejoras gana el icono de mejora %CREW%."""
ship: "Ala-B"
"Countermeasures":
name: "Contramedidas"
text: """Al comienzo de la fase de Combate, puedes descartar esta carta para aumentar en 1 tu Agilidad hasta el final de la ronda. Después puedes quitar 1 ficha enemiga de Blanco Fijado de tu nave."""
"Experimental Interface":
name: "Interfaz Experimental"
text: """Una vez por ronda, después de que realices una acción, puedes llevar a cabo 1 acción gratuita de una carta de Mejora equipada que tenga el encabezado "<strong>Acción:</strong>". Después recibes 1 ficha de Tension."""
"Tactical Jammer":
name: "Inhibidor Táctico"
text: """Tu nave puede obstruir ataques enemigos."""
"Autothrusters":
name: "Propulsores Automatizados"
text: """Cuando te defiendas, si estás fuera del arco de fuego del atacante, o dentro de su arco de fuego pero más allá de alcance 2, puedes cambiar 1 de tus resultados de cara vacía por un resultado %EVADE%. Sólo puedes equiparte con esta carta si tienes el icono de acción %BOOST%."""
"Twin Ion Engine Mk. II":
name: "Motor Iónico Doble Modelo II"
text: """<span class="card-restriction">Solo TIE.</span>%LINEBREAK%Puedes tratar todas las maniobras de inclinación (%BANKLEFT% y %BANKRIGHT%) como si fueran maniobras verdes."""
"Maneuvering Fins":
name: "Alerones de Estabilización"
text: """<span class="card-restriction">Solo YV-666.</span>%LINEBREAK%Cuando reveles una maniobra de giro (%TURNLEFT% o %TURNRIGHT%), puedes rotar tu selector para elegir en su lugar la maniobra de inclinación correspondiente (%BANKLEFT% o %BANKRIGHT%) de igual velocidad."""
"Ion Projector":
name: "Proyector de Iones"
text: """%LARGESHIPONLY%%LINEBREAK%Después de que una nave enemiga ejecute una maniobra que la solape con tu nave, tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, la nave enemiga recibe 1 ficha de Iones."""
"Advanced SLAM":
name: "Motor Sublumínico Avanzado"
text: """Después de efectuar una acción de MASA, si no te has solapado con un obstáculo ni con otra nave, puedes llevar a cabo una acctión gratuita."""
'Integrated Astromech':
name: "Droide Astromecánico Integrado"
text: '''<span class="card-restriction">Solo X-wing.</span>%LINEBREAK%Cuando recibas una carta de Daño, puedes descartar 1 de tus cartas de Mejora %ASTROMECH% para descartar esa carta de Daño (sin resolver su efecto).'''
'Optimized Generators':
name: "Generadores optimizados"
text: '''%HUGESHIPONLY%%LINEBREAK%Una vez por ronda, cuando asignes Energía a una carta de Mejora equipada, obtienes 2 de Energía.'''
'Automated Protocols':
name: "Procedimientos automatizados"
text: '''%HUGESHIPONLY%%LINEBREAK%OUna vez por ronda, después de que realices una acción que no sea una acción de recuperación o de refuerzo, puedes gastar 1 de Energía para realizar una acción gratuita de recuperación o de refuerzo.'''
'Ordnance Tubes':
text: '''%HUGESHIPONLY%%LINEBREAK%You may treat each of your %HARDPOINT% upgrade icons as a %TORPEDO% or %MISSILE% icon.%LINEBREAK%When you are instructed to discard a %TORPEDO% or %MISSILE% Upgrade card, do not discard it.'''
'Long-Range Scanners':
name: "Sensores de Largo Alcance"
text: '''Puedes fijar como blanco naves que tengas a alcance 3 o superior. No puedes fijar como blanco naves que tengas a alcance 1-2. Para poder equipar esta carta has de tener los iconos de mejora %TORPEDO% y %MISSILE% en tu barra de mejoras.'''
"Guidance Chips":
name: "Chips de Guiado"
text: """Una vez por ronda, cuando ataques con un sistema de armamento secundario %TORPEDO% o %MISSILE%, puedes cambiar 1 de tus resultados de dado por un resultado %HIT% (o por un resultad %CRIT% si tu valor de Armamento principal es de 3 o más)."""
'Vectored Thrusters':
name: "Propulsores vectoriales"
text: '''%SMALLSHIPONLY%%LINEBREAK%Tu barra de acciones gana el icono de acción %BARRELROLL%.'''
'Smuggling Compartment':
name: "Compartimento para contrabando"
text: '''<span class="card-restriction">Sólo YT-1300 y YT-2400.</span>%LINEBREAK%Tu barra de mejoras gana el icono %ILLICIT%.%LINEBREAK%Puedes equipar 1 mejora de Modificación adicional que no cueste más de 3 puntos de escuadrón.'''
'Gyroscopic Targeting':
name: "Estabilización giroscópica"
ship: "Nave de persecución clase Lancero"
text: '''<span class="card-restriction">Sólo Nave de persecución clase Lancero.</span>%LINEBREAK%Al final de la fase de Combate, si en esta ronda ejecutaste una maniobra de velocidad 3, 4 o 5, puedes reorientar tu arco de fuego móvil.'''
'Captured TIE':
ship: "Caza TIE"
name: "TIE capturado"
text: '''<span class="card-restriction">Sólo Caza TIE.</span>%REBELONLY%%LINEBREAK%Las naves enemigas cuyos pilotos tengan una Habilidad más baja que la tuya no pueden declararte como blanco de un ataque. Después de que efectúes un ataque o cuando seas la única nave aliada que queda en juego, descarta esta carta.'''
'Spacetug Tractor Array':
name: "Campos de tracción de remolque"
ship: "Saltador Quad"
text: '''<span class="card-restriction">Sólo Saltador Quad.</span>%LINEBREAK%<strong>Acción:</strong> Elige una nave que tengas dentro de tu arco de fuego a distancia 1 y asígnale una ficha de Campo de tracción. Si es una nave aliada, resuelve el efecto de la ficha de Campo de tracción como si se tratara de una nave enemiga.'''
'Lightweight Frame':
name: "Fuselaje ultraligero"
text: '''<span class="card-restriction">Sólo TIE.</span>%LINEBREAK%Cuando te defiendas, tras tirar los dados de defensa, si hay más dados de ataque que dados de defensa, tira 1 dado de defensa adicional.%LINEBREAK%Esta mejora no puede equiparse en naves con puntuación de Agilidad 3 o superior.'''
'Pulsed Ray Shield':
name: "Escudo de rayos pulsátil"
text: '''<span class="card-restriction">Sólo Escoria y Rebelde.</span>%LINEBREAK%Durante la fase Final, puedes recibir 1 ficha de Iones para recuperar 1 ficha de Escudos (pero no puedes exceder tu valor de Escudos). Sólo puedes equipar esta carta si tu valor de Escudos es 1.'''
'Deflective Plating':
name: "Blindaje deflector de impactos"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando una bomba aliada se detone, puedes elegir no sufrir sus efectos. Si lo haces, tira un dado de ataque. Si sacas %HIT%, descarta esta carta.'''
'Servomotor S-Foils':
name: "PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Sólo T-65 Ala-X.</span> %DUALCARD%%LINEBREAK%<strong>Cara A (Ataque):</strong>Tu barra de acciones gana el icono %BARRELROLL%. Si no estás bajo tensión, cuando reveles una maniobra (%TURNLEFT% 3) o (%TURNRIGHT% 3), puedes considerarla como si fuera una maniobra roja (%TROLLLEFT% 3) o (%TROLLRIGHT% 3) con la misma dirección.%LINEBREAK%Al comienzo de la fase de Activación, puedes darle la vuelta a esta carta.%LINEBREAK%<strong>Cara B (Cerrada):</strong>Tu valor de Armamento principal se reduce en 1. Tu barra de acciones gana el icono %BOOST%. Tus maniobras (%BANKLEFT% 2) y (%BANKRIGHT% 2 ) se consideran verdes.%LINEBREAK%Al comienzo de la fase de Activacion, puedes darle la vuelta a esta carta.'''
'Multi-spectral Camouflage':
name: "Camuflaje multiespectral"
text: '''%SMALLSHIPONLY%%LINEBREAK%Después de que recibas una ficha roja de Blanco fijado, si sólo tienes asignada 1 ficha roja de Blanco fijado, tira 1 dado de defensa. Si obtienes un resultado %EVADE%, retira esa ficha roja de Blanco fijado.'''
title_translations =
"Slave I":
name: "Esclavo 1"
text: """<span class="card-restriction">Solo Firespray-31.</span><br /><br />Tu barra de mejoras gana el icono %TORPEDO%."""
"Millennium Falcon":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo YT-1300.</span><br /><br />Tu barra de acciones gana el icono %EVADE%."""
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo HWK-290.</span><br /><br />Durante la fase Final, no retires de tu nave las fichas de Concentración que no hayas usado."""
"ST-321":
text: """<span class="card-restriction">Solo Lanzadera clase <em>Lambda</em>.</span><br /><br />Cuando fijas un blanco, puedes hacerlo con cualquier nave enemiga de la zona de juego."""
ship: "Lanzadera clase Lambda"
"Royal Guard TIE":
name: "TIE de la Guardia Real"
ship: "Interceptor TIE"
text: """<span class="card-restriction">Solo TIE Interceptor.</span><br /><br />Puedes equipar un máximo de 2 mejoras distintas de Modificación (en vez de 1).<br /><br />Esta mejora no puede equiparse en naves con pilotos de Habilidad 4 o inferior."""
"DodPI:NAME:<NAME>END_PI's Pride":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />Cuando realices una accion de Coordinación, puedes elegir 2 naves aliadas en vez de 1. Cada una de estas naves pueden realizar 1 accion gratuita."""
ship: "Corbeta CR90 (Proa)"
"A-Wing Test Pilot":
name: "Piloto de Ala-A experimental"
text: """<span class="card-restriction">Solo Ala-A.</span><br /><br />Tu barra de mejoras gana 1 icono de mejora %ELITE%.<br /><br />No puedes equipar 2 cartas de Mejora %ELITE% iguales. Tampoco te puedes equipar con esta carta si la Habilidad de tu piloto es 1 o inferior."""
ship: "Ala-A"
"Tantive IV":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />La barra de mejoras de tu sección de proa gana 1 icono adicional de %CREW% y 1 icono adicional de %TEAM%."""
ship: "Corbeta CR90 (Proa)"
"BPI:NAME:<NAME>END_PI Hope":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Una ficha de Refuerzo asignada a tu seccion de proa añade 2 resultados de %EVADE% en vez de 1."""
ship: 'Transporte mediano GR-75'
"Quantum Storm":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo GR-75.</span><br /><br />Al principio de la fase Final, si tienes 1 ficha de Energía o menos, ganas 1 ficha de Energía."""
ship: 'Transporte mediano GR-75'
"Dutyfree":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo GR-75./span><br /><br />Cuando realices una acción de Interferencia, puedes elegir una nave enemiga situada a alcance 1-3 en lugar de 1-2."""
ship: 'Transporte mediano GR-75'
"Jaina's Light":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo sección de proa de CR90.</span><br /><br />Cuando te defiendas, una vez por ataque, si recibes una carta de Daño boca arriba, puedes descartarla y robar otra carta de Daño boca arriba."""
"Outrider":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo YT-2400.</span><br /><br />Mientras tu nave tenga equipada una mejora de %CANNON%, <strong>no puedes</strong> atacar con tu armamento principal y puedes atacar con armamentos secundarios %CANNON% contra naves enemigas fuera de tu arco de fuego."""
"Andrasta":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo Firespray-31.</span><br /><br />Tu barra de mejoras gana 2 iconos %BOMB% adicionales."""
"TIE/x1":
ship: "TIE Avanzado"
text: """<span class="card-restriction">Solo TIE Avanzado.</span>%LINEBREAK%Tu barra de mejoras gana el icono %SYSTEM%.%LINEBREAK%Si te equipas con una mejora %SYSTEM%, su coste en puntos de escuadrón se reduce en 4 (hasta un mínimo de 0)."""
"BTL-A4 Y-PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo Ala-Y.</span><br /><br />No puedes atacar naves que estén fuera de tu arco de fuego. Después de que efectúes un ataque con tu armamento principal, puedes realizar inmediatamente un ataque con arma secundaria %TURRET%."""
ship: "Ala-Y"
"IG-2000":
name: "IG-2000"
text: """<span class="card-restriction">Solo Agresor.</span><br /><br />Tu piloto tiene la misma capacidad especial que cualquier otra nave aliada equipada con la carta de Mejora <em>IG-2000</em> (además de su propia capacidad especial)."""
ship: "Agresor"
"Virago":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo Víbora Estelar.</span><br /><br />Tu barra de mejoras gana los iconos %SYSTEM% y %ILLICIT%.<br /><br />Esta mejora no puede equiparse en naves con pilotos de Habilidad 3 o inferior."""
ship: 'Víbora Estelar'
'"Heavy Scyk" Interceptor (Cannon)':
name: 'Interceptor "Scyk Pesado" (Cañón)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %CANNON%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
'"Heavy Scyk" Interceptor (Missile)':
name: 'Interceptor "Scyk Pesado" (Misil)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %MISSILE%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
'"Heavy Scyk" Interceptor (Torpedo)':
name: 'Interceptor "Scyk Pesado" (Torpedo)'
text: """<span class="card-restriction">Solo Interceptor M3-A.</span><br /><br />Tu barra de mejoras gana el icono %TORPEDO%. Tu valor de Casco se incrementa en 1."""
ship: 'Interceptor M3-A'
"Dauntless":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo VT-49 Diezmador.</span><br /><br />Después de que ejecutes una maniobra que te solape con otra nave, puedes realizar 1 acción gratuita. Luego recibes 1 ficha de Tensión."""
ship: 'VT-49 Diezmador'
"Ghost":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Sólo VCX-100.</span>%LINEBREAK%Equipa la carta de Título <em>Fantasma</em> a una Lanzadera de ataque aliada y acóplala a esta nave.%LINEBREAK%Después de que ejecutes una maniobra, puedes desplegar la Lanzadera de ataque desde los salientes de la parte trasera de tu peana."""
"Phantom":
name: "PI:NAME:<NAME>END_PI"
text: """Mientras estás acoplado, el <em>Espíritu</em> puede efectuar ataques de armamento principal desde su arco de fuego especial y, al final de la fase de Combate, puede efectuar un ataque adicional con una %TURRET% equipada. Si efectúa este ataque, no puede volver a atacar durante esta ronda."""
ship: 'Lanzadera de Ataque'
"TIE/v1":
text: """<span class="card-restriction">Solo Prototipo de TIE Av.</span>%LINEBREAK%Después de que fijes a un blanco, puedes realizar una acción gratuita de evasión."""
ship: 'Prototipo de TIE Avanzado'
"PI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo Caza Estelar G-1A.</span>%LINEBREAK%Tu barra de acción gana el icono %BARRELROLL%.%LINEBREAK%<strong>Debes</strong> equiparte con 1 carta de Mejora "Proyector de Campo de Tracción" (pagando su coste normal en puntos de escuadrón)."""
ship: 'Caza Estelar G-1A'
"Punishing One":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo Saltador Maestro 5000.</span>%LINEBREAK%Tu valor de Armamento principal se incrementa en 1."""
ship: 'Saltador Maestro 5000'
"PI:NAME:<NAME>END_PIound's Tooth":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Solo YV-666.</span>%LINEBREAK%Después de que seas destruido, y antes de retirarte de la zona de juego, puedes <strong>desplegar</strong> al Piloto del <span>Cachorro de Nashtah</span>.%LINEBREAK%El <span>Cachorro de Nashtah</span> no puede atacar en esta ronda."""
"AssPI:NAME:<NAME>END_PI":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%Cuando te defiendas, si la sección atacada tiene asginada una ficha de Refuerzo, puedes cambiar 1 resultado de %FOCUS% por 1 resultado %EVADE%."""
"Instigator":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%ADespués de que hayas llevado a cabo una acción de recuperación, recuperas 1 de Escudos adicional."""
"Impetuous":
name: "PI:NAME:<NAME>END_PI"
text: """<span class="card-restriction">Sólo sección de popa de corbeta clase <em>Incursor</em>.</span>%LINEBREAK%Después de que hayas efectuado un ataque que destruya una nave enemiga, puedes fijar un blanco."""
'TIE/x7':
text: '''<span class="card-restriction">Sólo TIE Defensor.</span>%LINEBREAK%Tu barra de mejoras pierde los iconos de mejora %CANNON% y %MISSILE%.%LINEBREAK%Después de que ejecutes una maniobra de velocidad 3, 4 o 5, si no te solapaste con un obstáculo o nave, puedes realizar una acción gratuita de evasión.'''
ship: 'Defensor TIE'
'TIE/D':
text: '''<span class="card-restriction">Sólo TIE Defensor.</span>%LINEBREAK%Una vez por ronda, después de que efectúes un ataque con un armamento secundario %CANNON% con un coste en puntos de escuadrón inferior a 4, puedes efcetuar un ataque con tu armamento principal.'''
ship: 'Defensor TIE'
'TIE Shuttle':
name: "PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Sólo TIE Bombardero.</span>%LINEBREAK%Tu barra de mejoras pierde todos los iconos de mejora %TORPEDO%, %MISSILE% y %BOMB% y gana 2 iconos de mejora %CREW%. No puedes equipar ninguna carta de Mejora %CREW% con un coste en puntos de escuadrón superior a 4.'''
ship: 'Bombardero TIE'
'Requiem':
text: '''%GOZANTIONLY%%LINEBREAK%When you deploy a ship, treat its pilot skill value as "8" until the end of the round.'''
'Vector':
text: '''%GOZANTIONLY%%LINEBREAK%After you execute a maneuver, you may deploy up to 4 attached ships (instead of 2).'''
'Suppressor':
text: '''%GOZANTIONLY%%LINEBREAK%Once per round, after you acquire a target lock, you may remove 1 focus, evade, or blue target lock token from that ship.'''
'Black One':
name: "PI:NAME:<NAME>END_PI"
text: '''Después de que realices una acción de impulso o de tonel volado, puedes quitar 1 ficha de Blanco fijado enemiga de una nave aliada que tengas a alcance 1. Esta mejora no puede equiparse en naves con pilotos de Habilidad 6 o inferior.'''
ship: "T-70 Ala-X"
'Millennium Falcon (TFA)':
name: "PI:NAME:<NAME>END_PI (TFA)"
text: '''Después de que ejecutes una maniobra de inclinación (%BANKLEFT% o %BANKRIGHT%) de velocidad 3, si no estás en contacto con otra nave y no estás bajo tensión, puedes recibir 1 ficha de Tensión para cambiar la orientación de tu nave 180°.'''
'Alliance Overhaul':
name: "Reacondicionado por la Alianza"
text: '''<span class="card-restriction">Sólo ARC-170.</span>%LINEBREAK%Cuando ataques con un armamento principal desde tu arco de fuego normal, puedes tirar 1 dado de ataque adicional. Cuando ataques desde tu arco de fuego auxiliar, puedes cambiar 1 de tus resultados %FOCUS% por 1 resultado %CRIT%.'''
'Special Ops Training':
ship: "Caza TIE/sf"
name: "Entrenamiento de operaciones especiales"
text: '''<span class="card-restriction">Sólo TIE/sf.</span>%LINEBREAK%Cuando ataques con un armamento principal desde tu arco de fuego normal, puedes tirar 1 dado adicional de ataque. Si decides no hacerlo, puedes realizar un ataque adicional desde tu arco de fuego aixiliar.'''
'Concord Dawn Protector':
name: "Protector de Concord Dawn"
ship: "Caza Estelar del Protectorado"
text: '''<span class="card-restriction">Sólo Caza estelar del Protectorado.</span>%LINEBREAK%Cuando te defiendas, si estás dentro del arco de fuego del atacante y a alcance 1 y el atacante está dentro de tu arco de fuego, añade 1 resultado %EVADE%.'''
'Shadow Caster':
name: "PI:NAME:<NAME>END_PI"
ship: "Nave de persecución clase Lancero"
text: '''<span class="card-restriction">Sólo Nave de persecución clase Lancero</span>%LINEBREAK%Después de que efectúes un ataque que impacte, si el defensor está dentro de tu arco de fuego móvil y a alcance 1-2, puedes asignarle 1 ficha de Campo de tracción.'''
# Wave X
'''Sabine's Masterpiece''':
ship: "Caza TIE"
name: "OPI:NAME:<NAME>END_PIestPI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Sólo Caza TIE.</span>%REBELONLY%%LINEBREAK%Tu barra de mejoras gana los iconos %CREW% y %ILLICIT%.'''
'''PI:NAME:<NAME>END_PI Shuttle''':
ship: "Lanzadera clase Ípsilon"
name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"
text: '''<span class="card-restriction">Sólo Lanzadera clase Ípsilon.</span>%LINEBREAK%Al final de la fase de Combate, elige una nave enemiga que tengas a alcance 1-2 y no esté bajo tensión. El jugador que la controla debe asignarle una ficha de Tensión o asignar una ficha de Tensión a otra d esus naves que esté situada a alcance 1-2 de ti.'''
'''Pivot Wing''':
name: "PI:NAME:<NAME>END_PI"
ship: "Ala-U"
text: '''<span class="card-restriction">Sólo Ala-U.</span> %DUALCARD%%LINEBREAK%<strong>Cara A (Ataque):</strong> Tu Agilidad se incrementa en 1.%LINEBREAK%Después de que ejecutes una maniobra, puedes darle la vuelta a esta carta.%LINEBREAK%<strong>Cara B (Aterrizaje):</strong> Cuando reveles una maniobra (%STOP% 0), puedes cambiar la orientación de tu nave en 180°.%LINEBREAK%Después de que ejecutes una maniobra, puedes darle la vuelta a esta carta.'''
'''Adaptive Ailerons''':
name: "PI:NAME:<NAME>END_PI"
ship: "Fustigador TIE"
text: '''<span class="card-restriction">Sólo Fustigador TIE.</span>%LINEBREAK%Inmediatamente antes de revelar tu selector de maniobras, si no estás bajo tensión, debes ejecutar una manibora blanca (%BANKLEFT% 1), (%STRAIGHT% 1) o (%BANKRIGHT% 1).'''
# C-ROC
'''Merchant One''':
name: "PI:NAME:<NAME>END_PI"
ship: "Crucero C-ROC"
text: '''<span class="card-restriction">Sólo C-ROC Cruiser.</span>%LINEBREAK%Tu barra de mejoras gana 1 icono %CREW% adicional y 1 icono %TEAM% adicional y pierde 1 icono %CARGO%.'''
'''"Light Scyk" Interceptor''':
name: 'Interceptor "PI:NAME:<NAME>END_PI"'
ship: "Interceptor M3-A"
text: '''<span class="card-restriction">Sólo Interceptor M3-A.</span>%LINEBREAK%Toda slas cartas de Daño que te inflijan se te asignan boca arriba. Puedes ejecutar todas las maniobras de inclinación (%BANKLEFT% o %BANKRIGHT%) como maniobras verdes. No puedes equiparte con mejoras de Modificación.s.'''
'''Insatiable Worrt''':
name: "PI:NAME:<NAME>END_PI"
ship: "Crucero C-ROC"
text: '''Después de que realices la acción de recuperación, ganas 3 de energía.'''
'''Broken Horn''':
name: "PI:NAME:<NAME>END_PI"
ship: "Crucero C-ROC"
text: '''Cuando te defiendas, si tienes asignada una ficha de Refuerzo, puedes añadir 1 resultado %EVADE% adicional. Si lo haces, tras defenderte, descarta tu ficha de Refuerzo.'''
'PI:NAME:<NAME>END_PI':
name: "PI:NAME:<NAME>END_PI"
ship: "Bombardero Scurrg H-6"
text: '''<span class="card-restriction">Sólo Bombarder Scurrg H-6.</span>%LINEBREAK%Tu barra de mejoras gana los iconos %SYSTEM% y %SALVAGEDASTROMECH% y pierde el icono %CREW%.%LINEBREAK%No puedes equiparte con cartas de mejora %SALVAGEDASTROMECH% que no sean únicas.'''
'Vaksai':
ship: "Caza Kihraxz"
text: '''<span class="card-restriction">Sólo Caza Kihraxz.</span>%LINEBREAK%El coste en puntos de escuadrón de cada una de tus mejoras equipadas se reduce en 1 (hast aun mínimo de 0).%LINEBREAK%Puedes equipar un máximo de 3 mejoras distintas de Modificación.'''
'StarViper Mk. II':
name: "PI:NAME:<NAME>END_PI"
ship: "Víbora Estelar"
text: '''<span class="card-restriction">Sólo Víbora Estelar.</span>%LINEBREAK%Puedes equipar un máximo de 2 mejoras distintas de Título.%LINEBREAK%Cuando realices una acción de tonel volado <strong>debes</strong> utilizar la plantilla (%BANKLEFT% 1) o (%BANKRIGHT% 1) en vez de la plantilla (%STRAIGHT% 1).'''
'XG-1 Assault Configuration':
ship: "Ala Estelar clase Alfa"
name: "Configuración de asalto Xg-1"
text: '''<span class="card-restriction">Sólo Ala Estelar clase Alfa.</span>%LINEBREAK%Tu barra de mejoras gana 2 iconos %CANNON%.%LINEBREAK%Puedes efectuar ataques con sistemas de armamento secundario %CANNON% con un coste igual o inferior a 2 puntos de escuadrón incluso aunque tengas asignada una ficha de Armas bloqueadas.'''
'Enforcer':
name: "PI:NAME:<NAME>END_PI"
ship: "Caza M12-L Kimogila"
text: '''<span class="card-restriction">Sólo Caza M12-L Kimogila.</span>%LINEBREAK%Después de que te defiendas, si el atacante está situado dentro de tu arco de fuego centrado, recibe 1 fciha de Tensión.'''
'Ghost (Phantom II)':
name: "PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI)"
text: '''<span class="card-restriction">Sólo VCX-100.</span>%LINEBREAK%Equipa la carta de Título <em>Fantasma II</em> a una Lanzadera clase <em>Sheathipede</em> aliada y acóplala a esta nave.%LINEBREAK%Después de que ejecutes una maniobra, puedes desplegar la nave que tienes acoplada desde los salientes de la parte trasera de tu peana.'''
'Phantom II':
name: "PI:NAME:<NAME>END_PI"
ship: "Lanzadera clase Sheathipede"
text: '''Mientras estés acoplado, el <em>Espíritu</em> puede efectuar ataques con su armamento principal desde su arco de fuego especial.%LINEBREAK%Mientras estés acoplado, al final de la fase de Activación, el <em>Espíritu</em> puede efectuar una acción gratuita de coordinación.'''
'First Order Vanguard':
name: "PI:NAME:<NAME>END_PI"
ship: "Silenciador TIE"
text: '''<span class="card-restriction">Sólo Silenciador TIE.</span>%LINEBREAK%Cuando ataques, si el defensor es la única nave que tienes dentro de tu arco de fuego a alcance 1-3, puedes volver a tirar 1 dado de ataque.%LINEBREAK%Cuando te defiendas, puedes descartar esta carta para volver a tirar todos tus dados de defensa.'''
'Os-1 Arsenal Loadout':
name: "Configuración de Arsenal Os-1"
ship: "Ala Estelar clase Alfa"
text: '''<span class="card-restriction">Sólo Ala Estelar clase Alfa.</span>%LINEBREAK%Tu barra de mejoras gana los iconos %TORPEDO% y %MISSILE%.%LINEBREAK%Puedes efectuar ataques con sistemas de armamento secundario %TORPEDO% y %MISSILE% contra naves que hayas fijado como blanco incluso aunque tengas asignada una ficha de Armas bloqueadas.'''
'Crossfire Formation':
name: "Formación de fuego cruzado"
ship: "Bombardero B/SF-17"
text: '''<span class="card-restriction">Sólo bombardero B/SF-17.</span>%LINEBREAK%Cuando te defiendas, si hay por lo menos 1 otra nave aliada de la Reistencia situada a alcance 1-2 del atacante, puedes añadir 1 resultado %FOCUS% a tu tirada.'''
'Advanced Ailerons':
name: "Alerones avanzados"
ship: "Segador TIE"
text: '''<span class="card-restriction">Sólo Segador TIE.</span>%LINEBREAK%Tus maniobras (%BANKLEFT% 3) y (%BANKRIGHT% 3) se consideran blancas.%LINEBREAK%Inmediatamente antes de revelar tu selector de maniobras, si no estás bajo tensión, debes ejecutar una manibora blanca (%BANKLEFT% 1), (%STRAIGHT% 1) o (%BANKRIGHT% 1).'''
condition_translations =
'''I'll Show You the Dark Side''':
name: "Yo te mostraré el Lado Oscuro"
text: '''Cuando esta carta es asignada, si no está ya en juego, el jugador que la ha asignado busca en el mazo de Daño 1 carta de Daño que tenga el atributo <strong><em>Piloto</em></strong> y puede colocarla boca arriba sobre esta carta de Estado. Luego vuelve a barajar el mazo de Daño.%LINEBREAKCuando sufras daño crítico durante un ataque, en vez de eso recibes la carta de Daño boca arriba que has elegido.%LINEBREAK%Cuando no haya ninguna carta de Daño sobre esta carta de Estado, retírala.'''
'Suppressive Fire':
name: "Fuego de supresión"
text: '''Cuando ataques a una nave que no sea el "Capitán Rex", tira 1 dado de ataque menos.%LINEBREAK% Cuando declares un ataque que tenga como blanco al "Capitán Rex" o cuando el "Capitán Rex" sea destruido, retira esta carta.%LINEBREAK%Al final de la fase de Combate, si el "Capitán Rex" no ha efectuado un ataque en esta fase, retira esta carta.'''
'Fanatical Devotion':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando te defiendas, no pudes gastar fichas de Concentración.%LINEBREAK%Cuando ataques, si gastas una ficha de Concentración parar cambiar todos los resultados %FOCUS% por resultados %HIT%, deja aparte el primer resultado %FOCUS% que has cambiado. El resultado %HIT% que has dejado aparte no puede ser anulado por dados de defensa, pero el defensor puede anular resultados %CRIT% antes que él.%LINEBREAK%Durante la fase Final, retira esta carta.'''
'A Debt to Pay':
name: "Una deuda por saldar"
text: '''Cuando ataques a una nave que tiene la carta de Mejora "Una cuenta pendiente", puedes cambiar 1 resultado %FOCUS% por un resultado %CRIT%.'''
'Shadowed':
name: "PI:NAME:<NAME>END_PI"
text: '''Se considera que "Thweek" tiene el mismo valor de Habilidad que tu piloto tenía después de la preparación de la partida.%LINEBREAK%El valor de Habilidad de "Thweek" no cambia si el valor de Habilidad de tu piloto se modifica o eres destruido.'''
'Mimicked':
name: "PI:NAME:<NAME>END_PI"
text: '''Se considera que "Thweek" tiene tu misma capacidad especial de piloto.%LINEBREAK%"Thweek" no puede utilizar tu capacidad especial de piloto para asignar una carta de Estado.%LINEBREAK%"Thweek" no pierde tu capacidad especial de piloto si eres destruido.'''
'Harpooned!':
name: "PI:NAME:<NAME>END_PI¡PI:NAME:<NAME>END_PI!"
text: '''Cuando seas impactado por un ataque, si hay al menos 1 resultad %CRIT% sin anular, toda otra nave que tengas a alcance 1 sufre 1 punto de daño. Luego descarta esta carta y recibe 1 carta de Daño boca abajo.%LINEBREAK%Cuando seas destruido, toda nave que tengas a alcance 1 sufre 1 punto de daño.%LINEBREAK%<strong>Acción:</strong> Descarta esta carta. Luego tira 1 dado de ataque. Si sacas %HIT% o %CRIT%, sufres 1 punto de daño.'''
'Rattled':
name: "PI:NAME:<NAME>END_PI"
text: '''Cuando sufras daño normal o daño crítico causado por una bomba, sufres 1 punto adicional de daño crítico. Luego, retira esta carta%LINEBREAK%<strong>Acción:</strong> Tira 1 dado de ataque. Si sacas %FOCUS% o %HIT%, retira esta carta.'''
'Scrambled':
name: "Sistemas interferidos"
text: '''Cuando ataques a una nave que tengas a alcance 1 y esté equipada con la mejora "Interferidor de sistemas de puntería", no puedes modificar tus dados de ataque.%LINEBREAK%Al final de la fase de Combate, retira esta carta.'''
'Optimized Prototype':
name: "Prototipo optimizado"
text: '''Tu valor de Escudos se incrementa en 1.%LINEBREAK%Una vez por ronda, cuando efectúes un ataque con tu armamento principal, puedes gastar 1 resultado de dado para retirar 1 ficha de Escudos del defensor.%LINEBREAK%Después de que efectúes un ataque con tu armamento principal, una nave aliada que tengas a alcance 1-2 y esté equipada con la carta de Mejora "PI:NAME:<NAME>END_PI" puede fijar como blanco al defensor.'''
exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations
|
[
{
"context": ")\"\n params =\n email: email\n password: password\n @post \"session\", params, (data) -> fn data if",
"end": 1149,
"score": 0.9991312623023987,
"start": 1141,
"tag": "PASSWORD",
"value": "password"
}
] | src/Models/Users.coffee | lengyuedaidai/node-gitlab | 143 | BaseModel = require '../BaseModel'
class Users extends BaseModel
init: =>
@keys = @load 'UserKeys'
all: (params = {}, fn = null) =>
if 'function' is typeof params
fn = params
params = {}
@debug "Users::all()"
params.page ?= 1
params.per_page ?= 100
data = []
cb = (err, retData) =>
if err
return fn(retData || data) if fn
else if retData.length == params.per_page
@debug "Recurse Users::all()"
data = data.concat(retData)
params.page++
return @get "users", params, cb
else
data = data.concat(retData)
return fn data if fn
@get "users", params, cb
current: (fn = null) =>
@debug "Users::current()"
@get "user", (data) -> fn data if fn
show: (userId, fn = null) =>
@debug "Users::show()"
@get "users/#{parseInt userId}", (data) => fn data if fn
create: (params = {}, fn = null) =>
@debug "Users::create()", params
@post "users", params, (data) -> fn data if fn
session: (email, password, fn = null) =>
@debug "Users::session()"
params =
email: email
password: password
@post "session", params, (data) -> fn data if fn
search: (emailOrUsername, fn = null) =>
@debug "Users::search(#{emailOrUsername})"
params =
search: emailOrUsername
@get "users", params, (data) -> fn data if fn
module.exports = (client) -> new Users client
| 145979 | BaseModel = require '../BaseModel'
class Users extends BaseModel
init: =>
@keys = @load 'UserKeys'
all: (params = {}, fn = null) =>
if 'function' is typeof params
fn = params
params = {}
@debug "Users::all()"
params.page ?= 1
params.per_page ?= 100
data = []
cb = (err, retData) =>
if err
return fn(retData || data) if fn
else if retData.length == params.per_page
@debug "Recurse Users::all()"
data = data.concat(retData)
params.page++
return @get "users", params, cb
else
data = data.concat(retData)
return fn data if fn
@get "users", params, cb
current: (fn = null) =>
@debug "Users::current()"
@get "user", (data) -> fn data if fn
show: (userId, fn = null) =>
@debug "Users::show()"
@get "users/#{parseInt userId}", (data) => fn data if fn
create: (params = {}, fn = null) =>
@debug "Users::create()", params
@post "users", params, (data) -> fn data if fn
session: (email, password, fn = null) =>
@debug "Users::session()"
params =
email: email
password: <PASSWORD>
@post "session", params, (data) -> fn data if fn
search: (emailOrUsername, fn = null) =>
@debug "Users::search(#{emailOrUsername})"
params =
search: emailOrUsername
@get "users", params, (data) -> fn data if fn
module.exports = (client) -> new Users client
| true | BaseModel = require '../BaseModel'
class Users extends BaseModel
init: =>
@keys = @load 'UserKeys'
all: (params = {}, fn = null) =>
if 'function' is typeof params
fn = params
params = {}
@debug "Users::all()"
params.page ?= 1
params.per_page ?= 100
data = []
cb = (err, retData) =>
if err
return fn(retData || data) if fn
else if retData.length == params.per_page
@debug "Recurse Users::all()"
data = data.concat(retData)
params.page++
return @get "users", params, cb
else
data = data.concat(retData)
return fn data if fn
@get "users", params, cb
current: (fn = null) =>
@debug "Users::current()"
@get "user", (data) -> fn data if fn
show: (userId, fn = null) =>
@debug "Users::show()"
@get "users/#{parseInt userId}", (data) => fn data if fn
create: (params = {}, fn = null) =>
@debug "Users::create()", params
@post "users", params, (data) -> fn data if fn
session: (email, password, fn = null) =>
@debug "Users::session()"
params =
email: email
password: PI:PASSWORD:<PASSWORD>END_PI
@post "session", params, (data) -> fn data if fn
search: (emailOrUsername, fn = null) =>
@debug "Users::search(#{emailOrUsername})"
params =
search: emailOrUsername
@get "users", params, (data) -> fn data if fn
module.exports = (client) -> new Users client
|
[
{
"context": "er, Mesh, SphereGeometry} from 'three'\n\n# Based on Ian Webster's blog post: http://www.ianww.com/blog/2014/02/17",
"end": 142,
"score": 0.9995133876800537,
"start": 131,
"tag": "NAME",
"value": "Ian Webster"
}
] | src/Background.coffee | skepticalimagination/solaris-js | 4 | import publicize from './helpers/publicizer'
import {ShaderMaterial, TextureLoader, Mesh, SphereGeometry} from 'three'
# Based on Ian Webster's blog post: http://www.ianww.com/blog/2014/02/17/making-a-skydome-in-three-dot-js/
class $Background
constructor: (sceneSize, root) ->
material = new ShaderMaterial
uniforms:
texture: {type: 't', value: new TextureLoader().load("#{root}/img/background.jpg")}
vertexShader: '''
varying vec2 vUV;
void main() {
vUV = uv;
vec4 pos = vec4(position, 1.0);
gl_Position = projectionMatrix * modelViewMatrix * pos;
}
'''
fragmentShader: '''
uniform sampler2D texture;
varying vec2 vUV;
void main() {
vec4 sample = texture2D(texture, vUV);
gl_FragColor = vec4(sample.xyz, sample.w);
}
'''
# @public
@mesh = new Mesh(new SphereGeometry(sceneSize * 50, 60, 40), material)
@mesh.scale.set(-1, 1, 1)
@mesh.rotation.order = 'XZY'
@mesh.rotation.z = Math.PI / 2
@mesh.rotation.x = Math.PI
@mesh.renderDepth = 1000.0
export default class Background extends publicize $Background,
properties: ['mesh']
| 130916 | import publicize from './helpers/publicizer'
import {ShaderMaterial, TextureLoader, Mesh, SphereGeometry} from 'three'
# Based on <NAME>'s blog post: http://www.ianww.com/blog/2014/02/17/making-a-skydome-in-three-dot-js/
class $Background
constructor: (sceneSize, root) ->
material = new ShaderMaterial
uniforms:
texture: {type: 't', value: new TextureLoader().load("#{root}/img/background.jpg")}
vertexShader: '''
varying vec2 vUV;
void main() {
vUV = uv;
vec4 pos = vec4(position, 1.0);
gl_Position = projectionMatrix * modelViewMatrix * pos;
}
'''
fragmentShader: '''
uniform sampler2D texture;
varying vec2 vUV;
void main() {
vec4 sample = texture2D(texture, vUV);
gl_FragColor = vec4(sample.xyz, sample.w);
}
'''
# @public
@mesh = new Mesh(new SphereGeometry(sceneSize * 50, 60, 40), material)
@mesh.scale.set(-1, 1, 1)
@mesh.rotation.order = 'XZY'
@mesh.rotation.z = Math.PI / 2
@mesh.rotation.x = Math.PI
@mesh.renderDepth = 1000.0
export default class Background extends publicize $Background,
properties: ['mesh']
| true | import publicize from './helpers/publicizer'
import {ShaderMaterial, TextureLoader, Mesh, SphereGeometry} from 'three'
# Based on PI:NAME:<NAME>END_PI's blog post: http://www.ianww.com/blog/2014/02/17/making-a-skydome-in-three-dot-js/
class $Background
constructor: (sceneSize, root) ->
material = new ShaderMaterial
uniforms:
texture: {type: 't', value: new TextureLoader().load("#{root}/img/background.jpg")}
vertexShader: '''
varying vec2 vUV;
void main() {
vUV = uv;
vec4 pos = vec4(position, 1.0);
gl_Position = projectionMatrix * modelViewMatrix * pos;
}
'''
fragmentShader: '''
uniform sampler2D texture;
varying vec2 vUV;
void main() {
vec4 sample = texture2D(texture, vUV);
gl_FragColor = vec4(sample.xyz, sample.w);
}
'''
# @public
@mesh = new Mesh(new SphereGeometry(sceneSize * 50, 60, 40), material)
@mesh.scale.set(-1, 1, 1)
@mesh.rotation.order = 'XZY'
@mesh.rotation.z = Math.PI / 2
@mesh.rotation.x = Math.PI
@mesh.renderDepth = 1000.0
export default class Background extends publicize $Background,
properties: ['mesh']
|
[
{
"context": "ata - for debugging only\n# $scope.user.name = \"Luke\"\n# $scope.user.password = \"Skywalker\"\n\n\n # lo",
"end": 435,
"score": 0.9943066239356995,
"start": 431,
"tag": "NAME",
"value": "Luke"
},
{
"context": "e.user.name = \"Luke\"\n# $scope.user.password = \"Skywalker\"\n\n\n # login\n # --------------------------------",
"end": 475,
"score": 0.9988800883293152,
"start": 466,
"tag": "PASSWORD",
"value": "Skywalker"
}
] | app/assets/javascripts/controllers/loginController.coffee | kronus/angular-ruby-2014-example | 0 | angular.module('cafeTownsend')
.controller 'LoginController'
, ['$log',
'$scope',
'$location',
'SessionService',
'ViewState'
, ($log, $scope, $location, SessionService, ViewState) ->
# init
# ------------------------------------------------------------
init = ->
$scope.user = SessionService.getCurrentUser()
ViewState.current = 'login'
# mock user data - for debugging only
# $scope.user.name = "Luke"
# $scope.user.password = "Skywalker"
# login
# ------------------------------------------------------------
$scope.submit = ->
SessionService.login($scope.user)
.then((result)->
loginResultHandler(result)
,
(error)->
loginErrorHandler(error)
)
loginResultHandler = (result) ->
if !!SessionService.authorized()
$location.path '/employees'
else
$scope.message = 'Invalid username or password!'
loginErrorHandler = (error) ->
$scope.message = "Error: #{error}"
#helper method called by view
# to show or hide a message
$scope.showMessage = ->
$scope.message isnt undefined and $scope.message.length > 0
init()
] | 86732 | angular.module('cafeTownsend')
.controller 'LoginController'
, ['$log',
'$scope',
'$location',
'SessionService',
'ViewState'
, ($log, $scope, $location, SessionService, ViewState) ->
# init
# ------------------------------------------------------------
init = ->
$scope.user = SessionService.getCurrentUser()
ViewState.current = 'login'
# mock user data - for debugging only
# $scope.user.name = "<NAME>"
# $scope.user.password = "<PASSWORD>"
# login
# ------------------------------------------------------------
$scope.submit = ->
SessionService.login($scope.user)
.then((result)->
loginResultHandler(result)
,
(error)->
loginErrorHandler(error)
)
loginResultHandler = (result) ->
if !!SessionService.authorized()
$location.path '/employees'
else
$scope.message = 'Invalid username or password!'
loginErrorHandler = (error) ->
$scope.message = "Error: #{error}"
#helper method called by view
# to show or hide a message
$scope.showMessage = ->
$scope.message isnt undefined and $scope.message.length > 0
init()
] | true | angular.module('cafeTownsend')
.controller 'LoginController'
, ['$log',
'$scope',
'$location',
'SessionService',
'ViewState'
, ($log, $scope, $location, SessionService, ViewState) ->
# init
# ------------------------------------------------------------
init = ->
$scope.user = SessionService.getCurrentUser()
ViewState.current = 'login'
# mock user data - for debugging only
# $scope.user.name = "PI:NAME:<NAME>END_PI"
# $scope.user.password = "PI:PASSWORD:<PASSWORD>END_PI"
# login
# ------------------------------------------------------------
$scope.submit = ->
SessionService.login($scope.user)
.then((result)->
loginResultHandler(result)
,
(error)->
loginErrorHandler(error)
)
loginResultHandler = (result) ->
if !!SessionService.authorized()
$location.path '/employees'
else
$scope.message = 'Invalid username or password!'
loginErrorHandler = (error) ->
$scope.message = "Error: #{error}"
#helper method called by view
# to show or hide a message
$scope.showMessage = ->
$scope.message isnt undefined and $scope.message.length > 0
init()
] |
[
{
"context": " kind: operations.ADD_DEPOSIT\n account: 'Peter'\n currency: 'USD'\n amount: 200.0\n ",
"end": 818,
"score": 0.9992102980613708,
"start": 813,
"tag": "NAME",
"value": "Peter"
}
] | test/integration/test_trade.coffee | PartTimeLegend/buttercoin-engine | 8 | test.uses "trade_engine",
"Journal",
"pce",
"operations",
"logger"
Q = require("q")
kTestFilename = 'test.log'
describe 'TradeEngine', ->
beforeEach =>
TestHelper.remove_log(kTestFilename)
afterEach =>
TestHelper.remove_log(kTestFilename)
xit 'can perform deposit', (finish) ->
deferred = Q.defer()
deferred.resolve(undefined)
replicationStub =
start: sinon.stub()
send: sinon.stub().returns(deferred.promise)
pce = new ProcessingChainEntrance(new TradeEngine(),
new Journal(kTestFilename),
replicationStub)
pce.start().then ->
logger.info('Started PCE')
pce.forward_operation
kind: operations.ADD_DEPOSIT
account: 'Peter'
currency: 'USD'
amount: 200.0
.then =>
finish()
.done()
| 20699 | test.uses "trade_engine",
"Journal",
"pce",
"operations",
"logger"
Q = require("q")
kTestFilename = 'test.log'
describe 'TradeEngine', ->
beforeEach =>
TestHelper.remove_log(kTestFilename)
afterEach =>
TestHelper.remove_log(kTestFilename)
xit 'can perform deposit', (finish) ->
deferred = Q.defer()
deferred.resolve(undefined)
replicationStub =
start: sinon.stub()
send: sinon.stub().returns(deferred.promise)
pce = new ProcessingChainEntrance(new TradeEngine(),
new Journal(kTestFilename),
replicationStub)
pce.start().then ->
logger.info('Started PCE')
pce.forward_operation
kind: operations.ADD_DEPOSIT
account: '<NAME>'
currency: 'USD'
amount: 200.0
.then =>
finish()
.done()
| true | test.uses "trade_engine",
"Journal",
"pce",
"operations",
"logger"
Q = require("q")
kTestFilename = 'test.log'
describe 'TradeEngine', ->
beforeEach =>
TestHelper.remove_log(kTestFilename)
afterEach =>
TestHelper.remove_log(kTestFilename)
xit 'can perform deposit', (finish) ->
deferred = Q.defer()
deferred.resolve(undefined)
replicationStub =
start: sinon.stub()
send: sinon.stub().returns(deferred.promise)
pce = new ProcessingChainEntrance(new TradeEngine(),
new Journal(kTestFilename),
replicationStub)
pce.start().then ->
logger.info('Started PCE')
pce.forward_operation
kind: operations.ADD_DEPOSIT
account: 'PI:NAME:<NAME>END_PI'
currency: 'USD'
amount: 200.0
.then =>
finish()
.done()
|
[
{
"context": "!\"\n\n@MyCtrl1 = ($scope, $http) ->\n\t$scope.name = \"World\"\nMyCtrl1.$inject = ['$scope','$http']\n\n\n@MyCtrl2 ",
"end": 306,
"score": 0.8707911968231201,
"start": 301,
"tag": "NAME",
"value": "World"
},
{
"context": "]\n\n\n@MyCtrl2 = ($scope, $http) ->\n\t$scope.name = \"Bear\"\nMyCtrl2.$inject = ['$scope','$http']",
"end": 397,
"score": 0.9821189045906067,
"start": 393,
"tag": "NAME",
"value": "Bear"
}
] | client/src/js/controllers.coffee | kuetemeier/Node-Express-Angular-Coffee-Bootstrap | 0 | "use strict"
# Controllers
@AppCtrl = ($scope, $http) ->
$http(
method: "GET"
url: "/api/name"
).success((data, status, headers, config) ->
$scope.name = data.name
).error (data, status, headers, config) ->
$scope.name = "Error!"
@MyCtrl1 = ($scope, $http) ->
$scope.name = "World"
MyCtrl1.$inject = ['$scope','$http']
@MyCtrl2 = ($scope, $http) ->
$scope.name = "Bear"
MyCtrl2.$inject = ['$scope','$http'] | 180021 | "use strict"
# Controllers
@AppCtrl = ($scope, $http) ->
$http(
method: "GET"
url: "/api/name"
).success((data, status, headers, config) ->
$scope.name = data.name
).error (data, status, headers, config) ->
$scope.name = "Error!"
@MyCtrl1 = ($scope, $http) ->
$scope.name = "<NAME>"
MyCtrl1.$inject = ['$scope','$http']
@MyCtrl2 = ($scope, $http) ->
$scope.name = "<NAME>"
MyCtrl2.$inject = ['$scope','$http'] | true | "use strict"
# Controllers
@AppCtrl = ($scope, $http) ->
$http(
method: "GET"
url: "/api/name"
).success((data, status, headers, config) ->
$scope.name = data.name
).error (data, status, headers, config) ->
$scope.name = "Error!"
@MyCtrl1 = ($scope, $http) ->
$scope.name = "PI:NAME:<NAME>END_PI"
MyCtrl1.$inject = ['$scope','$http']
@MyCtrl2 = ($scope, $http) ->
$scope.name = "PI:NAME:<NAME>END_PI"
MyCtrl2.$inject = ['$scope','$http'] |
[
{
"context": "operty\nwindow.fn.playSensors =\n \"1002\": { name: 'Миладиновци', group: 13 }\n \"11888f3a-bc5e-4a0c-9f27-702984de",
"end": 153,
"score": 0.9963108897209167,
"start": 142,
"tag": "NAME",
"value": "Миладиновци"
},
{
"context": " \"11888f3a-bc5e-4a0c-9f27-702984decedf\": { name: 'МЗТ', group: 9 }\n \"01440b05-255d-4764-be87-bdf135f32",
"end": 222,
"score": 0.7385501861572266,
"start": 219,
"tag": "NAME",
"value": "МЗТ"
},
{
"context": " \"01440b05-255d-4764-be87-bdf135f32289\": { name: 'Бардовци', group: 10 }\n \"bb948861-3fd7-47dd-b986-cb13c973",
"end": 295,
"score": 0.9927813410758972,
"start": 287,
"tag": "NAME",
"value": "Бардовци"
},
{
"context": " \"bb948861-3fd7-47dd-b986-cb13c9732725\": { name: 'Бисер', group: 7 }\n \"cec29ba1-5414-4cf3-bbcc-8ce4db1da",
"end": 366,
"score": 0.9781646132469177,
"start": 361,
"tag": "NAME",
"value": "Бисер"
},
{
"context": " \"cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0\": { name: 'Алуминка', group: 1 }\n \"1005\": { name: 'Ректорат', group:",
"end": 439,
"score": 0.9784752726554871,
"start": 431,
"tag": "NAME",
"value": "Алуминка"
},
{
"context": "{ name: 'Алуминка', group: 1 }\n \"1005\": { name: 'Ректорат', group: 3 }\n \"bc9f31ea-bf3d-416c-86b5-ecba6e98b",
"end": 480,
"score": 0.9615117311477661,
"start": 472,
"tag": "NAME",
"value": "Ректорат"
},
{
"context": " \"bc9f31ea-bf3d-416c-86b5-ecba6e98bb24\": { name: 'Фонтана', group: 3 }\n \"66710fdc-cdfc-4bbe-93a8-7e796fb8a",
"end": 552,
"score": 0.9539019465446472,
"start": 545,
"tag": "NAME",
"value": "Фонтана"
},
{
"context": " \"66710fdc-cdfc-4bbe-93a8-7e796fb8a88d\": { name: 'Козле', group: 2 }\n \"24eaebc2-ca62-49ff-8b22-880bc131b",
"end": 622,
"score": 0.9400443434715271,
"start": 617,
"tag": "NAME",
"value": "Козле"
},
{
"context": "\"24eaebc2-ca62-49ff-8b22-880bc131b69f\": { name: 'Црниче', group: 5 }\n \"b79604bb-0bea-454f-a474-849156e41",
"end": 693,
"score": 0.7389925718307495,
"start": 688,
"tag": "NAME",
"value": "рниче"
},
{
"context": " \"b79604bb-0bea-454f-a474-849156e418ea\": { name: 'Драчево', group: 11 }\n \"1004\": { name: 'Газибаба', group",
"end": 765,
"score": 0.9695242047309875,
"start": 758,
"tag": "NAME",
"value": "Драчево"
},
{
"context": "{ name: 'Драчево', group: 11 }\n \"1004\": { name: 'Газибаба', group: 8 }\n \"fc4bfa77-f791-4f93-8c0c-62d8306c5",
"end": 807,
"score": 0.9963046908378601,
"start": 799,
"tag": "NAME",
"value": "Газибаба"
},
{
"context": " \"fc4bfa77-f791-4f93-8c0c-62d8306c599c\": { name: 'Нерези', group: 2 }\n \"cfb0a034-6e29-4803-be02-9215dcac1",
"end": 878,
"score": 0.9818727970123291,
"start": 872,
"tag": "NAME",
"value": "Нерези"
},
{
"context": " \"cfb0a034-6e29-4803-be02-9215dcac17a8\": { name: 'Ѓорче Петров', group: 4 }\n \"1003\": { name: 'Карпош', group: 1",
"end": 955,
"score": 0.9987363815307617,
"start": 943,
"tag": "NAME",
"value": "Ѓорче Петров"
},
{
"context": "me: 'Ѓорче Петров', group: 4 }\n \"1003\": { name: 'Карпош', group: 1 }\n \"200cdb67-8dc5-4dcf-ac62-748db636e",
"end": 994,
"score": 0.9969118237495422,
"start": 988,
"tag": "NAME",
"value": "Карпош"
},
{
"context": " \"200cdb67-8dc5-4dcf-ac62-748db636e04e\": { name: '11ти Октомври', group: 6 }\n \"8d415fa0-77dc-4cb3-8460-a91598009",
"end": 1072,
"score": 0.8198642730712891,
"start": 1059,
"tag": "NAME",
"value": "11ти Октомври"
},
{
"context": " \"8d415fa0-77dc-4cb3-8460-a9159800917f\": { name: 'СД Гоце Делчев', group: 2 }\n \"b80e5cd2-76cb-40bf-b784-2a0a312e6",
"end": 1151,
"score": 0.9317798614501953,
"start": 1137,
"tag": "NAME",
"value": "СД Гоце Делчев"
},
{
"context": " \"b80e5cd2-76cb-40bf-b784-2a0a312e6264\": { name: 'Станица Ѓорче', group: 4 }\n \"6380c7cc-df23-4512-ad10-f2b363000",
"end": 1229,
"score": 0.9881977438926697,
"start": 1216,
"tag": "NAME",
"value": "Станица Ѓорче"
},
{
"context": " \"6380c7cc-df23-4512-ad10-f2b363000579\": { name: 'Сопиште', group: 6 }\n \"eaae3b5f-bd71-46f9-85d5-8d3a19c96",
"end": 1301,
"score": 0.7604027390480042,
"start": 1294,
"tag": "NAME",
"value": "Сопиште"
},
{
"context": " \"eaae3b5f-bd71-46f9-85d5-8d3a19c96322\": { name: 'Карпош 2', group: 1 }\n \"7c497bfd-36b6-4eed-9172-37fd70f17",
"end": 1374,
"score": 0.8559079766273499,
"start": 1366,
"tag": "NAME",
"value": "Карпош 2"
},
{
"context": " \"7c497bfd-36b6-4eed-9172-37fd70f17c48\": { name: 'Железара', group: 8 }\n \"1000\": { name: 'Центар', group: 3",
"end": 1447,
"score": 0.9899620413780212,
"start": 1439,
"tag": "NAME",
"value": "Железара"
},
{
"context": "{ name: 'Железара', group: 8 }\n \"1000\": { name: 'Центар', group: 3 }\n \"3d7bd712-24a9-482c-b387-a8168b12d",
"end": 1486,
"score": 0.9927823543548584,
"start": 1480,
"tag": "NAME",
"value": "Центар"
},
{
"context": " \"3d7bd712-24a9-482c-b387-a8168b12d3f4\": { name: 'Бутел 1', group: 0 }\n \"5f718e32-5491-4c3c-98ff-45dc9e287",
"end": 1558,
"score": 0.8435988426208496,
"start": 1551,
"tag": "NAME",
"value": "Бутел 1"
},
{
"context": " \"5f718e32-5491-4c3c-98ff-45dc9e287df4\": { name: 'Водно', group: 5 }\n \"e7a05c01-1d5c-479a-a5a5-419f28ceb",
"end": 1628,
"score": 0.989433765411377,
"start": 1623,
"tag": "NAME",
"value": "Водно"
},
{
"context": " \"e7a05c01-1d5c-479a-a5a5-419f28cebeef\": { name: 'Излет', group: 3 }\n \"1001\": { name: 'Лисиче', group: 7",
"end": 1698,
"score": 0.999743640422821,
"start": 1693,
"tag": "NAME",
"value": "Излет"
},
{
"context": "\": { name: 'Излет', group: 3 }\n \"1001\": { name: 'Лисиче', group: 7 }\n \"8ad9e315-0e23-4dc0-a26f-ba5a17d4d",
"end": 1737,
"score": 0.9998325109481812,
"start": 1731,
"tag": "NAME",
"value": "Лисиче"
},
{
"context": " \"8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed\": { name: 'Аеродром', group: 7}\n \"680b0098-7c4d-44cf-acb1-dc4031e93d",
"end": 1810,
"score": 0.9994916915893555,
"start": 1802,
"tag": "NAME",
"value": "Аеродром"
},
{
"context": " \"680b0098-7c4d-44cf-acb1-dc4031e93d34\": { name: 'Илинден', group: 12}\n\n# latlngs for group/area\nlatlngs = ",
"end": 1881,
"score": 0.9997577667236328,
"start": 1874,
"tag": "NAME",
"value": "Илинден"
},
{
"context": " 12}\n\n# latlngs for group/area\nlatlngs = [\n [ #0: Бутел\n [42.02085304335116, 21.449068749034254],\n ",
"end": 1944,
"score": 0.9202011227607727,
"start": 1941,
"tag": "NAME",
"value": "Бут"
},
{
"context": "2.0397833869608, 21.454604110248848],\n ],\n [ #1: Карпош\n [42.00014153064202, 21.41316319319767],\n [",
"end": 2278,
"score": 0.9018673896789551,
"start": 2272,
"tag": "NAME",
"value": "Карпош"
},
{
"context": "42.0016532981841, 21.41347939309618],\n ],\n [ #2: Тафталиџе\n [41.999901217245906, 21.4130944226685",
"end": 2732,
"score": 0.6485361456871033,
"start": 2731,
"tag": "NAME",
"value": "Т"
},
{
"context": ".99385763206613, 21.448567600505104],\n ],\n [ #4: Ѓорче Петров\n [42.0104374739155, 21.381418140250933],\n [",
"end": 3637,
"score": 0.9998507499694824,
"start": 3625,
"tag": "NAME",
"value": "Ѓорче Петров"
},
{
"context": ".99148042888061, 21.423517942084803],\n ],\n [ #6: Кисела Вода\n [41.987405225853784, 21.432231903272626],\n ",
"end": 4578,
"score": 0.9755678772926331,
"start": 4567,
"tag": "NAME",
"value": "Кисела Вода"
},
{
"context": ".98743951388864, 21.441814899444584],\n ],\n [ #7: Аеродром\n [41.96521321351477, 21.491369248615232],\n ",
"end": 5453,
"score": 0.9972954988479614,
"start": 5445,
"tag": "NAME",
"value": "Аеродром"
},
{
"context": "85918729384345, 21.510715484619144],\n ],\n [ #10: Бардовци\n [42.00900286039821, 21.324119409620764],\n ",
"end": 8330,
"score": 0.9978926181793213,
"start": 8324,
"tag": "NAME",
"value": "Бардов"
},
{
"context": "01028038378219, 21.326297694298397],\n ],\n [ #11: Драчево\n [41.948416545200615, 21.511551093055237],\n ",
"end": 9557,
"score": 0.9960001111030579,
"start": 9550,
"tag": "NAME",
"value": "Драчево"
},
{
"context": "40951489149725, 21.504428084110156],\n ],\n [ #12: Илинден\n [41.99817833451146, 21.548629735708737],\n ",
"end": 10071,
"score": 0.9774478077888489,
"start": 10064,
"tag": "NAME",
"value": "Илинден"
},
{
"context": "98, 21.42361109 ]\n CITY = 'skopje'\n USERNAME = \"atonevski\"\n PASSWORD = \"pv1530kay\"\n\n\n parsePos = (s) ->\n ",
"end": 11963,
"score": 0.9995977878570557,
"start": 11954,
"tag": "USERNAME",
"value": "atonevski"
},
{
"context": "= 'skopje'\n USERNAME = \"atonevski\"\n PASSWORD = \"pv1530kay\"\n\n\n parsePos = (s) ->\n s.split /\\s*,\\s*/\n ",
"end": 11988,
"score": 0.999280571937561,
"start": 11979,
"tag": "PASSWORD",
"value": "pv1530kay"
},
{
"context": " url: url\n method: 'GET'\n username: USERNAME\n password: PASSWORD\n dataType: \"json\"\n ",
"end": 12751,
"score": 0.9994038343429565,
"start": 12743,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "od: 'GET'\n username: USERNAME\n password: PASSWORD\n dataType: \"json\"\n headers:\n \"Au",
"end": 12776,
"score": 0.9993702173233032,
"start": 12768,
"tag": "PASSWORD",
"value": "PASSWORD"
},
{
"context": "o/rest/sensor\"\n method: 'GET'\n username: USERNAME\n password: PASSWORD\n .done (d) ->\n #",
"end": 14347,
"score": 0.999505877494812,
"start": 14339,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "od: 'GET'\n username: USERNAME\n password: PASSWORD\n .done (d) ->\n # console.log d\n for ",
"end": 14372,
"score": 0.9978518486022949,
"start": 14364,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] | www/coffee/play.coffee | atonevski/skp-ons | 0 | #
# play.coffee: play last 24h pm10 measurements
#
window.fn.playMap = null
# add group property
window.fn.playSensors =
"1002": { name: 'Миладиновци', group: 13 }
"11888f3a-bc5e-4a0c-9f27-702984decedf": { name: 'МЗТ', group: 9 }
"01440b05-255d-4764-be87-bdf135f32289": { name: 'Бардовци', group: 10 }
"bb948861-3fd7-47dd-b986-cb13c9732725": { name: 'Бисер', group: 7 }
"cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0": { name: 'Алуминка', group: 1 }
"1005": { name: 'Ректорат', group: 3 }
"bc9f31ea-bf3d-416c-86b5-ecba6e98bb24": { name: 'Фонтана', group: 3 }
"66710fdc-cdfc-4bbe-93a8-7e796fb8a88d": { name: 'Козле', group: 2 }
"24eaebc2-ca62-49ff-8b22-880bc131b69f": { name: 'Црниче', group: 5 }
"b79604bb-0bea-454f-a474-849156e418ea": { name: 'Драчево', group: 11 }
"1004": { name: 'Газибаба', group: 8 }
"fc4bfa77-f791-4f93-8c0c-62d8306c599c": { name: 'Нерези', group: 2 }
"cfb0a034-6e29-4803-be02-9215dcac17a8": { name: 'Ѓорче Петров', group: 4 }
"1003": { name: 'Карпош', group: 1 }
"200cdb67-8dc5-4dcf-ac62-748db636e04e": { name: '11ти Октомври', group: 6 }
"8d415fa0-77dc-4cb3-8460-a9159800917f": { name: 'СД Гоце Делчев', group: 2 }
"b80e5cd2-76cb-40bf-b784-2a0a312e6264": { name: 'Станица Ѓорче', group: 4 }
"6380c7cc-df23-4512-ad10-f2b363000579": { name: 'Сопиште', group: 6 }
"eaae3b5f-bd71-46f9-85d5-8d3a19c96322": { name: 'Карпош 2', group: 1 }
"7c497bfd-36b6-4eed-9172-37fd70f17c48": { name: 'Железара', group: 8 }
"1000": { name: 'Центар', group: 3 }
"3d7bd712-24a9-482c-b387-a8168b12d3f4": { name: 'Бутел 1', group: 0 }
"5f718e32-5491-4c3c-98ff-45dc9e287df4": { name: 'Водно', group: 5 }
"e7a05c01-1d5c-479a-a5a5-419f28cebeef": { name: 'Излет', group: 3 }
"1001": { name: 'Лисиче', group: 7 }
"8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed": { name: 'Аеродром', group: 7}
"680b0098-7c4d-44cf-acb1-dc4031e93d34": { name: 'Илинден', group: 12}
# latlngs for group/area
latlngs = [
[ #0: Бутел
[42.02085304335116, 21.449068749034254],
[42.0222566295136, 21.43018848436059],
[42.02723273079618, 21.429244471126886],
[42.02710514332077, 21.434393634219713],
[42.052352164029465, 21.423005104261396],
[42.04594384579999, 21.43919259561023],
[42.0397833869608, 21.454604110248848],
],
[ #1: Карпош
[42.00014153064202, 21.41316319319767],
[42.00460390831076, 21.38278313095],
[42.00557239019032, 21.380225335657713],
[42.00966193219604, 21.38228917108791],
[42.00930271511426, 21.38507317670075],
[42.00767729097137, 21.39090889487261],
[42.00767729097137, 21.39082307548773],
[42.006179314301946, 21.414080128790324],
[42.0053187585617, 21.416654710336722],
[42.0016532981841, 21.41347939309618],
],
[ #2: Тафталиџе
[41.999901217245906, 21.413094422668596],
[41.993366432064164, 21.411034757431477],
[41.989190193553455, 21.406228871878163],
[41.99748501915229, 21.371961189924015],
[42.00523402234377, 21.38009756173427],
[42.00445313657715, 21.382779417511763],
],
[ #3: Центар
[41.98745837139266, 21.441801552158026],
[41.98758589765055, 21.431760684127],
[41.99153908493555, 21.42352202317851],
[41.98758589765055, 21.417171388697337],
[41.99309313129358, 21.411201094635402],
[41.99978732184316, 21.413260759872532],
[42.00153873372848, 21.41366539376736],
[42.00518184740425, 21.416814956452857],
[42.002058244270216, 21.423101226395328],
[42.00358819149654, 21.42438851716855],
[42.0011892397794, 21.428743322597725],
[41.99854358309758, 21.450155259125392],
[41.99385763206613, 21.448567600505104],
],
[ #4: Ѓорче Петров
[42.0104374739155, 21.381418140250933],
[42.005146819652325, 21.379229745936488],
[41.99787942070697, 21.371506001297263],
[42.00227820869816, 21.34760530260808],
[42.00686792414399, 21.331814535790077],
[42.00906704545891, 21.32966905116807],
[42.01126609075234, 21.358590183872767],
[42.011680395122966, 21.379358475013806],
],
[ #5: Водно
[41.98734784287371, 21.431993218498246],
[41.98285237126461, 21.434996896969064],
[41.982055268700734, 21.43482525819931],
[41.975614312962584, 21.43832668805481],
[41.971937733549375, 21.436502948400076],
[41.97538248984099, 21.43135310676406],
[41.98153793295743, 21.42189456450104],
[41.98563607904012, 21.41173553492991],
[41.98914706834681, 21.40632390975952],
[41.993148836140286, 21.410950183835673],
[41.98757415545117, 21.417117118917304],
[41.99148042888061, 21.423517942084803],
],
[ #6: Кисела Вода
[41.987405225853784, 21.432231903272626],
[41.98281304317566, 21.435235977369306],
[41.98199980963907, 21.434957027631757],
[41.97562578450093, 21.438362360131578],
[41.97173954577081, 21.436504125595093],
[41.968428076659336, 21.44695185536242],
[41.96385194392173, 21.43320861490372],
[41.95589477301708, 21.43069553643727],
[41.95602239300942, 21.44388771430386],
[41.95988274753732, 21.45131206885708],
[41.974680134569695, 21.461491584777836],
[41.976389270759356, 21.45737171189467],
[41.97611178885931, 21.45797681851036],
[41.982805039080375, 21.443595886230472],
[41.98428796731331, 21.441763399361665],
[41.98487794010307, 21.441312788247163],
[41.98578202601866, 21.440956592559814],
[41.98653143238881, 21.441063880920414],
[41.98743951388864, 21.441814899444584],
],
[ #7: Аеродром
[41.96521321351477, 21.491369248615232],
[41.96401125335132, 21.486622810953126],
[41.974780392600195, 21.462706089641873],
[41.97635531282277, 21.458144187927246],
[41.97635531282277, 21.458144187927246],
[41.98326756292444, 21.44337272542544],
[41.98441563145085, 21.441977976737697],
[41.985133163767294, 21.441527365623195],
[41.98597824701364, 21.441377161918354],
[41.98671170639861, 21.441591738639552],
[41.98728571219694, 21.442042349754054],
[41.99408330330143, 21.449588420157912],
[41.990111145672934, 21.455437010713727],
[41.99168919937105, 21.460800722268754],
[41.994159810929126, 21.464726959127027],
[41.99039806743705, 21.473845268770564],
[41.99027625458941, 21.473972546095684],
[41.98957488665183, 21.48100973565588],
[41.98415496474574, 21.49122224245667],
[41.98262455031965, 21.495427392315793],
[41.980647710575276, 21.49843107078658],
[41.97822440393778, 21.498860167711012],
[41.97643875056391, 21.50057655540862],
[41.97580100508219, 21.501520568642285],
],
[ #8: Автокоманда+Железара+Ченто
[41.99702382087668, 21.529375076424913],
[41.998991954254535, 21.50402069091797],
[42.00480282872743, 21.48002243120573],
[41.99967233494524, 21.451646805398926],
[42.00205545105743, 21.451719761189455],
[42.00305971566881, 21.456118584301297],
[42.007162689160154, 21.459242821165393],
[42.009349559108614, 21.45964193350665],
[42.0140003919269, 21.454208850991566],
[42.01585315628746, 21.45219612226356],
[42.02093820121273, 21.4492263799184],
[42.02694264184265, 21.451415062474553],
[42.0396144965093, 21.45532036403893],
[42.03132961764397, 21.497755055897873],
[42.02971932393803, 21.52050020406023],
[42.012890897084645, 21.532173177693043],
[41.99702382087668, 21.529375076424913],
],
[ #9: Маџари+Хиподром
[41.993313990077745, 21.530027389526367],
[41.99618366965164, 21.52153015136719],
[41.99657903641696, 21.516311646555554],
[41.99766309718109, 21.50541114911903],
[41.99854604953885, 21.502647399902344],
[42.003634440127776, 21.481962203979492],
[42.0021423941035, 21.471473694109598],
[41.999006394403686, 21.45128631595071],
[41.995240878873986, 21.44975852976131],
[41.993200200904845, 21.45171117792416],
[41.991599497945295, 21.454226016867327],
[41.99091392576721, 21.456972598898577],
[41.99163138484365, 21.45881795870082],
[41.99376777064399, 21.460843563063467],
[41.99467651002937, 21.462560176832998],
[41.995001740795495, 21.465495586280674],
[41.994268376926605, 21.468070506934964],
[41.99324803053007, 21.469937324409337],
[41.983524961557634, 21.498973840934926],
[41.97803948170846, 21.501548761589223],
[41.985918729384345, 21.510715484619144],
],
[ #10: Бардовци
[42.00900286039821, 21.324119409620764],
[42.00941717950984, 21.329697669637987],
[42.011313451772914, 21.345295342839975],
[42.011303890780816, 21.34785705200245],
[42.010905518885565, 21.352319660016256],
[42.01117641204577, 21.356524809875378],
[42.011636098529756, 21.379680114407083],
[42.0132506280016, 21.41325993392542],
[42.01949658186978, 21.4099987973],
[42.02459486494895, 21.412058462537118],
[42.0222350748204, 21.429911501241865],
[42.02716745778609, 21.42905759993369],
[42.02718338863532, 21.434249672718952],
[42.05223658652196, 21.422873554133805],
[42.05260899088653, 21.381681236491644],
[42.0525771424161, 21.3656501734972],
[42.05471098718492, 21.356467499315002],
[42.056080432121995, 21.347915597808093],
[42.05510908486005, 21.343646083410306],
[42.05186053691804, 21.33944093355118],
[42.04565598531368, 21.338149352856306],
[42.03829446127371, 21.336849188389657],
[42.02988388773591, 21.33069593810092],
[42.017852283885176, 21.331820171911886],
[42.0134545726861, 21.33038269721513],
[42.01096877532139, 21.32757211236032],
[42.01028038378219, 21.326297694298397],
],
[ #11: Драчево
[41.948416545200615, 21.511551093055237],
[41.94044102604154, 21.5409871420692],
[41.9360381121176, 21.5409871420692],
[41.93361318913743, 21.534636507588026],
[41.9299118131517, 21.535237243282214],
[41.92589110967575, 21.52965898326499],
[41.92461464288131, 21.512752564443527],
[41.93265595731823, 21.516013701068992],
[41.935017103152745, 21.508118317660006],
[41.935591422706715, 21.501939321948598],
[41.940951489149725, 21.504428084110156],
],
[ #12: Илинден
[41.99817833451146, 21.548629735708737],
[42.001238277097144, 21.560644449592008],
[42.00187574661528, 21.57695013271929],
[41.998815834684244, 21.59634531370227],
[41.99422569089769, 21.598233340169635],
[41.98887010472021, 21.605270529729832],
[41.97815758056011, 21.6071585561972],
[41.97356594703401, 21.60630036234837],
[41.97088734126831, 21.582614212121385],
[41.982748883042774, 21.57849488164714],
[41.98784994197814, 21.56991294315909],
[41.98938017996059, 21.562017559750107],
[41.99142044005076, 21.550346123406353],
],
[ #13: Миладиновци
[41.98923749037232, 21.647618456865054],
[41.99185156769003, 21.652510161803207],
[41.99204283742523, 21.655513840274036],
[41.990831452728585, 21.657144408586763],
[41.98770724895983, 21.656629492277496],
[41.98464665578334, 21.655256382119397],
[41.98190474945355, 21.654569827040326],
[41.97814240675479, 21.653110897497392],
[41.97546399345698, 21.6517377873393],
[41.97284924324992, 21.65002139964169],
[41.9726579158494, 21.647532637480175],
[41.9726579158494, 21.64349912639076],
[41.973933420996886, 21.639980531610664],
[41.977122072114376, 21.63972307345603],
[41.9798004156786, 21.642297655002462],
[41.98133084713901, 21.645387152858127],
[41.98420030698533, 21.648219192559196],
]
]
window.fn.loadPlay = () ->
content = $('#content')[0]
menu = $('#menu')[0]
if window.fn.selected is 'measurements'
menu.close.bind(menu)()
return
content.load 'views/play.html'
.then menu.close.bind(menu)
.then () ->
renderPlay()
data = null
stamps = []
avgs = {}
polys = []
frameCounter = 0
tmInterval = 0
idInterval = null
#
renderPlay = () ->
window.fn.selected = 'measurements'
CENTER = [ 41.99249998, 21.42361109 ]
CITY = 'skopje'
USERNAME = "atonevski"
PASSWORD = "pv1530kay"
parsePos = (s) ->
s.split /\s*,\s*/
.map (v) -> parseFloat(v)
toDTM = (d) ->
throw "#{ d } is not Date()" unless d instanceof Date
dd = (new Date(d - d.getTimezoneOffset()*1000*60))
ymd= dd.toISOString()[0..9]
re = /(\d\d:\d\d:\d\d) GMT([-+]\d+)/gm
s = re.exec d.toString()
"#{ ymd }T#{ s[1] }#{ s[2][0..2] }:#{ s[2][3..4] }"
# get last 24h measurements but only for pm10
getLast24h = () ->
#...
to = new Date()
from = new Date to - 24*60*60*1000
url = "https://#{ CITY }.pulse.eco/rest/dataRaw?" +
"type=pm10&" +
"from=#{ encodeURIComponent toDTM(from) }&" +
"to=#{ encodeURIComponent toDTM(to) }"
$.ajax
url: url
method: 'GET'
username: USERNAME
password: PASSWORD
dataType: "json"
headers:
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
.done (d) =>
data = d
stamps = data
.map (x) -> x.stamp[0..14]
.filter (v, i, self) -> self.indexOf(v) is i
avgs = { }
for m in data
s = m.stamp[0..14]
g = fn.playSensors[m.sensorId].group
unless avgs[s]?
avgs[s] = []
unless avgs[s][g]?
avgs[s][g] = sum: 0, count: 0
avgs[s][g].sum += m.value * 1
avgs[s][g].count++
# for every stamp, for every group calc avg typeVal...
frameCounter = 0
tmInterval = Math.ceil 30000/stamps.length
fnInterval = () ->
stamp = stamps[frameCounter]
avg = avgs[stamps[frameCounter]]
throw "avg undefined" unless avg
# put tm stamp in the right corner
stamp = stamp[0..9] + ' ' + stamp[-4..-1] + '0'
$('#label-id').html stamp
for g, v of avg
if v?
polys[g].setStyle color: getValueColor v.sum/v.count
frameCounter++
if frameCounter >= stamps.length
clearInterval idInterval
console.log "finished play"
$('#label-id').html ''
for p in polys
p.remove()
idInterval = setInterval fnInterval, tmInterval
console.log "started play, frame duration #{ tmInterval }ms"
getSensors = () ->
$.ajax
url: "https://#{ CITY }.pulse.eco/rest/sensor"
method: 'GET'
username: USERNAME
password: PASSWORD
.done (d) ->
# console.log d
for s in d
if window.fn.playSensors[s.sensorId]?
window.fn.playSensors[s.sensorId].position = s.position
window.fn.playSensors[s.sensorId].description = s.description
window.fn.playSensors[s.sensorId].coments = s.coments
else
window.fn.playSensors[s.sensorId] = s
window.fn.playSensors[s.sensorId].name = s.description
ons.notification.toast "Unknown sensor #{ s.sensorId }"
# pos = parsePos s.position
# marker = L.marker pos, { icon: window.fn.markerIcons[0] }
# .addTo window.fn.playMap
# .bindPopup """
# <p>Sensor: #{ window.fn.playSensors[s.sensorId].name }</p>
# <p>Group: #{ window.fn.playSensors[s.sensorId].group }
# """
getLast24h()
renderMap = () ->
window.fn.playMap = L.map 'play-map-id'
.setView CENTER, 12
# L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { }
L.tileLayer 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {}
.addTo window.fn.playMap
# added for lat/lngs
# window.fn.playMap.on 'click', (e) ->
# ons.notification.alert "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })"
# console.log "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })"
# for the sake of groups add them on the map
# almost transparent
polys = []
for i, ll of latlngs
polys[i] = L.polygon ll, color: '#dddddd', weight: 1
.addTo window.fn.playMap
getSensors()
renderMap()
# Darkgreen: rgb(0, 100, 0) hsl(120, 100%, 20%)
# Green: rgb(0, 128, 0) hsl(120, 100%, 25%)
# Forestgreen: rgb(34, 139, 34) hsl(120, 61%, 34%)
# Limegreen: rgb(50, 205, 50) hsl(120, 61%, 50%)
# Lime: rgb(0, 255, 0) hsl(120, 100%, 50%)
# Greenyellow: rgb(173, 255, 47) hsl(84, 100%, 59%)
# Orange: rgb(255, 165, 0) hsl(39, 100%, 50%)
# Orangered: rgb(255, 69, 0) hsl(16, 100%, 50%)
# Crimson: rgb(220, 20, 60) hsl(348, 83%, 47%)
# Darkred: rgb(139, 0, 0) hsl(0, 100%, 27%)
# Maroon: rgb(128, 0, 0) hsl(0, 100%, 25%)
# Darkmagenta: rgb(139, 0, 139) hsl(300, 100%, 27%)
# Purple: rgb(128, 0, 128) hsl(300, 100%, 25%)
# Indigo: rgb(75, 0, 130) hsl(275, 100%, 25%)
# Midnightblue: rgb(25, 25, 112) hsl(240, 64%, 27%)
hsl2rgb = (h, s, l) ->
[r, g, b] = [0, 0, 0]
if s is 0
r = g = b = l; # achromatic
else
hue2rgb = (p, q, t) ->
if t < 0 then t += 1
if t > 1 then t -= 1
if t < 1/6 then return p + (q - p) * 6 * t
if t < 1/2 then return q
if t < 2/3 then return p + (q - p) * (2/3 - t) * 6
p
q = if l < 0.5 then l * (1 + s) else l + s - l * s
p = 2 * l - q
r = hue2rgb(p, q, h + 1/3)
g = hue2rgb(p, q, h)
b = hue2rgb(p, q, h - 1/3)
# [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
"#" +
('0' + Math.round(r * 255).toString(16))[-2..-1] +
('0' + Math.round(g * 255).toString(16))[-2..-1] +
('0' + Math.round(b * 255).toString(16))[-2..-1]
# from range to range
# assume a=[a0, a1], [b0, b1], a0 ≤ t ≤ a1
r2r = (t, a, b) -> (b[0] - b[1])/(a[0] - a[1])*(t - a[0]) + b[0]
rgb2hex = (r, g, b) ->
'#' +
('0' + Math.floor(r%255).toString(16))[-2..-1] +
('0' + Math.floor(g%255).toString(16))[-2..-1] +
('0' + Math.floor(b%255).toString(16))[-2..-1]
# good: [ 0, 50]
# moderate: [ 50, 100]
# sensitive: [100, 250]
# unhealthy: [250, 350]
# veryUnhealthy: [350, 430]
# hazardous: [430, 2000]
#
getValueColor = (val) ->
val = Math.round val+0
switch
when 0 <= val < 50 # good: Darkgreen - Limegreen
# rgb(0, 100, 0) - rgb(50, 205, 50)
ra = [0, 50]
ga = [100, 205]
ba = [0, 50]
ar = [0, 50]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 50 <= val < 100 # moderate: Limegreen - Orange
# rgb(50, 205, 50) - rgb(255, 165, 0)
ra = [50, 255]
ga = [205, 165]
ba = [50, 0]
ar = [50, 100]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 100 <= val < 250 # sensitive: Orange - Crimson
# rgb(255, 165, 0) - rgb(220, 20, 60)
ra = [255, 220]
ga = [165, 20]
ba = [0, 60]
ar = [100, 250]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 250 <= val < 350 # unhealthy: Crimson - Maroon
# rgb(220, 20, 60) - rgb(128, 0, 0)
ra = [220, 128]
ga = [20, 0]
ba = [60, 0]
ar = [250, 350]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 350 <= val < 430 # veryUnhealthy: Maroon - Purple
# rgb(128, 0, 0) - rgb(128, 0, 128)
ra = [128, 128]
ga = [0, 0]
ba = [0, 128]
ar = [350, 430]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 430 <= val < 2000 # hazardous: Purple - Midnightblue
# rgb(128, 0, 128) - rgb(25, 25, 112)
ra = [128, 25]
ga = [0, 25]
ba = [128, 112]
ar = [430, 2000]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
else
'#dddddd'
| 175157 | #
# play.coffee: play last 24h pm10 measurements
#
window.fn.playMap = null
# add group property
window.fn.playSensors =
"1002": { name: '<NAME>', group: 13 }
"11888f3a-bc5e-4a0c-9f27-702984decedf": { name: '<NAME>', group: 9 }
"01440b05-255d-4764-be87-bdf135f32289": { name: '<NAME>', group: 10 }
"bb948861-3fd7-47dd-b986-cb13c9732725": { name: '<NAME>', group: 7 }
"cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0": { name: '<NAME>', group: 1 }
"1005": { name: '<NAME>', group: 3 }
"bc9f31ea-bf3d-416c-86b5-ecba6e98bb24": { name: '<NAME>', group: 3 }
"66710fdc-cdfc-4bbe-93a8-7e796fb8a88d": { name: '<NAME>', group: 2 }
"24eaebc2-ca62-49ff-8b22-880bc131b69f": { name: 'Ц<NAME>', group: 5 }
"b79604bb-0bea-454f-a474-849156e418ea": { name: '<NAME>', group: 11 }
"1004": { name: '<NAME>', group: 8 }
"fc4bfa77-f791-4f93-8c0c-62d8306c599c": { name: '<NAME>', group: 2 }
"cfb0a034-6e29-4803-be02-9215dcac17a8": { name: '<NAME>', group: 4 }
"1003": { name: '<NAME>', group: 1 }
"200cdb67-8dc5-4dcf-ac62-748db636e04e": { name: '<NAME>', group: 6 }
"8d415fa0-77dc-4cb3-8460-a9159800917f": { name: '<NAME>', group: 2 }
"b80e5cd2-76cb-40bf-b784-2a0a312e6264": { name: '<NAME>', group: 4 }
"6380c7cc-df23-4512-ad10-f2b363000579": { name: '<NAME>', group: 6 }
"eaae3b5f-bd71-46f9-85d5-8d3a19c96322": { name: '<NAME>', group: 1 }
"7c497bfd-36b6-4eed-9172-37fd70f17c48": { name: '<NAME>', group: 8 }
"1000": { name: '<NAME>', group: 3 }
"3d7bd712-24a9-482c-b387-a8168b12d3f4": { name: '<NAME>', group: 0 }
"5f718e32-5491-4c3c-98ff-45dc9e287df4": { name: '<NAME>', group: 5 }
"e7a05c01-1d5c-479a-a5a5-419f28cebeef": { name: '<NAME>', group: 3 }
"1001": { name: '<NAME>', group: 7 }
"8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed": { name: '<NAME>', group: 7}
"680b0098-7c4d-44cf-acb1-dc4031e93d34": { name: '<NAME>', group: 12}
# latlngs for group/area
latlngs = [
[ #0: <NAME>ел
[42.02085304335116, 21.449068749034254],
[42.0222566295136, 21.43018848436059],
[42.02723273079618, 21.429244471126886],
[42.02710514332077, 21.434393634219713],
[42.052352164029465, 21.423005104261396],
[42.04594384579999, 21.43919259561023],
[42.0397833869608, 21.454604110248848],
],
[ #1: <NAME>
[42.00014153064202, 21.41316319319767],
[42.00460390831076, 21.38278313095],
[42.00557239019032, 21.380225335657713],
[42.00966193219604, 21.38228917108791],
[42.00930271511426, 21.38507317670075],
[42.00767729097137, 21.39090889487261],
[42.00767729097137, 21.39082307548773],
[42.006179314301946, 21.414080128790324],
[42.0053187585617, 21.416654710336722],
[42.0016532981841, 21.41347939309618],
],
[ #2: <NAME>афталиџе
[41.999901217245906, 21.413094422668596],
[41.993366432064164, 21.411034757431477],
[41.989190193553455, 21.406228871878163],
[41.99748501915229, 21.371961189924015],
[42.00523402234377, 21.38009756173427],
[42.00445313657715, 21.382779417511763],
],
[ #3: Центар
[41.98745837139266, 21.441801552158026],
[41.98758589765055, 21.431760684127],
[41.99153908493555, 21.42352202317851],
[41.98758589765055, 21.417171388697337],
[41.99309313129358, 21.411201094635402],
[41.99978732184316, 21.413260759872532],
[42.00153873372848, 21.41366539376736],
[42.00518184740425, 21.416814956452857],
[42.002058244270216, 21.423101226395328],
[42.00358819149654, 21.42438851716855],
[42.0011892397794, 21.428743322597725],
[41.99854358309758, 21.450155259125392],
[41.99385763206613, 21.448567600505104],
],
[ #4: <NAME>
[42.0104374739155, 21.381418140250933],
[42.005146819652325, 21.379229745936488],
[41.99787942070697, 21.371506001297263],
[42.00227820869816, 21.34760530260808],
[42.00686792414399, 21.331814535790077],
[42.00906704545891, 21.32966905116807],
[42.01126609075234, 21.358590183872767],
[42.011680395122966, 21.379358475013806],
],
[ #5: Водно
[41.98734784287371, 21.431993218498246],
[41.98285237126461, 21.434996896969064],
[41.982055268700734, 21.43482525819931],
[41.975614312962584, 21.43832668805481],
[41.971937733549375, 21.436502948400076],
[41.97538248984099, 21.43135310676406],
[41.98153793295743, 21.42189456450104],
[41.98563607904012, 21.41173553492991],
[41.98914706834681, 21.40632390975952],
[41.993148836140286, 21.410950183835673],
[41.98757415545117, 21.417117118917304],
[41.99148042888061, 21.423517942084803],
],
[ #6: <NAME>
[41.987405225853784, 21.432231903272626],
[41.98281304317566, 21.435235977369306],
[41.98199980963907, 21.434957027631757],
[41.97562578450093, 21.438362360131578],
[41.97173954577081, 21.436504125595093],
[41.968428076659336, 21.44695185536242],
[41.96385194392173, 21.43320861490372],
[41.95589477301708, 21.43069553643727],
[41.95602239300942, 21.44388771430386],
[41.95988274753732, 21.45131206885708],
[41.974680134569695, 21.461491584777836],
[41.976389270759356, 21.45737171189467],
[41.97611178885931, 21.45797681851036],
[41.982805039080375, 21.443595886230472],
[41.98428796731331, 21.441763399361665],
[41.98487794010307, 21.441312788247163],
[41.98578202601866, 21.440956592559814],
[41.98653143238881, 21.441063880920414],
[41.98743951388864, 21.441814899444584],
],
[ #7: <NAME>
[41.96521321351477, 21.491369248615232],
[41.96401125335132, 21.486622810953126],
[41.974780392600195, 21.462706089641873],
[41.97635531282277, 21.458144187927246],
[41.97635531282277, 21.458144187927246],
[41.98326756292444, 21.44337272542544],
[41.98441563145085, 21.441977976737697],
[41.985133163767294, 21.441527365623195],
[41.98597824701364, 21.441377161918354],
[41.98671170639861, 21.441591738639552],
[41.98728571219694, 21.442042349754054],
[41.99408330330143, 21.449588420157912],
[41.990111145672934, 21.455437010713727],
[41.99168919937105, 21.460800722268754],
[41.994159810929126, 21.464726959127027],
[41.99039806743705, 21.473845268770564],
[41.99027625458941, 21.473972546095684],
[41.98957488665183, 21.48100973565588],
[41.98415496474574, 21.49122224245667],
[41.98262455031965, 21.495427392315793],
[41.980647710575276, 21.49843107078658],
[41.97822440393778, 21.498860167711012],
[41.97643875056391, 21.50057655540862],
[41.97580100508219, 21.501520568642285],
],
[ #8: Автокоманда+Железара+Ченто
[41.99702382087668, 21.529375076424913],
[41.998991954254535, 21.50402069091797],
[42.00480282872743, 21.48002243120573],
[41.99967233494524, 21.451646805398926],
[42.00205545105743, 21.451719761189455],
[42.00305971566881, 21.456118584301297],
[42.007162689160154, 21.459242821165393],
[42.009349559108614, 21.45964193350665],
[42.0140003919269, 21.454208850991566],
[42.01585315628746, 21.45219612226356],
[42.02093820121273, 21.4492263799184],
[42.02694264184265, 21.451415062474553],
[42.0396144965093, 21.45532036403893],
[42.03132961764397, 21.497755055897873],
[42.02971932393803, 21.52050020406023],
[42.012890897084645, 21.532173177693043],
[41.99702382087668, 21.529375076424913],
],
[ #9: Маџари+Хиподром
[41.993313990077745, 21.530027389526367],
[41.99618366965164, 21.52153015136719],
[41.99657903641696, 21.516311646555554],
[41.99766309718109, 21.50541114911903],
[41.99854604953885, 21.502647399902344],
[42.003634440127776, 21.481962203979492],
[42.0021423941035, 21.471473694109598],
[41.999006394403686, 21.45128631595071],
[41.995240878873986, 21.44975852976131],
[41.993200200904845, 21.45171117792416],
[41.991599497945295, 21.454226016867327],
[41.99091392576721, 21.456972598898577],
[41.99163138484365, 21.45881795870082],
[41.99376777064399, 21.460843563063467],
[41.99467651002937, 21.462560176832998],
[41.995001740795495, 21.465495586280674],
[41.994268376926605, 21.468070506934964],
[41.99324803053007, 21.469937324409337],
[41.983524961557634, 21.498973840934926],
[41.97803948170846, 21.501548761589223],
[41.985918729384345, 21.510715484619144],
],
[ #10: <NAME>ци
[42.00900286039821, 21.324119409620764],
[42.00941717950984, 21.329697669637987],
[42.011313451772914, 21.345295342839975],
[42.011303890780816, 21.34785705200245],
[42.010905518885565, 21.352319660016256],
[42.01117641204577, 21.356524809875378],
[42.011636098529756, 21.379680114407083],
[42.0132506280016, 21.41325993392542],
[42.01949658186978, 21.4099987973],
[42.02459486494895, 21.412058462537118],
[42.0222350748204, 21.429911501241865],
[42.02716745778609, 21.42905759993369],
[42.02718338863532, 21.434249672718952],
[42.05223658652196, 21.422873554133805],
[42.05260899088653, 21.381681236491644],
[42.0525771424161, 21.3656501734972],
[42.05471098718492, 21.356467499315002],
[42.056080432121995, 21.347915597808093],
[42.05510908486005, 21.343646083410306],
[42.05186053691804, 21.33944093355118],
[42.04565598531368, 21.338149352856306],
[42.03829446127371, 21.336849188389657],
[42.02988388773591, 21.33069593810092],
[42.017852283885176, 21.331820171911886],
[42.0134545726861, 21.33038269721513],
[42.01096877532139, 21.32757211236032],
[42.01028038378219, 21.326297694298397],
],
[ #11: <NAME>
[41.948416545200615, 21.511551093055237],
[41.94044102604154, 21.5409871420692],
[41.9360381121176, 21.5409871420692],
[41.93361318913743, 21.534636507588026],
[41.9299118131517, 21.535237243282214],
[41.92589110967575, 21.52965898326499],
[41.92461464288131, 21.512752564443527],
[41.93265595731823, 21.516013701068992],
[41.935017103152745, 21.508118317660006],
[41.935591422706715, 21.501939321948598],
[41.940951489149725, 21.504428084110156],
],
[ #12: <NAME>
[41.99817833451146, 21.548629735708737],
[42.001238277097144, 21.560644449592008],
[42.00187574661528, 21.57695013271929],
[41.998815834684244, 21.59634531370227],
[41.99422569089769, 21.598233340169635],
[41.98887010472021, 21.605270529729832],
[41.97815758056011, 21.6071585561972],
[41.97356594703401, 21.60630036234837],
[41.97088734126831, 21.582614212121385],
[41.982748883042774, 21.57849488164714],
[41.98784994197814, 21.56991294315909],
[41.98938017996059, 21.562017559750107],
[41.99142044005076, 21.550346123406353],
],
[ #13: Миладиновци
[41.98923749037232, 21.647618456865054],
[41.99185156769003, 21.652510161803207],
[41.99204283742523, 21.655513840274036],
[41.990831452728585, 21.657144408586763],
[41.98770724895983, 21.656629492277496],
[41.98464665578334, 21.655256382119397],
[41.98190474945355, 21.654569827040326],
[41.97814240675479, 21.653110897497392],
[41.97546399345698, 21.6517377873393],
[41.97284924324992, 21.65002139964169],
[41.9726579158494, 21.647532637480175],
[41.9726579158494, 21.64349912639076],
[41.973933420996886, 21.639980531610664],
[41.977122072114376, 21.63972307345603],
[41.9798004156786, 21.642297655002462],
[41.98133084713901, 21.645387152858127],
[41.98420030698533, 21.648219192559196],
]
]
window.fn.loadPlay = () ->
content = $('#content')[0]
menu = $('#menu')[0]
if window.fn.selected is 'measurements'
menu.close.bind(menu)()
return
content.load 'views/play.html'
.then menu.close.bind(menu)
.then () ->
renderPlay()
data = null
stamps = []
avgs = {}
polys = []
frameCounter = 0
tmInterval = 0
idInterval = null
#
renderPlay = () ->
window.fn.selected = 'measurements'
CENTER = [ 41.99249998, 21.42361109 ]
CITY = 'skopje'
USERNAME = "atonevski"
PASSWORD = "<PASSWORD>"
parsePos = (s) ->
s.split /\s*,\s*/
.map (v) -> parseFloat(v)
toDTM = (d) ->
throw "#{ d } is not Date()" unless d instanceof Date
dd = (new Date(d - d.getTimezoneOffset()*1000*60))
ymd= dd.toISOString()[0..9]
re = /(\d\d:\d\d:\d\d) GMT([-+]\d+)/gm
s = re.exec d.toString()
"#{ ymd }T#{ s[1] }#{ s[2][0..2] }:#{ s[2][3..4] }"
# get last 24h measurements but only for pm10
getLast24h = () ->
#...
to = new Date()
from = new Date to - 24*60*60*1000
url = "https://#{ CITY }.pulse.eco/rest/dataRaw?" +
"type=pm10&" +
"from=#{ encodeURIComponent toDTM(from) }&" +
"to=#{ encodeURIComponent toDTM(to) }"
$.ajax
url: url
method: 'GET'
username: USERNAME
password: <PASSWORD>
dataType: "json"
headers:
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
.done (d) =>
data = d
stamps = data
.map (x) -> x.stamp[0..14]
.filter (v, i, self) -> self.indexOf(v) is i
avgs = { }
for m in data
s = m.stamp[0..14]
g = fn.playSensors[m.sensorId].group
unless avgs[s]?
avgs[s] = []
unless avgs[s][g]?
avgs[s][g] = sum: 0, count: 0
avgs[s][g].sum += m.value * 1
avgs[s][g].count++
# for every stamp, for every group calc avg typeVal...
frameCounter = 0
tmInterval = Math.ceil 30000/stamps.length
fnInterval = () ->
stamp = stamps[frameCounter]
avg = avgs[stamps[frameCounter]]
throw "avg undefined" unless avg
# put tm stamp in the right corner
stamp = stamp[0..9] + ' ' + stamp[-4..-1] + '0'
$('#label-id').html stamp
for g, v of avg
if v?
polys[g].setStyle color: getValueColor v.sum/v.count
frameCounter++
if frameCounter >= stamps.length
clearInterval idInterval
console.log "finished play"
$('#label-id').html ''
for p in polys
p.remove()
idInterval = setInterval fnInterval, tmInterval
console.log "started play, frame duration #{ tmInterval }ms"
getSensors = () ->
$.ajax
url: "https://#{ CITY }.pulse.eco/rest/sensor"
method: 'GET'
username: USERNAME
password: <PASSWORD>
.done (d) ->
# console.log d
for s in d
if window.fn.playSensors[s.sensorId]?
window.fn.playSensors[s.sensorId].position = s.position
window.fn.playSensors[s.sensorId].description = s.description
window.fn.playSensors[s.sensorId].coments = s.coments
else
window.fn.playSensors[s.sensorId] = s
window.fn.playSensors[s.sensorId].name = s.description
ons.notification.toast "Unknown sensor #{ s.sensorId }"
# pos = parsePos s.position
# marker = L.marker pos, { icon: window.fn.markerIcons[0] }
# .addTo window.fn.playMap
# .bindPopup """
# <p>Sensor: #{ window.fn.playSensors[s.sensorId].name }</p>
# <p>Group: #{ window.fn.playSensors[s.sensorId].group }
# """
getLast24h()
renderMap = () ->
window.fn.playMap = L.map 'play-map-id'
.setView CENTER, 12
# L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { }
L.tileLayer 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {}
.addTo window.fn.playMap
# added for lat/lngs
# window.fn.playMap.on 'click', (e) ->
# ons.notification.alert "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })"
# console.log "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })"
# for the sake of groups add them on the map
# almost transparent
polys = []
for i, ll of latlngs
polys[i] = L.polygon ll, color: '#dddddd', weight: 1
.addTo window.fn.playMap
getSensors()
renderMap()
# Darkgreen: rgb(0, 100, 0) hsl(120, 100%, 20%)
# Green: rgb(0, 128, 0) hsl(120, 100%, 25%)
# Forestgreen: rgb(34, 139, 34) hsl(120, 61%, 34%)
# Limegreen: rgb(50, 205, 50) hsl(120, 61%, 50%)
# Lime: rgb(0, 255, 0) hsl(120, 100%, 50%)
# Greenyellow: rgb(173, 255, 47) hsl(84, 100%, 59%)
# Orange: rgb(255, 165, 0) hsl(39, 100%, 50%)
# Orangered: rgb(255, 69, 0) hsl(16, 100%, 50%)
# Crimson: rgb(220, 20, 60) hsl(348, 83%, 47%)
# Darkred: rgb(139, 0, 0) hsl(0, 100%, 27%)
# Maroon: rgb(128, 0, 0) hsl(0, 100%, 25%)
# Darkmagenta: rgb(139, 0, 139) hsl(300, 100%, 27%)
# Purple: rgb(128, 0, 128) hsl(300, 100%, 25%)
# Indigo: rgb(75, 0, 130) hsl(275, 100%, 25%)
# Midnightblue: rgb(25, 25, 112) hsl(240, 64%, 27%)
hsl2rgb = (h, s, l) ->
[r, g, b] = [0, 0, 0]
if s is 0
r = g = b = l; # achromatic
else
hue2rgb = (p, q, t) ->
if t < 0 then t += 1
if t > 1 then t -= 1
if t < 1/6 then return p + (q - p) * 6 * t
if t < 1/2 then return q
if t < 2/3 then return p + (q - p) * (2/3 - t) * 6
p
q = if l < 0.5 then l * (1 + s) else l + s - l * s
p = 2 * l - q
r = hue2rgb(p, q, h + 1/3)
g = hue2rgb(p, q, h)
b = hue2rgb(p, q, h - 1/3)
# [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
"#" +
('0' + Math.round(r * 255).toString(16))[-2..-1] +
('0' + Math.round(g * 255).toString(16))[-2..-1] +
('0' + Math.round(b * 255).toString(16))[-2..-1]
# from range to range
# assume a=[a0, a1], [b0, b1], a0 ≤ t ≤ a1
r2r = (t, a, b) -> (b[0] - b[1])/(a[0] - a[1])*(t - a[0]) + b[0]
rgb2hex = (r, g, b) ->
'#' +
('0' + Math.floor(r%255).toString(16))[-2..-1] +
('0' + Math.floor(g%255).toString(16))[-2..-1] +
('0' + Math.floor(b%255).toString(16))[-2..-1]
# good: [ 0, 50]
# moderate: [ 50, 100]
# sensitive: [100, 250]
# unhealthy: [250, 350]
# veryUnhealthy: [350, 430]
# hazardous: [430, 2000]
#
getValueColor = (val) ->
val = Math.round val+0
switch
when 0 <= val < 50 # good: Darkgreen - Limegreen
# rgb(0, 100, 0) - rgb(50, 205, 50)
ra = [0, 50]
ga = [100, 205]
ba = [0, 50]
ar = [0, 50]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 50 <= val < 100 # moderate: Limegreen - Orange
# rgb(50, 205, 50) - rgb(255, 165, 0)
ra = [50, 255]
ga = [205, 165]
ba = [50, 0]
ar = [50, 100]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 100 <= val < 250 # sensitive: Orange - Crimson
# rgb(255, 165, 0) - rgb(220, 20, 60)
ra = [255, 220]
ga = [165, 20]
ba = [0, 60]
ar = [100, 250]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 250 <= val < 350 # unhealthy: Crimson - Maroon
# rgb(220, 20, 60) - rgb(128, 0, 0)
ra = [220, 128]
ga = [20, 0]
ba = [60, 0]
ar = [250, 350]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 350 <= val < 430 # veryUnhealthy: Maroon - Purple
# rgb(128, 0, 0) - rgb(128, 0, 128)
ra = [128, 128]
ga = [0, 0]
ba = [0, 128]
ar = [350, 430]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 430 <= val < 2000 # hazardous: Purple - Midnightblue
# rgb(128, 0, 128) - rgb(25, 25, 112)
ra = [128, 25]
ga = [0, 25]
ba = [128, 112]
ar = [430, 2000]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
else
'#dddddd'
| true | #
# play.coffee: play last 24h pm10 measurements
#
window.fn.playMap = null
# add group property
window.fn.playSensors =
"1002": { name: 'PI:NAME:<NAME>END_PI', group: 13 }
"11888f3a-bc5e-4a0c-9f27-702984decedf": { name: 'PI:NAME:<NAME>END_PI', group: 9 }
"01440b05-255d-4764-be87-bdf135f32289": { name: 'PI:NAME:<NAME>END_PI', group: 10 }
"bb948861-3fd7-47dd-b986-cb13c9732725": { name: 'PI:NAME:<NAME>END_PI', group: 7 }
"cec29ba1-5414-4cf3-bbcc-8ce4db1da5d0": { name: 'PI:NAME:<NAME>END_PI', group: 1 }
"1005": { name: 'PI:NAME:<NAME>END_PI', group: 3 }
"bc9f31ea-bf3d-416c-86b5-ecba6e98bb24": { name: 'PI:NAME:<NAME>END_PI', group: 3 }
"66710fdc-cdfc-4bbe-93a8-7e796fb8a88d": { name: 'PI:NAME:<NAME>END_PI', group: 2 }
"24eaebc2-ca62-49ff-8b22-880bc131b69f": { name: 'ЦPI:NAME:<NAME>END_PI', group: 5 }
"b79604bb-0bea-454f-a474-849156e418ea": { name: 'PI:NAME:<NAME>END_PI', group: 11 }
"1004": { name: 'PI:NAME:<NAME>END_PI', group: 8 }
"fc4bfa77-f791-4f93-8c0c-62d8306c599c": { name: 'PI:NAME:<NAME>END_PI', group: 2 }
"cfb0a034-6e29-4803-be02-9215dcac17a8": { name: 'PI:NAME:<NAME>END_PI', group: 4 }
"1003": { name: 'PI:NAME:<NAME>END_PI', group: 1 }
"200cdb67-8dc5-4dcf-ac62-748db636e04e": { name: 'PI:NAME:<NAME>END_PI', group: 6 }
"8d415fa0-77dc-4cb3-8460-a9159800917f": { name: 'PI:NAME:<NAME>END_PI', group: 2 }
"b80e5cd2-76cb-40bf-b784-2a0a312e6264": { name: 'PI:NAME:<NAME>END_PI', group: 4 }
"6380c7cc-df23-4512-ad10-f2b363000579": { name: 'PI:NAME:<NAME>END_PI', group: 6 }
"eaae3b5f-bd71-46f9-85d5-8d3a19c96322": { name: 'PI:NAME:<NAME>END_PI', group: 1 }
"7c497bfd-36b6-4eed-9172-37fd70f17c48": { name: 'PI:NAME:<NAME>END_PI', group: 8 }
"1000": { name: 'PI:NAME:<NAME>END_PI', group: 3 }
"3d7bd712-24a9-482c-b387-a8168b12d3f4": { name: 'PI:NAME:<NAME>END_PI', group: 0 }
"5f718e32-5491-4c3c-98ff-45dc9e287df4": { name: 'PI:NAME:<NAME>END_PI', group: 5 }
"e7a05c01-1d5c-479a-a5a5-419f28cebeef": { name: 'PI:NAME:<NAME>END_PI', group: 3 }
"1001": { name: 'PI:NAME:<NAME>END_PI', group: 7 }
"8ad9e315-0e23-4dc0-a26f-ba5a17d4d7ed": { name: 'PI:NAME:<NAME>END_PI', group: 7}
"680b0098-7c4d-44cf-acb1-dc4031e93d34": { name: 'PI:NAME:<NAME>END_PI', group: 12}
# latlngs for group/area
latlngs = [
[ #0: PI:NAME:<NAME>END_PIел
[42.02085304335116, 21.449068749034254],
[42.0222566295136, 21.43018848436059],
[42.02723273079618, 21.429244471126886],
[42.02710514332077, 21.434393634219713],
[42.052352164029465, 21.423005104261396],
[42.04594384579999, 21.43919259561023],
[42.0397833869608, 21.454604110248848],
],
[ #1: PI:NAME:<NAME>END_PI
[42.00014153064202, 21.41316319319767],
[42.00460390831076, 21.38278313095],
[42.00557239019032, 21.380225335657713],
[42.00966193219604, 21.38228917108791],
[42.00930271511426, 21.38507317670075],
[42.00767729097137, 21.39090889487261],
[42.00767729097137, 21.39082307548773],
[42.006179314301946, 21.414080128790324],
[42.0053187585617, 21.416654710336722],
[42.0016532981841, 21.41347939309618],
],
[ #2: PI:NAME:<NAME>END_PIафталиџе
[41.999901217245906, 21.413094422668596],
[41.993366432064164, 21.411034757431477],
[41.989190193553455, 21.406228871878163],
[41.99748501915229, 21.371961189924015],
[42.00523402234377, 21.38009756173427],
[42.00445313657715, 21.382779417511763],
],
[ #3: Центар
[41.98745837139266, 21.441801552158026],
[41.98758589765055, 21.431760684127],
[41.99153908493555, 21.42352202317851],
[41.98758589765055, 21.417171388697337],
[41.99309313129358, 21.411201094635402],
[41.99978732184316, 21.413260759872532],
[42.00153873372848, 21.41366539376736],
[42.00518184740425, 21.416814956452857],
[42.002058244270216, 21.423101226395328],
[42.00358819149654, 21.42438851716855],
[42.0011892397794, 21.428743322597725],
[41.99854358309758, 21.450155259125392],
[41.99385763206613, 21.448567600505104],
],
[ #4: PI:NAME:<NAME>END_PI
[42.0104374739155, 21.381418140250933],
[42.005146819652325, 21.379229745936488],
[41.99787942070697, 21.371506001297263],
[42.00227820869816, 21.34760530260808],
[42.00686792414399, 21.331814535790077],
[42.00906704545891, 21.32966905116807],
[42.01126609075234, 21.358590183872767],
[42.011680395122966, 21.379358475013806],
],
[ #5: Водно
[41.98734784287371, 21.431993218498246],
[41.98285237126461, 21.434996896969064],
[41.982055268700734, 21.43482525819931],
[41.975614312962584, 21.43832668805481],
[41.971937733549375, 21.436502948400076],
[41.97538248984099, 21.43135310676406],
[41.98153793295743, 21.42189456450104],
[41.98563607904012, 21.41173553492991],
[41.98914706834681, 21.40632390975952],
[41.993148836140286, 21.410950183835673],
[41.98757415545117, 21.417117118917304],
[41.99148042888061, 21.423517942084803],
],
[ #6: PI:NAME:<NAME>END_PI
[41.987405225853784, 21.432231903272626],
[41.98281304317566, 21.435235977369306],
[41.98199980963907, 21.434957027631757],
[41.97562578450093, 21.438362360131578],
[41.97173954577081, 21.436504125595093],
[41.968428076659336, 21.44695185536242],
[41.96385194392173, 21.43320861490372],
[41.95589477301708, 21.43069553643727],
[41.95602239300942, 21.44388771430386],
[41.95988274753732, 21.45131206885708],
[41.974680134569695, 21.461491584777836],
[41.976389270759356, 21.45737171189467],
[41.97611178885931, 21.45797681851036],
[41.982805039080375, 21.443595886230472],
[41.98428796731331, 21.441763399361665],
[41.98487794010307, 21.441312788247163],
[41.98578202601866, 21.440956592559814],
[41.98653143238881, 21.441063880920414],
[41.98743951388864, 21.441814899444584],
],
[ #7: PI:NAME:<NAME>END_PI
[41.96521321351477, 21.491369248615232],
[41.96401125335132, 21.486622810953126],
[41.974780392600195, 21.462706089641873],
[41.97635531282277, 21.458144187927246],
[41.97635531282277, 21.458144187927246],
[41.98326756292444, 21.44337272542544],
[41.98441563145085, 21.441977976737697],
[41.985133163767294, 21.441527365623195],
[41.98597824701364, 21.441377161918354],
[41.98671170639861, 21.441591738639552],
[41.98728571219694, 21.442042349754054],
[41.99408330330143, 21.449588420157912],
[41.990111145672934, 21.455437010713727],
[41.99168919937105, 21.460800722268754],
[41.994159810929126, 21.464726959127027],
[41.99039806743705, 21.473845268770564],
[41.99027625458941, 21.473972546095684],
[41.98957488665183, 21.48100973565588],
[41.98415496474574, 21.49122224245667],
[41.98262455031965, 21.495427392315793],
[41.980647710575276, 21.49843107078658],
[41.97822440393778, 21.498860167711012],
[41.97643875056391, 21.50057655540862],
[41.97580100508219, 21.501520568642285],
],
[ #8: Автокоманда+Железара+Ченто
[41.99702382087668, 21.529375076424913],
[41.998991954254535, 21.50402069091797],
[42.00480282872743, 21.48002243120573],
[41.99967233494524, 21.451646805398926],
[42.00205545105743, 21.451719761189455],
[42.00305971566881, 21.456118584301297],
[42.007162689160154, 21.459242821165393],
[42.009349559108614, 21.45964193350665],
[42.0140003919269, 21.454208850991566],
[42.01585315628746, 21.45219612226356],
[42.02093820121273, 21.4492263799184],
[42.02694264184265, 21.451415062474553],
[42.0396144965093, 21.45532036403893],
[42.03132961764397, 21.497755055897873],
[42.02971932393803, 21.52050020406023],
[42.012890897084645, 21.532173177693043],
[41.99702382087668, 21.529375076424913],
],
[ #9: Маџари+Хиподром
[41.993313990077745, 21.530027389526367],
[41.99618366965164, 21.52153015136719],
[41.99657903641696, 21.516311646555554],
[41.99766309718109, 21.50541114911903],
[41.99854604953885, 21.502647399902344],
[42.003634440127776, 21.481962203979492],
[42.0021423941035, 21.471473694109598],
[41.999006394403686, 21.45128631595071],
[41.995240878873986, 21.44975852976131],
[41.993200200904845, 21.45171117792416],
[41.991599497945295, 21.454226016867327],
[41.99091392576721, 21.456972598898577],
[41.99163138484365, 21.45881795870082],
[41.99376777064399, 21.460843563063467],
[41.99467651002937, 21.462560176832998],
[41.995001740795495, 21.465495586280674],
[41.994268376926605, 21.468070506934964],
[41.99324803053007, 21.469937324409337],
[41.983524961557634, 21.498973840934926],
[41.97803948170846, 21.501548761589223],
[41.985918729384345, 21.510715484619144],
],
[ #10: PI:NAME:<NAME>END_PIци
[42.00900286039821, 21.324119409620764],
[42.00941717950984, 21.329697669637987],
[42.011313451772914, 21.345295342839975],
[42.011303890780816, 21.34785705200245],
[42.010905518885565, 21.352319660016256],
[42.01117641204577, 21.356524809875378],
[42.011636098529756, 21.379680114407083],
[42.0132506280016, 21.41325993392542],
[42.01949658186978, 21.4099987973],
[42.02459486494895, 21.412058462537118],
[42.0222350748204, 21.429911501241865],
[42.02716745778609, 21.42905759993369],
[42.02718338863532, 21.434249672718952],
[42.05223658652196, 21.422873554133805],
[42.05260899088653, 21.381681236491644],
[42.0525771424161, 21.3656501734972],
[42.05471098718492, 21.356467499315002],
[42.056080432121995, 21.347915597808093],
[42.05510908486005, 21.343646083410306],
[42.05186053691804, 21.33944093355118],
[42.04565598531368, 21.338149352856306],
[42.03829446127371, 21.336849188389657],
[42.02988388773591, 21.33069593810092],
[42.017852283885176, 21.331820171911886],
[42.0134545726861, 21.33038269721513],
[42.01096877532139, 21.32757211236032],
[42.01028038378219, 21.326297694298397],
],
[ #11: PI:NAME:<NAME>END_PI
[41.948416545200615, 21.511551093055237],
[41.94044102604154, 21.5409871420692],
[41.9360381121176, 21.5409871420692],
[41.93361318913743, 21.534636507588026],
[41.9299118131517, 21.535237243282214],
[41.92589110967575, 21.52965898326499],
[41.92461464288131, 21.512752564443527],
[41.93265595731823, 21.516013701068992],
[41.935017103152745, 21.508118317660006],
[41.935591422706715, 21.501939321948598],
[41.940951489149725, 21.504428084110156],
],
[ #12: PI:NAME:<NAME>END_PI
[41.99817833451146, 21.548629735708737],
[42.001238277097144, 21.560644449592008],
[42.00187574661528, 21.57695013271929],
[41.998815834684244, 21.59634531370227],
[41.99422569089769, 21.598233340169635],
[41.98887010472021, 21.605270529729832],
[41.97815758056011, 21.6071585561972],
[41.97356594703401, 21.60630036234837],
[41.97088734126831, 21.582614212121385],
[41.982748883042774, 21.57849488164714],
[41.98784994197814, 21.56991294315909],
[41.98938017996059, 21.562017559750107],
[41.99142044005076, 21.550346123406353],
],
[ #13: Миладиновци
[41.98923749037232, 21.647618456865054],
[41.99185156769003, 21.652510161803207],
[41.99204283742523, 21.655513840274036],
[41.990831452728585, 21.657144408586763],
[41.98770724895983, 21.656629492277496],
[41.98464665578334, 21.655256382119397],
[41.98190474945355, 21.654569827040326],
[41.97814240675479, 21.653110897497392],
[41.97546399345698, 21.6517377873393],
[41.97284924324992, 21.65002139964169],
[41.9726579158494, 21.647532637480175],
[41.9726579158494, 21.64349912639076],
[41.973933420996886, 21.639980531610664],
[41.977122072114376, 21.63972307345603],
[41.9798004156786, 21.642297655002462],
[41.98133084713901, 21.645387152858127],
[41.98420030698533, 21.648219192559196],
]
]
window.fn.loadPlay = () ->
content = $('#content')[0]
menu = $('#menu')[0]
if window.fn.selected is 'measurements'
menu.close.bind(menu)()
return
content.load 'views/play.html'
.then menu.close.bind(menu)
.then () ->
renderPlay()
data = null
stamps = []
avgs = {}
polys = []
frameCounter = 0
tmInterval = 0
idInterval = null
#
renderPlay = () ->
window.fn.selected = 'measurements'
CENTER = [ 41.99249998, 21.42361109 ]
CITY = 'skopje'
USERNAME = "atonevski"
PASSWORD = "PI:PASSWORD:<PASSWORD>END_PI"
parsePos = (s) ->
s.split /\s*,\s*/
.map (v) -> parseFloat(v)
toDTM = (d) ->
throw "#{ d } is not Date()" unless d instanceof Date
dd = (new Date(d - d.getTimezoneOffset()*1000*60))
ymd= dd.toISOString()[0..9]
re = /(\d\d:\d\d:\d\d) GMT([-+]\d+)/gm
s = re.exec d.toString()
"#{ ymd }T#{ s[1] }#{ s[2][0..2] }:#{ s[2][3..4] }"
# get last 24h measurements but only for pm10
getLast24h = () ->
#...
to = new Date()
from = new Date to - 24*60*60*1000
url = "https://#{ CITY }.pulse.eco/rest/dataRaw?" +
"type=pm10&" +
"from=#{ encodeURIComponent toDTM(from) }&" +
"to=#{ encodeURIComponent toDTM(to) }"
$.ajax
url: url
method: 'GET'
username: USERNAME
password: PI:PASSWORD:<PASSWORD>END_PI
dataType: "json"
headers:
"Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
.done (d) =>
data = d
stamps = data
.map (x) -> x.stamp[0..14]
.filter (v, i, self) -> self.indexOf(v) is i
avgs = { }
for m in data
s = m.stamp[0..14]
g = fn.playSensors[m.sensorId].group
unless avgs[s]?
avgs[s] = []
unless avgs[s][g]?
avgs[s][g] = sum: 0, count: 0
avgs[s][g].sum += m.value * 1
avgs[s][g].count++
# for every stamp, for every group calc avg typeVal...
frameCounter = 0
tmInterval = Math.ceil 30000/stamps.length
fnInterval = () ->
stamp = stamps[frameCounter]
avg = avgs[stamps[frameCounter]]
throw "avg undefined" unless avg
# put tm stamp in the right corner
stamp = stamp[0..9] + ' ' + stamp[-4..-1] + '0'
$('#label-id').html stamp
for g, v of avg
if v?
polys[g].setStyle color: getValueColor v.sum/v.count
frameCounter++
if frameCounter >= stamps.length
clearInterval idInterval
console.log "finished play"
$('#label-id').html ''
for p in polys
p.remove()
idInterval = setInterval fnInterval, tmInterval
console.log "started play, frame duration #{ tmInterval }ms"
getSensors = () ->
$.ajax
url: "https://#{ CITY }.pulse.eco/rest/sensor"
method: 'GET'
username: USERNAME
password: PI:PASSWORD:<PASSWORD>END_PI
.done (d) ->
# console.log d
for s in d
if window.fn.playSensors[s.sensorId]?
window.fn.playSensors[s.sensorId].position = s.position
window.fn.playSensors[s.sensorId].description = s.description
window.fn.playSensors[s.sensorId].coments = s.coments
else
window.fn.playSensors[s.sensorId] = s
window.fn.playSensors[s.sensorId].name = s.description
ons.notification.toast "Unknown sensor #{ s.sensorId }"
# pos = parsePos s.position
# marker = L.marker pos, { icon: window.fn.markerIcons[0] }
# .addTo window.fn.playMap
# .bindPopup """
# <p>Sensor: #{ window.fn.playSensors[s.sensorId].name }</p>
# <p>Group: #{ window.fn.playSensors[s.sensorId].group }
# """
getLast24h()
renderMap = () ->
window.fn.playMap = L.map 'play-map-id'
.setView CENTER, 12
# L.tileLayer 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { }
L.tileLayer 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', {}
.addTo window.fn.playMap
# added for lat/lngs
# window.fn.playMap.on 'click', (e) ->
# ons.notification.alert "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })"
# console.log "Pos: (#{ e.latlng.lat }, #{ e.latlng.lng })"
# for the sake of groups add them on the map
# almost transparent
polys = []
for i, ll of latlngs
polys[i] = L.polygon ll, color: '#dddddd', weight: 1
.addTo window.fn.playMap
getSensors()
renderMap()
# Darkgreen: rgb(0, 100, 0) hsl(120, 100%, 20%)
# Green: rgb(0, 128, 0) hsl(120, 100%, 25%)
# Forestgreen: rgb(34, 139, 34) hsl(120, 61%, 34%)
# Limegreen: rgb(50, 205, 50) hsl(120, 61%, 50%)
# Lime: rgb(0, 255, 0) hsl(120, 100%, 50%)
# Greenyellow: rgb(173, 255, 47) hsl(84, 100%, 59%)
# Orange: rgb(255, 165, 0) hsl(39, 100%, 50%)
# Orangered: rgb(255, 69, 0) hsl(16, 100%, 50%)
# Crimson: rgb(220, 20, 60) hsl(348, 83%, 47%)
# Darkred: rgb(139, 0, 0) hsl(0, 100%, 27%)
# Maroon: rgb(128, 0, 0) hsl(0, 100%, 25%)
# Darkmagenta: rgb(139, 0, 139) hsl(300, 100%, 27%)
# Purple: rgb(128, 0, 128) hsl(300, 100%, 25%)
# Indigo: rgb(75, 0, 130) hsl(275, 100%, 25%)
# Midnightblue: rgb(25, 25, 112) hsl(240, 64%, 27%)
hsl2rgb = (h, s, l) ->
[r, g, b] = [0, 0, 0]
if s is 0
r = g = b = l; # achromatic
else
hue2rgb = (p, q, t) ->
if t < 0 then t += 1
if t > 1 then t -= 1
if t < 1/6 then return p + (q - p) * 6 * t
if t < 1/2 then return q
if t < 2/3 then return p + (q - p) * (2/3 - t) * 6
p
q = if l < 0.5 then l * (1 + s) else l + s - l * s
p = 2 * l - q
r = hue2rgb(p, q, h + 1/3)
g = hue2rgb(p, q, h)
b = hue2rgb(p, q, h - 1/3)
# [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]
"#" +
('0' + Math.round(r * 255).toString(16))[-2..-1] +
('0' + Math.round(g * 255).toString(16))[-2..-1] +
('0' + Math.round(b * 255).toString(16))[-2..-1]
# from range to range
# assume a=[a0, a1], [b0, b1], a0 ≤ t ≤ a1
r2r = (t, a, b) -> (b[0] - b[1])/(a[0] - a[1])*(t - a[0]) + b[0]
rgb2hex = (r, g, b) ->
'#' +
('0' + Math.floor(r%255).toString(16))[-2..-1] +
('0' + Math.floor(g%255).toString(16))[-2..-1] +
('0' + Math.floor(b%255).toString(16))[-2..-1]
# good: [ 0, 50]
# moderate: [ 50, 100]
# sensitive: [100, 250]
# unhealthy: [250, 350]
# veryUnhealthy: [350, 430]
# hazardous: [430, 2000]
#
getValueColor = (val) ->
val = Math.round val+0
switch
when 0 <= val < 50 # good: Darkgreen - Limegreen
# rgb(0, 100, 0) - rgb(50, 205, 50)
ra = [0, 50]
ga = [100, 205]
ba = [0, 50]
ar = [0, 50]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 50 <= val < 100 # moderate: Limegreen - Orange
# rgb(50, 205, 50) - rgb(255, 165, 0)
ra = [50, 255]
ga = [205, 165]
ba = [50, 0]
ar = [50, 100]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 100 <= val < 250 # sensitive: Orange - Crimson
# rgb(255, 165, 0) - rgb(220, 20, 60)
ra = [255, 220]
ga = [165, 20]
ba = [0, 60]
ar = [100, 250]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 250 <= val < 350 # unhealthy: Crimson - Maroon
# rgb(220, 20, 60) - rgb(128, 0, 0)
ra = [220, 128]
ga = [20, 0]
ba = [60, 0]
ar = [250, 350]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 350 <= val < 430 # veryUnhealthy: Maroon - Purple
# rgb(128, 0, 0) - rgb(128, 0, 128)
ra = [128, 128]
ga = [0, 0]
ba = [0, 128]
ar = [350, 430]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
when 430 <= val < 2000 # hazardous: Purple - Midnightblue
# rgb(128, 0, 128) - rgb(25, 25, 112)
ra = [128, 25]
ga = [0, 25]
ba = [128, 112]
ar = [430, 2000]
r = r2r val, ar, ra
g = r2r val, ar, ga
b = r2r val, ar, ba
rgb2hex r, g, b
else
'#dddddd'
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991262555122375,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/disabled/test-fs-largefile.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
filepath = path.join(common.tmpDir, "large.txt")
fd = fs.openSync(filepath, "w+")
offset = 5 * 1024 * 1024 * 1024 # 5GB
message = "Large File"
fs.truncateSync fd, offset
assert.equal fs.statSync(filepath).size, offset
writeBuf = new Buffer(message)
fs.writeSync fd, writeBuf, 0, writeBuf.length, offset
readBuf = new Buffer(writeBuf.length)
fs.readSync fd, readBuf, 0, readBuf.length, offset
assert.equal readBuf.toString(), message
fs.readSync fd, readBuf, 0, 1, 0
assert.equal readBuf[0], 0
exceptionRaised = false
try
fs.writeSync fd, writeBuf, 0, writeBuf.length, 42.000001
catch err
console.log err
exceptionRaised = true
assert.equal err.message, "Not an integer"
assert.ok exceptionRaised
fs.close fd
process.on "exit", ->
fs.unlinkSync filepath
return
| 61637 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
filepath = path.join(common.tmpDir, "large.txt")
fd = fs.openSync(filepath, "w+")
offset = 5 * 1024 * 1024 * 1024 # 5GB
message = "Large File"
fs.truncateSync fd, offset
assert.equal fs.statSync(filepath).size, offset
writeBuf = new Buffer(message)
fs.writeSync fd, writeBuf, 0, writeBuf.length, offset
readBuf = new Buffer(writeBuf.length)
fs.readSync fd, readBuf, 0, readBuf.length, offset
assert.equal readBuf.toString(), message
fs.readSync fd, readBuf, 0, 1, 0
assert.equal readBuf[0], 0
exceptionRaised = false
try
fs.writeSync fd, writeBuf, 0, writeBuf.length, 42.000001
catch err
console.log err
exceptionRaised = true
assert.equal err.message, "Not an integer"
assert.ok exceptionRaised
fs.close fd
process.on "exit", ->
fs.unlinkSync filepath
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.
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
filepath = path.join(common.tmpDir, "large.txt")
fd = fs.openSync(filepath, "w+")
offset = 5 * 1024 * 1024 * 1024 # 5GB
message = "Large File"
fs.truncateSync fd, offset
assert.equal fs.statSync(filepath).size, offset
writeBuf = new Buffer(message)
fs.writeSync fd, writeBuf, 0, writeBuf.length, offset
readBuf = new Buffer(writeBuf.length)
fs.readSync fd, readBuf, 0, readBuf.length, offset
assert.equal readBuf.toString(), message
fs.readSync fd, readBuf, 0, 1, 0
assert.equal readBuf[0], 0
exceptionRaised = false
try
fs.writeSync fd, writeBuf, 0, writeBuf.length, 42.000001
catch err
console.log err
exceptionRaised = true
assert.equal err.message, "Not an integer"
assert.ok exceptionRaised
fs.close fd
process.on "exit", ->
fs.unlinkSync filepath
return
|
[
{
"context": "\n \"hex\": \"#afaf87\",\n \"name\": \"NavajoWhite3\"\n },\n {\n \"hex\": \"#afafaf\",\n \"",
"end": 9791,
"score": 0.5160722732543945,
"start": 9785,
"tag": "USERNAME",
"value": "White3"
},
{
"context": "\n {\n \"hex\": \"#d7afaf\",\n \"name\": \"MistyRose3\"\n },\n {\n \"hex\": \"#d7afd7\",\n \"",
"end": 12298,
"score": 0.8111603856086731,
"start": 12288,
"tag": "NAME",
"value": "MistyRose3"
},
{
"context": "\n {\n \"hex\": \"#ffd7d7\",\n \"name\": \"MistyRose1\"\n },\n {\n \"hex\": \"#ffd7ff\",\n \"",
"end": 15200,
"score": 0.6352326273918152,
"start": 15190,
"tag": "NAME",
"value": "MistyRose1"
}
] | src/lib/colors.coffee | destinmoulton/cagen | 0 | module.exports = [
{
"hex": "#000000",
"name": "Black"
},
{
"hex": "#800000",
"name": "Maroon"
},
{
"hex": "#008000",
"name": "Green"
},
{
"hex": "#808000",
"name": "Olive"
},
{
"hex": "#000080",
"name": "Navy"
},
{
"hex": "#800080",
"name": "Purple"
},
{
"hex": "#008080",
"name": "Teal"
},
{
"hex": "#c0c0c0",
"name": "Silver"
},
{
"hex": "#808080",
"name": "Grey"
},
{
"hex": "#ff0000",
"name": "Red"
},
{
"hex": "#00ff00",
"name": "Lime"
},
{
"hex": "#ffff00",
"name": "Yellow"
},
{
"hex": "#0000ff",
"name": "Blue"
},
{
"hex": "#ff00ff",
"name": "Fuchsia"
},
{
"hex": "#00ffff",
"name": "Aqua"
},
{
"hex": "#ffffff",
"name": "White"
},
{
"hex": "#000000",
"name": "Grey0"
},
{
"hex": "#00005f",
"name": "NavyBlue"
},
{
"hex": "#000087",
"name": "DarkBlue"
},
{
"hex": "#0000af",
"name": "Blue3"
},
{
"hex": "#0000d7",
"name": "Blue3"
},
{
"hex": "#0000ff",
"name": "Blue1"
},
{
"hex": "#005f00",
"name": "DarkGreen"
},
{
"hex": "#005f5f",
"name": "DeepSkyBlue4"
},
{
"hex": "#005f87",
"name": "DeepSkyBlue4"
},
{
"hex": "#005faf",
"name": "DeepSkyBlue4"
},
{
"hex": "#005fd7",
"name": "DodgerBlue3"
},
{
"hex": "#005fff",
"name": "DodgerBlue2"
},
{
"hex": "#008700",
"name": "Green4"
},
{
"hex": "#00875f",
"name": "SpringGreen4"
},
{
"hex": "#008787",
"name": "Turquoise4"
},
{
"hex": "#0087af",
"name": "DeepSkyBlue3"
},
{
"hex": "#0087d7",
"name": "DeepSkyBlue3"
},
{
"hex": "#0087ff",
"name": "DodgerBlue1"
},
{
"hex": "#00af00",
"name": "Green3"
},
{
"hex": "#00af5f",
"name": "SpringGreen3"
},
{
"hex": "#00af87",
"name": "DarkCyan"
},
{
"hex": "#00afaf",
"name": "LightSeaGreen"
},
{
"hex": "#00afd7",
"name": "DeepSkyBlue2"
},
{
"hex": "#00afff",
"name": "DeepSkyBlue1"
},
{
"hex": "#00d700",
"name": "Green3"
},
{
"hex": "#00d75f",
"name": "SpringGreen3"
},
{
"hex": "#00d787",
"name": "SpringGreen2"
},
{
"hex": "#00d7af",
"name": "Cyan3"
},
{
"hex": "#00d7d7",
"name": "DarkTurquoise"
},
{
"hex": "#00d7ff",
"name": "Turquoise2"
},
{
"hex": "#00ff00",
"name": "Green1"
},
{
"hex": "#00ff5f",
"name": "SpringGreen2"
},
{
"hex": "#00ff87",
"name": "SpringGreen1"
},
{
"hex": "#00ffaf",
"name": "MediumSpringGreen"
},
{
"hex": "#00ffd7",
"name": "Cyan2"
},
{
"hex": "#00ffff",
"name": "Cyan1"
},
{
"hex": "#5f0000",
"name": "DarkRed"
},
{
"hex": "#5f005f",
"name": "DeepPink4"
},
{
"hex": "#5f0087",
"name": "Purple4"
},
{
"hex": "#5f00af",
"name": "Purple4"
},
{
"hex": "#5f00d7",
"name": "Purple3"
},
{
"hex": "#5f00ff",
"name": "BlueViolet"
},
{
"hex": "#5f5f00",
"name": "Orange4"
},
{
"hex": "#5f5f5f",
"name": "Grey37"
},
{
"hex": "#5f5f87",
"name": "MediumPurple4"
},
{
"hex": "#5f5faf",
"name": "SlateBlue3"
},
{
"hex": "#5f5fd7",
"name": "SlateBlue3"
},
{
"hex": "#5f5fff",
"name": "RoyalBlue1"
},
{
"hex": "#5f8700",
"name": "Chartreuse4"
},
{
"hex": "#5f875f",
"name": "DarkSeaGreen4"
},
{
"hex": "#5f8787",
"name": "PaleTurquoise4"
},
{
"hex": "#5f87af",
"name": "SteelBlue"
},
{
"hex": "#5f87d7",
"name": "SteelBlue3"
},
{
"hex": "#5f87ff",
"name": "CornflowerBlue"
},
{
"hex": "#5faf00",
"name": "Chartreuse3"
},
{
"hex": "#5faf5f",
"name": "DarkSeaGreen4"
},
{
"hex": "#5faf87",
"name": "CadetBlue"
},
{
"hex": "#5fafaf",
"name": "CadetBlue"
},
{
"hex": "#5fafd7",
"name": "SkyBlue3"
},
{
"hex": "#5fafff",
"name": "SteelBlue1"
},
{
"hex": "#5fd700",
"name": "Chartreuse3"
},
{
"hex": "#5fd75f",
"name": "PaleGreen3"
},
{
"hex": "#5fd787",
"name": "SeaGreen3"
},
{
"hex": "#5fd7af",
"name": "Aquamarine3"
},
{
"hex": "#5fd7d7",
"name": "MediumTurquoise"
},
{
"hex": "#5fd7ff",
"name": "SteelBlue1"
},
{
"hex": "#5fff00",
"name": "Chartreuse2"
},
{
"hex": "#5fff5f",
"name": "SeaGreen2"
},
{
"hex": "#5fff87",
"name": "SeaGreen1"
},
{
"hex": "#5fffaf",
"name": "SeaGreen1"
},
{
"hex": "#5fffd7",
"name": "Aquamarine1"
},
{
"hex": "#5fffff",
"name": "DarkSlateGray2"
},
{
"hex": "#870000",
"name": "DarkRed"
},
{
"hex": "#87005f",
"name": "DeepPink4"
},
{
"hex": "#870087",
"name": "DarkMagenta"
},
{
"hex": "#8700af",
"name": "DarkMagenta"
},
{
"hex": "#8700d7",
"name": "DarkViolet"
},
{
"hex": "#8700ff",
"name": "Purple"
},
{
"hex": "#875f00",
"name": "Orange4"
},
{
"hex": "#875f5f",
"name": "LightPink4"
},
{
"hex": "#875f87",
"name": "Plum4"
},
{
"hex": "#875faf",
"name": "MediumPurple3"
},
{
"hex": "#875fd7",
"name": "MediumPurple3"
},
{
"hex": "#875fff",
"name": "SlateBlue1"
},
{
"hex": "#878700",
"name": "Yellow4"
},
{
"hex": "#87875f",
"name": "Wheat4"
},
{
"hex": "#878787",
"name": "Grey53"
},
{
"hex": "#8787af",
"name": "LightSlateGrey"
},
{
"hex": "#8787d7",
"name": "MediumPurple"
},
{
"hex": "#8787ff",
"name": "LightSlateBlue"
},
{
"hex": "#87af00",
"name": "Yellow4"
},
{
"hex": "#87af5f",
"name": "DarkOliveGreen3"
},
{
"hex": "#87af87",
"name": "DarkSeaGreen"
},
{
"hex": "#87afaf",
"name": "LightSkyBlue3"
},
{
"hex": "#87afd7",
"name": "LightSkyBlue3"
},
{
"hex": "#87afff",
"name": "SkyBlue2"
},
{
"hex": "#87d700",
"name": "Chartreuse2"
},
{
"hex": "#87d75f",
"name": "DarkOliveGreen3"
},
{
"hex": "#87d787",
"name": "PaleGreen3"
},
{
"hex": "#87d7af",
"name": "DarkSeaGreen3"
},
{
"hex": "#87d7d7",
"name": "DarkSlateGray3"
},
{
"hex": "#87d7ff",
"name": "SkyBlue1"
},
{
"hex": "#87ff00",
"name": "Chartreuse1"
},
{
"hex": "#87ff5f",
"name": "LightGreen"
},
{
"hex": "#87ff87",
"name": "LightGreen"
},
{
"hex": "#87ffaf",
"name": "PaleGreen1"
},
{
"hex": "#87ffd7",
"name": "Aquamarine1"
},
{
"hex": "#87ffff",
"name": "DarkSlateGray1"
},
{
"hex": "#af0000",
"name": "Red3"
},
{
"hex": "#af005f",
"name": "DeepPink4"
},
{
"hex": "#af0087",
"name": "MediumVioletRed"
},
{
"hex": "#af00af",
"name": "Magenta3"
},
{
"hex": "#af00d7",
"name": "DarkViolet"
},
{
"hex": "#af00ff",
"name": "Purple"
},
{
"hex": "#af5f00",
"name": "DarkOrange3"
},
{
"hex": "#af5f5f",
"name": "IndianRed"
},
{
"hex": "#af5f87",
"name": "HotPink3"
},
{
"hex": "#af5faf",
"name": "MediumOrchid3"
},
{
"hex": "#af5fd7",
"name": "MediumOrchid"
},
{
"hex": "#af5fff",
"name": "MediumPurple2"
},
{
"hex": "#af8700",
"name": "DarkGoldenrod"
},
{
"hex": "#af875f",
"name": "LightSalmon3"
},
{
"hex": "#af8787",
"name": "RosyBrown"
},
{
"hex": "#af87af",
"name": "Grey63"
},
{
"hex": "#af87d7",
"name": "MediumPurple2"
},
{
"hex": "#af87ff",
"name": "MediumPurple1"
},
{
"hex": "#afaf00",
"name": "Gold3"
},
{
"hex": "#afaf5f",
"name": "DarkKhaki"
},
{
"hex": "#afaf87",
"name": "NavajoWhite3"
},
{
"hex": "#afafaf",
"name": "Grey69"
},
{
"hex": "#afafd7",
"name": "LightSteelBlue3"
},
{
"hex": "#afafff",
"name": "LightSteelBlue"
},
{
"hex": "#afd700",
"name": "Yellow3"
},
{
"hex": "#afd75f",
"name": "DarkOliveGreen3"
},
{
"hex": "#afd787",
"name": "DarkSeaGreen3"
},
{
"hex": "#afd7af",
"name": "DarkSeaGreen2"
},
{
"hex": "#afd7d7",
"name": "LightCyan3"
},
{
"hex": "#afd7ff",
"name": "LightSkyBlue1"
},
{
"hex": "#afff00",
"name": "GreenYellow"
},
{
"hex": "#afff5f",
"name": "DarkOliveGreen2"
},
{
"hex": "#afff87",
"name": "PaleGreen1"
},
{
"hex": "#afffaf",
"name": "DarkSeaGreen2"
},
{
"hex": "#afffd7",
"name": "DarkSeaGreen1"
},
{
"hex": "#afffff",
"name": "PaleTurquoise1"
},
{
"hex": "#d70000",
"name": "Red3"
},
{
"hex": "#d7005f",
"name": "DeepPink3"
},
{
"hex": "#d70087",
"name": "DeepPink3"
},
{
"hex": "#d700af",
"name": "Magenta3"
},
{
"hex": "#d700d7",
"name": "Magenta3"
},
{
"hex": "#d700ff",
"name": "Magenta2"
},
{
"hex": "#d75f00",
"name": "DarkOrange3"
},
{
"hex": "#d75f5f",
"name": "IndianRed"
},
{
"hex": "#d75f87",
"name": "HotPink3"
},
{
"hex": "#d75faf",
"name": "HotPink2"
},
{
"hex": "#d75fd7",
"name": "Orchid"
},
{
"hex": "#d75fff",
"name": "MediumOrchid1"
},
{
"hex": "#d78700",
"name": "Orange3"
},
{
"hex": "#d7875f",
"name": "LightSalmon3"
},
{
"hex": "#d78787",
"name": "LightPink3"
},
{
"hex": "#d787af",
"name": "Pink3"
},
{
"hex": "#d787d7",
"name": "Plum3"
},
{
"hex": "#d787ff",
"name": "Violet"
},
{
"hex": "#d7af00",
"name": "Gold3"
},
{
"hex": "#d7af5f",
"name": "LightGoldenrod3"
},
{
"hex": "#d7af87",
"name": "Tan"
},
{
"hex": "#d7afaf",
"name": "MistyRose3"
},
{
"hex": "#d7afd7",
"name": "Thistle3"
},
{
"hex": "#d7afff",
"name": "Plum2"
},
{
"hex": "#d7d700",
"name": "Yellow3"
},
{
"hex": "#d7d75f",
"name": "Khaki3"
},
{
"hex": "#d7d787",
"name": "LightGoldenrod2"
},
{
"hex": "#d7d7af",
"name": "LightYellow3"
},
{
"hex": "#d7d7d7",
"name": "Grey84"
},
{
"hex": "#d7d7ff",
"name": "LightSteelBlue1"
},
{
"hex": "#d7ff00",
"name": "Yellow2"
},
{
"hex": "#d7ff5f",
"name": "DarkOliveGreen1"
},
{
"hex": "#d7ff87",
"name": "DarkOliveGreen1"
},
{
"hex": "#d7ffaf",
"name": "DarkSeaGreen1"
},
{
"hex": "#d7ffd7",
"name": "Honeydew2"
},
{
"hex": "#d7ffff",
"name": "LightCyan1"
},
{
"hex": "#ff0000",
"name": "Red1"
},
{
"hex": "#ff005f",
"name": "DeepPink2"
},
{
"hex": "#ff0087",
"name": "DeepPink1"
},
{
"hex": "#ff00af",
"name": "DeepPink1"
},
{
"hex": "#ff00d7",
"name": "Magenta2"
},
{
"hex": "#ff00ff",
"name": "Magenta1"
},
{
"hex": "#ff5f00",
"name": "OrangeRed1"
},
{
"hex": "#ff5f5f",
"name": "IndianRed1"
},
{
"hex": "#ff5f87",
"name": "IndianRed1"
},
{
"hex": "#ff5faf",
"name": "HotPink"
},
{
"hex": "#ff5fd7",
"name": "HotPink"
},
{
"hex": "#ff5fff",
"name": "MediumOrchid1"
},
{
"hex": "#ff8700",
"name": "DarkOrange"
},
{
"hex": "#ff875f",
"name": "Salmon1"
},
{
"hex": "#ff8787",
"name": "LightCoral"
},
{
"hex": "#ff87af",
"name": "PaleVioletRed1"
},
{
"hex": "#ff87d7",
"name": "Orchid2"
},
{
"hex": "#ff87ff",
"name": "Orchid1"
},
{
"hex": "#ffaf00",
"name": "Orange1"
},
{
"hex": "#ffaf5f",
"name": "SandyBrown"
},
{
"hex": "#ffaf87",
"name": "LightSalmon1"
},
{
"hex": "#ffafaf",
"name": "LightPink1"
},
{
"hex": "#ffafd7",
"name": "Pink1"
},
{
"hex": "#ffafff",
"name": "Plum1"
},
{
"hex": "#ffd700",
"name": "Gold1"
},
{
"hex": "#ffd75f",
"name": "LightGoldenrod2"
},
{
"hex": "#ffd787",
"name": "LightGoldenrod2"
},
{
"hex": "#ffd7af",
"name": "NavajoWhite1"
},
{
"hex": "#ffd7d7",
"name": "MistyRose1"
},
{
"hex": "#ffd7ff",
"name": "Thistle1"
},
{
"hex": "#ffff00",
"name": "Yellow1"
},
{
"hex": "#ffff5f",
"name": "LightGoldenrod1"
},
{
"hex": "#ffff87",
"name": "Khaki1"
},
{
"hex": "#ffffaf",
"name": "Wheat1"
},
{
"hex": "#ffffd7",
"name": "Cornsilk1"
},
{
"hex": "#ffffff",
"name": "Grey100"
},
{
"hex": "#080808",
"name": "Grey3"
},
{
"hex": "#121212",
"name": "Grey7"
},
{
"hex": "#1c1c1c",
"name": "Grey11"
},
{
"hex": "#262626",
"name": "Grey15"
},
{
"hex": "#303030",
"name": "Grey19"
},
{
"hex": "#3a3a3a",
"name": "Grey23"
},
{
"hex": "#444444",
"name": "Grey27"
},
{
"hex": "#4e4e4e",
"name": "Grey30"
},
{
"hex": "#585858",
"name": "Grey35"
},
{
"hex": "#626262",
"name": "Grey39"
},
{
"hex": "#6c6c6c",
"name": "Grey42"
},
{
"hex": "#767676",
"name": "Grey46"
},
{
"hex": "#808080",
"name": "Grey50"
},
{
"hex": "#8a8a8a",
"name": "Grey54"
},
{
"hex": "#949494",
"name": "Grey58"
},
{
"hex": "#9e9e9e",
"name": "Grey62"
},
{
"hex": "#a8a8a8",
"name": "Grey66"
},
{
"hex": "#b2b2b2",
"name": "Grey70"
},
{
"hex": "#bcbcbc",
"name": "Grey74"
},
{
"hex": "#c6c6c6",
"name": "Grey78"
},
{
"hex": "#d0d0d0",
"name": "Grey82"
},
{
"hex": "#dadada",
"name": "Grey85"
},
{
"hex": "#e4e4e4",
"name": "Grey89"
},
{
"hex": "#eeeeee",
"name": "Grey93"
}
]
| 111175 | module.exports = [
{
"hex": "#000000",
"name": "Black"
},
{
"hex": "#800000",
"name": "Maroon"
},
{
"hex": "#008000",
"name": "Green"
},
{
"hex": "#808000",
"name": "Olive"
},
{
"hex": "#000080",
"name": "Navy"
},
{
"hex": "#800080",
"name": "Purple"
},
{
"hex": "#008080",
"name": "Teal"
},
{
"hex": "#c0c0c0",
"name": "Silver"
},
{
"hex": "#808080",
"name": "Grey"
},
{
"hex": "#ff0000",
"name": "Red"
},
{
"hex": "#00ff00",
"name": "Lime"
},
{
"hex": "#ffff00",
"name": "Yellow"
},
{
"hex": "#0000ff",
"name": "Blue"
},
{
"hex": "#ff00ff",
"name": "Fuchsia"
},
{
"hex": "#00ffff",
"name": "Aqua"
},
{
"hex": "#ffffff",
"name": "White"
},
{
"hex": "#000000",
"name": "Grey0"
},
{
"hex": "#00005f",
"name": "NavyBlue"
},
{
"hex": "#000087",
"name": "DarkBlue"
},
{
"hex": "#0000af",
"name": "Blue3"
},
{
"hex": "#0000d7",
"name": "Blue3"
},
{
"hex": "#0000ff",
"name": "Blue1"
},
{
"hex": "#005f00",
"name": "DarkGreen"
},
{
"hex": "#005f5f",
"name": "DeepSkyBlue4"
},
{
"hex": "#005f87",
"name": "DeepSkyBlue4"
},
{
"hex": "#005faf",
"name": "DeepSkyBlue4"
},
{
"hex": "#005fd7",
"name": "DodgerBlue3"
},
{
"hex": "#005fff",
"name": "DodgerBlue2"
},
{
"hex": "#008700",
"name": "Green4"
},
{
"hex": "#00875f",
"name": "SpringGreen4"
},
{
"hex": "#008787",
"name": "Turquoise4"
},
{
"hex": "#0087af",
"name": "DeepSkyBlue3"
},
{
"hex": "#0087d7",
"name": "DeepSkyBlue3"
},
{
"hex": "#0087ff",
"name": "DodgerBlue1"
},
{
"hex": "#00af00",
"name": "Green3"
},
{
"hex": "#00af5f",
"name": "SpringGreen3"
},
{
"hex": "#00af87",
"name": "DarkCyan"
},
{
"hex": "#00afaf",
"name": "LightSeaGreen"
},
{
"hex": "#00afd7",
"name": "DeepSkyBlue2"
},
{
"hex": "#00afff",
"name": "DeepSkyBlue1"
},
{
"hex": "#00d700",
"name": "Green3"
},
{
"hex": "#00d75f",
"name": "SpringGreen3"
},
{
"hex": "#00d787",
"name": "SpringGreen2"
},
{
"hex": "#00d7af",
"name": "Cyan3"
},
{
"hex": "#00d7d7",
"name": "DarkTurquoise"
},
{
"hex": "#00d7ff",
"name": "Turquoise2"
},
{
"hex": "#00ff00",
"name": "Green1"
},
{
"hex": "#00ff5f",
"name": "SpringGreen2"
},
{
"hex": "#00ff87",
"name": "SpringGreen1"
},
{
"hex": "#00ffaf",
"name": "MediumSpringGreen"
},
{
"hex": "#00ffd7",
"name": "Cyan2"
},
{
"hex": "#00ffff",
"name": "Cyan1"
},
{
"hex": "#5f0000",
"name": "DarkRed"
},
{
"hex": "#5f005f",
"name": "DeepPink4"
},
{
"hex": "#5f0087",
"name": "Purple4"
},
{
"hex": "#5f00af",
"name": "Purple4"
},
{
"hex": "#5f00d7",
"name": "Purple3"
},
{
"hex": "#5f00ff",
"name": "BlueViolet"
},
{
"hex": "#5f5f00",
"name": "Orange4"
},
{
"hex": "#5f5f5f",
"name": "Grey37"
},
{
"hex": "#5f5f87",
"name": "MediumPurple4"
},
{
"hex": "#5f5faf",
"name": "SlateBlue3"
},
{
"hex": "#5f5fd7",
"name": "SlateBlue3"
},
{
"hex": "#5f5fff",
"name": "RoyalBlue1"
},
{
"hex": "#5f8700",
"name": "Chartreuse4"
},
{
"hex": "#5f875f",
"name": "DarkSeaGreen4"
},
{
"hex": "#5f8787",
"name": "PaleTurquoise4"
},
{
"hex": "#5f87af",
"name": "SteelBlue"
},
{
"hex": "#5f87d7",
"name": "SteelBlue3"
},
{
"hex": "#5f87ff",
"name": "CornflowerBlue"
},
{
"hex": "#5faf00",
"name": "Chartreuse3"
},
{
"hex": "#5faf5f",
"name": "DarkSeaGreen4"
},
{
"hex": "#5faf87",
"name": "CadetBlue"
},
{
"hex": "#5fafaf",
"name": "CadetBlue"
},
{
"hex": "#5fafd7",
"name": "SkyBlue3"
},
{
"hex": "#5fafff",
"name": "SteelBlue1"
},
{
"hex": "#5fd700",
"name": "Chartreuse3"
},
{
"hex": "#5fd75f",
"name": "PaleGreen3"
},
{
"hex": "#5fd787",
"name": "SeaGreen3"
},
{
"hex": "#5fd7af",
"name": "Aquamarine3"
},
{
"hex": "#5fd7d7",
"name": "MediumTurquoise"
},
{
"hex": "#5fd7ff",
"name": "SteelBlue1"
},
{
"hex": "#5fff00",
"name": "Chartreuse2"
},
{
"hex": "#5fff5f",
"name": "SeaGreen2"
},
{
"hex": "#5fff87",
"name": "SeaGreen1"
},
{
"hex": "#5fffaf",
"name": "SeaGreen1"
},
{
"hex": "#5fffd7",
"name": "Aquamarine1"
},
{
"hex": "#5fffff",
"name": "DarkSlateGray2"
},
{
"hex": "#870000",
"name": "DarkRed"
},
{
"hex": "#87005f",
"name": "DeepPink4"
},
{
"hex": "#870087",
"name": "DarkMagenta"
},
{
"hex": "#8700af",
"name": "DarkMagenta"
},
{
"hex": "#8700d7",
"name": "DarkViolet"
},
{
"hex": "#8700ff",
"name": "Purple"
},
{
"hex": "#875f00",
"name": "Orange4"
},
{
"hex": "#875f5f",
"name": "LightPink4"
},
{
"hex": "#875f87",
"name": "Plum4"
},
{
"hex": "#875faf",
"name": "MediumPurple3"
},
{
"hex": "#875fd7",
"name": "MediumPurple3"
},
{
"hex": "#875fff",
"name": "SlateBlue1"
},
{
"hex": "#878700",
"name": "Yellow4"
},
{
"hex": "#87875f",
"name": "Wheat4"
},
{
"hex": "#878787",
"name": "Grey53"
},
{
"hex": "#8787af",
"name": "LightSlateGrey"
},
{
"hex": "#8787d7",
"name": "MediumPurple"
},
{
"hex": "#8787ff",
"name": "LightSlateBlue"
},
{
"hex": "#87af00",
"name": "Yellow4"
},
{
"hex": "#87af5f",
"name": "DarkOliveGreen3"
},
{
"hex": "#87af87",
"name": "DarkSeaGreen"
},
{
"hex": "#87afaf",
"name": "LightSkyBlue3"
},
{
"hex": "#87afd7",
"name": "LightSkyBlue3"
},
{
"hex": "#87afff",
"name": "SkyBlue2"
},
{
"hex": "#87d700",
"name": "Chartreuse2"
},
{
"hex": "#87d75f",
"name": "DarkOliveGreen3"
},
{
"hex": "#87d787",
"name": "PaleGreen3"
},
{
"hex": "#87d7af",
"name": "DarkSeaGreen3"
},
{
"hex": "#87d7d7",
"name": "DarkSlateGray3"
},
{
"hex": "#87d7ff",
"name": "SkyBlue1"
},
{
"hex": "#87ff00",
"name": "Chartreuse1"
},
{
"hex": "#87ff5f",
"name": "LightGreen"
},
{
"hex": "#87ff87",
"name": "LightGreen"
},
{
"hex": "#87ffaf",
"name": "PaleGreen1"
},
{
"hex": "#87ffd7",
"name": "Aquamarine1"
},
{
"hex": "#87ffff",
"name": "DarkSlateGray1"
},
{
"hex": "#af0000",
"name": "Red3"
},
{
"hex": "#af005f",
"name": "DeepPink4"
},
{
"hex": "#af0087",
"name": "MediumVioletRed"
},
{
"hex": "#af00af",
"name": "Magenta3"
},
{
"hex": "#af00d7",
"name": "DarkViolet"
},
{
"hex": "#af00ff",
"name": "Purple"
},
{
"hex": "#af5f00",
"name": "DarkOrange3"
},
{
"hex": "#af5f5f",
"name": "IndianRed"
},
{
"hex": "#af5f87",
"name": "HotPink3"
},
{
"hex": "#af5faf",
"name": "MediumOrchid3"
},
{
"hex": "#af5fd7",
"name": "MediumOrchid"
},
{
"hex": "#af5fff",
"name": "MediumPurple2"
},
{
"hex": "#af8700",
"name": "DarkGoldenrod"
},
{
"hex": "#af875f",
"name": "LightSalmon3"
},
{
"hex": "#af8787",
"name": "RosyBrown"
},
{
"hex": "#af87af",
"name": "Grey63"
},
{
"hex": "#af87d7",
"name": "MediumPurple2"
},
{
"hex": "#af87ff",
"name": "MediumPurple1"
},
{
"hex": "#afaf00",
"name": "Gold3"
},
{
"hex": "#afaf5f",
"name": "DarkKhaki"
},
{
"hex": "#afaf87",
"name": "NavajoWhite3"
},
{
"hex": "#afafaf",
"name": "Grey69"
},
{
"hex": "#afafd7",
"name": "LightSteelBlue3"
},
{
"hex": "#afafff",
"name": "LightSteelBlue"
},
{
"hex": "#afd700",
"name": "Yellow3"
},
{
"hex": "#afd75f",
"name": "DarkOliveGreen3"
},
{
"hex": "#afd787",
"name": "DarkSeaGreen3"
},
{
"hex": "#afd7af",
"name": "DarkSeaGreen2"
},
{
"hex": "#afd7d7",
"name": "LightCyan3"
},
{
"hex": "#afd7ff",
"name": "LightSkyBlue1"
},
{
"hex": "#afff00",
"name": "GreenYellow"
},
{
"hex": "#afff5f",
"name": "DarkOliveGreen2"
},
{
"hex": "#afff87",
"name": "PaleGreen1"
},
{
"hex": "#afffaf",
"name": "DarkSeaGreen2"
},
{
"hex": "#afffd7",
"name": "DarkSeaGreen1"
},
{
"hex": "#afffff",
"name": "PaleTurquoise1"
},
{
"hex": "#d70000",
"name": "Red3"
},
{
"hex": "#d7005f",
"name": "DeepPink3"
},
{
"hex": "#d70087",
"name": "DeepPink3"
},
{
"hex": "#d700af",
"name": "Magenta3"
},
{
"hex": "#d700d7",
"name": "Magenta3"
},
{
"hex": "#d700ff",
"name": "Magenta2"
},
{
"hex": "#d75f00",
"name": "DarkOrange3"
},
{
"hex": "#d75f5f",
"name": "IndianRed"
},
{
"hex": "#d75f87",
"name": "HotPink3"
},
{
"hex": "#d75faf",
"name": "HotPink2"
},
{
"hex": "#d75fd7",
"name": "Orchid"
},
{
"hex": "#d75fff",
"name": "MediumOrchid1"
},
{
"hex": "#d78700",
"name": "Orange3"
},
{
"hex": "#d7875f",
"name": "LightSalmon3"
},
{
"hex": "#d78787",
"name": "LightPink3"
},
{
"hex": "#d787af",
"name": "Pink3"
},
{
"hex": "#d787d7",
"name": "Plum3"
},
{
"hex": "#d787ff",
"name": "Violet"
},
{
"hex": "#d7af00",
"name": "Gold3"
},
{
"hex": "#d7af5f",
"name": "LightGoldenrod3"
},
{
"hex": "#d7af87",
"name": "Tan"
},
{
"hex": "#d7afaf",
"name": "<NAME>"
},
{
"hex": "#d7afd7",
"name": "Thistle3"
},
{
"hex": "#d7afff",
"name": "Plum2"
},
{
"hex": "#d7d700",
"name": "Yellow3"
},
{
"hex": "#d7d75f",
"name": "Khaki3"
},
{
"hex": "#d7d787",
"name": "LightGoldenrod2"
},
{
"hex": "#d7d7af",
"name": "LightYellow3"
},
{
"hex": "#d7d7d7",
"name": "Grey84"
},
{
"hex": "#d7d7ff",
"name": "LightSteelBlue1"
},
{
"hex": "#d7ff00",
"name": "Yellow2"
},
{
"hex": "#d7ff5f",
"name": "DarkOliveGreen1"
},
{
"hex": "#d7ff87",
"name": "DarkOliveGreen1"
},
{
"hex": "#d7ffaf",
"name": "DarkSeaGreen1"
},
{
"hex": "#d7ffd7",
"name": "Honeydew2"
},
{
"hex": "#d7ffff",
"name": "LightCyan1"
},
{
"hex": "#ff0000",
"name": "Red1"
},
{
"hex": "#ff005f",
"name": "DeepPink2"
},
{
"hex": "#ff0087",
"name": "DeepPink1"
},
{
"hex": "#ff00af",
"name": "DeepPink1"
},
{
"hex": "#ff00d7",
"name": "Magenta2"
},
{
"hex": "#ff00ff",
"name": "Magenta1"
},
{
"hex": "#ff5f00",
"name": "OrangeRed1"
},
{
"hex": "#ff5f5f",
"name": "IndianRed1"
},
{
"hex": "#ff5f87",
"name": "IndianRed1"
},
{
"hex": "#ff5faf",
"name": "HotPink"
},
{
"hex": "#ff5fd7",
"name": "HotPink"
},
{
"hex": "#ff5fff",
"name": "MediumOrchid1"
},
{
"hex": "#ff8700",
"name": "DarkOrange"
},
{
"hex": "#ff875f",
"name": "Salmon1"
},
{
"hex": "#ff8787",
"name": "LightCoral"
},
{
"hex": "#ff87af",
"name": "PaleVioletRed1"
},
{
"hex": "#ff87d7",
"name": "Orchid2"
},
{
"hex": "#ff87ff",
"name": "Orchid1"
},
{
"hex": "#ffaf00",
"name": "Orange1"
},
{
"hex": "#ffaf5f",
"name": "SandyBrown"
},
{
"hex": "#ffaf87",
"name": "LightSalmon1"
},
{
"hex": "#ffafaf",
"name": "LightPink1"
},
{
"hex": "#ffafd7",
"name": "Pink1"
},
{
"hex": "#ffafff",
"name": "Plum1"
},
{
"hex": "#ffd700",
"name": "Gold1"
},
{
"hex": "#ffd75f",
"name": "LightGoldenrod2"
},
{
"hex": "#ffd787",
"name": "LightGoldenrod2"
},
{
"hex": "#ffd7af",
"name": "NavajoWhite1"
},
{
"hex": "#ffd7d7",
"name": "<NAME>"
},
{
"hex": "#ffd7ff",
"name": "Thistle1"
},
{
"hex": "#ffff00",
"name": "Yellow1"
},
{
"hex": "#ffff5f",
"name": "LightGoldenrod1"
},
{
"hex": "#ffff87",
"name": "Khaki1"
},
{
"hex": "#ffffaf",
"name": "Wheat1"
},
{
"hex": "#ffffd7",
"name": "Cornsilk1"
},
{
"hex": "#ffffff",
"name": "Grey100"
},
{
"hex": "#080808",
"name": "Grey3"
},
{
"hex": "#121212",
"name": "Grey7"
},
{
"hex": "#1c1c1c",
"name": "Grey11"
},
{
"hex": "#262626",
"name": "Grey15"
},
{
"hex": "#303030",
"name": "Grey19"
},
{
"hex": "#3a3a3a",
"name": "Grey23"
},
{
"hex": "#444444",
"name": "Grey27"
},
{
"hex": "#4e4e4e",
"name": "Grey30"
},
{
"hex": "#585858",
"name": "Grey35"
},
{
"hex": "#626262",
"name": "Grey39"
},
{
"hex": "#6c6c6c",
"name": "Grey42"
},
{
"hex": "#767676",
"name": "Grey46"
},
{
"hex": "#808080",
"name": "Grey50"
},
{
"hex": "#8a8a8a",
"name": "Grey54"
},
{
"hex": "#949494",
"name": "Grey58"
},
{
"hex": "#9e9e9e",
"name": "Grey62"
},
{
"hex": "#a8a8a8",
"name": "Grey66"
},
{
"hex": "#b2b2b2",
"name": "Grey70"
},
{
"hex": "#bcbcbc",
"name": "Grey74"
},
{
"hex": "#c6c6c6",
"name": "Grey78"
},
{
"hex": "#d0d0d0",
"name": "Grey82"
},
{
"hex": "#dadada",
"name": "Grey85"
},
{
"hex": "#e4e4e4",
"name": "Grey89"
},
{
"hex": "#eeeeee",
"name": "Grey93"
}
]
| true | module.exports = [
{
"hex": "#000000",
"name": "Black"
},
{
"hex": "#800000",
"name": "Maroon"
},
{
"hex": "#008000",
"name": "Green"
},
{
"hex": "#808000",
"name": "Olive"
},
{
"hex": "#000080",
"name": "Navy"
},
{
"hex": "#800080",
"name": "Purple"
},
{
"hex": "#008080",
"name": "Teal"
},
{
"hex": "#c0c0c0",
"name": "Silver"
},
{
"hex": "#808080",
"name": "Grey"
},
{
"hex": "#ff0000",
"name": "Red"
},
{
"hex": "#00ff00",
"name": "Lime"
},
{
"hex": "#ffff00",
"name": "Yellow"
},
{
"hex": "#0000ff",
"name": "Blue"
},
{
"hex": "#ff00ff",
"name": "Fuchsia"
},
{
"hex": "#00ffff",
"name": "Aqua"
},
{
"hex": "#ffffff",
"name": "White"
},
{
"hex": "#000000",
"name": "Grey0"
},
{
"hex": "#00005f",
"name": "NavyBlue"
},
{
"hex": "#000087",
"name": "DarkBlue"
},
{
"hex": "#0000af",
"name": "Blue3"
},
{
"hex": "#0000d7",
"name": "Blue3"
},
{
"hex": "#0000ff",
"name": "Blue1"
},
{
"hex": "#005f00",
"name": "DarkGreen"
},
{
"hex": "#005f5f",
"name": "DeepSkyBlue4"
},
{
"hex": "#005f87",
"name": "DeepSkyBlue4"
},
{
"hex": "#005faf",
"name": "DeepSkyBlue4"
},
{
"hex": "#005fd7",
"name": "DodgerBlue3"
},
{
"hex": "#005fff",
"name": "DodgerBlue2"
},
{
"hex": "#008700",
"name": "Green4"
},
{
"hex": "#00875f",
"name": "SpringGreen4"
},
{
"hex": "#008787",
"name": "Turquoise4"
},
{
"hex": "#0087af",
"name": "DeepSkyBlue3"
},
{
"hex": "#0087d7",
"name": "DeepSkyBlue3"
},
{
"hex": "#0087ff",
"name": "DodgerBlue1"
},
{
"hex": "#00af00",
"name": "Green3"
},
{
"hex": "#00af5f",
"name": "SpringGreen3"
},
{
"hex": "#00af87",
"name": "DarkCyan"
},
{
"hex": "#00afaf",
"name": "LightSeaGreen"
},
{
"hex": "#00afd7",
"name": "DeepSkyBlue2"
},
{
"hex": "#00afff",
"name": "DeepSkyBlue1"
},
{
"hex": "#00d700",
"name": "Green3"
},
{
"hex": "#00d75f",
"name": "SpringGreen3"
},
{
"hex": "#00d787",
"name": "SpringGreen2"
},
{
"hex": "#00d7af",
"name": "Cyan3"
},
{
"hex": "#00d7d7",
"name": "DarkTurquoise"
},
{
"hex": "#00d7ff",
"name": "Turquoise2"
},
{
"hex": "#00ff00",
"name": "Green1"
},
{
"hex": "#00ff5f",
"name": "SpringGreen2"
},
{
"hex": "#00ff87",
"name": "SpringGreen1"
},
{
"hex": "#00ffaf",
"name": "MediumSpringGreen"
},
{
"hex": "#00ffd7",
"name": "Cyan2"
},
{
"hex": "#00ffff",
"name": "Cyan1"
},
{
"hex": "#5f0000",
"name": "DarkRed"
},
{
"hex": "#5f005f",
"name": "DeepPink4"
},
{
"hex": "#5f0087",
"name": "Purple4"
},
{
"hex": "#5f00af",
"name": "Purple4"
},
{
"hex": "#5f00d7",
"name": "Purple3"
},
{
"hex": "#5f00ff",
"name": "BlueViolet"
},
{
"hex": "#5f5f00",
"name": "Orange4"
},
{
"hex": "#5f5f5f",
"name": "Grey37"
},
{
"hex": "#5f5f87",
"name": "MediumPurple4"
},
{
"hex": "#5f5faf",
"name": "SlateBlue3"
},
{
"hex": "#5f5fd7",
"name": "SlateBlue3"
},
{
"hex": "#5f5fff",
"name": "RoyalBlue1"
},
{
"hex": "#5f8700",
"name": "Chartreuse4"
},
{
"hex": "#5f875f",
"name": "DarkSeaGreen4"
},
{
"hex": "#5f8787",
"name": "PaleTurquoise4"
},
{
"hex": "#5f87af",
"name": "SteelBlue"
},
{
"hex": "#5f87d7",
"name": "SteelBlue3"
},
{
"hex": "#5f87ff",
"name": "CornflowerBlue"
},
{
"hex": "#5faf00",
"name": "Chartreuse3"
},
{
"hex": "#5faf5f",
"name": "DarkSeaGreen4"
},
{
"hex": "#5faf87",
"name": "CadetBlue"
},
{
"hex": "#5fafaf",
"name": "CadetBlue"
},
{
"hex": "#5fafd7",
"name": "SkyBlue3"
},
{
"hex": "#5fafff",
"name": "SteelBlue1"
},
{
"hex": "#5fd700",
"name": "Chartreuse3"
},
{
"hex": "#5fd75f",
"name": "PaleGreen3"
},
{
"hex": "#5fd787",
"name": "SeaGreen3"
},
{
"hex": "#5fd7af",
"name": "Aquamarine3"
},
{
"hex": "#5fd7d7",
"name": "MediumTurquoise"
},
{
"hex": "#5fd7ff",
"name": "SteelBlue1"
},
{
"hex": "#5fff00",
"name": "Chartreuse2"
},
{
"hex": "#5fff5f",
"name": "SeaGreen2"
},
{
"hex": "#5fff87",
"name": "SeaGreen1"
},
{
"hex": "#5fffaf",
"name": "SeaGreen1"
},
{
"hex": "#5fffd7",
"name": "Aquamarine1"
},
{
"hex": "#5fffff",
"name": "DarkSlateGray2"
},
{
"hex": "#870000",
"name": "DarkRed"
},
{
"hex": "#87005f",
"name": "DeepPink4"
},
{
"hex": "#870087",
"name": "DarkMagenta"
},
{
"hex": "#8700af",
"name": "DarkMagenta"
},
{
"hex": "#8700d7",
"name": "DarkViolet"
},
{
"hex": "#8700ff",
"name": "Purple"
},
{
"hex": "#875f00",
"name": "Orange4"
},
{
"hex": "#875f5f",
"name": "LightPink4"
},
{
"hex": "#875f87",
"name": "Plum4"
},
{
"hex": "#875faf",
"name": "MediumPurple3"
},
{
"hex": "#875fd7",
"name": "MediumPurple3"
},
{
"hex": "#875fff",
"name": "SlateBlue1"
},
{
"hex": "#878700",
"name": "Yellow4"
},
{
"hex": "#87875f",
"name": "Wheat4"
},
{
"hex": "#878787",
"name": "Grey53"
},
{
"hex": "#8787af",
"name": "LightSlateGrey"
},
{
"hex": "#8787d7",
"name": "MediumPurple"
},
{
"hex": "#8787ff",
"name": "LightSlateBlue"
},
{
"hex": "#87af00",
"name": "Yellow4"
},
{
"hex": "#87af5f",
"name": "DarkOliveGreen3"
},
{
"hex": "#87af87",
"name": "DarkSeaGreen"
},
{
"hex": "#87afaf",
"name": "LightSkyBlue3"
},
{
"hex": "#87afd7",
"name": "LightSkyBlue3"
},
{
"hex": "#87afff",
"name": "SkyBlue2"
},
{
"hex": "#87d700",
"name": "Chartreuse2"
},
{
"hex": "#87d75f",
"name": "DarkOliveGreen3"
},
{
"hex": "#87d787",
"name": "PaleGreen3"
},
{
"hex": "#87d7af",
"name": "DarkSeaGreen3"
},
{
"hex": "#87d7d7",
"name": "DarkSlateGray3"
},
{
"hex": "#87d7ff",
"name": "SkyBlue1"
},
{
"hex": "#87ff00",
"name": "Chartreuse1"
},
{
"hex": "#87ff5f",
"name": "LightGreen"
},
{
"hex": "#87ff87",
"name": "LightGreen"
},
{
"hex": "#87ffaf",
"name": "PaleGreen1"
},
{
"hex": "#87ffd7",
"name": "Aquamarine1"
},
{
"hex": "#87ffff",
"name": "DarkSlateGray1"
},
{
"hex": "#af0000",
"name": "Red3"
},
{
"hex": "#af005f",
"name": "DeepPink4"
},
{
"hex": "#af0087",
"name": "MediumVioletRed"
},
{
"hex": "#af00af",
"name": "Magenta3"
},
{
"hex": "#af00d7",
"name": "DarkViolet"
},
{
"hex": "#af00ff",
"name": "Purple"
},
{
"hex": "#af5f00",
"name": "DarkOrange3"
},
{
"hex": "#af5f5f",
"name": "IndianRed"
},
{
"hex": "#af5f87",
"name": "HotPink3"
},
{
"hex": "#af5faf",
"name": "MediumOrchid3"
},
{
"hex": "#af5fd7",
"name": "MediumOrchid"
},
{
"hex": "#af5fff",
"name": "MediumPurple2"
},
{
"hex": "#af8700",
"name": "DarkGoldenrod"
},
{
"hex": "#af875f",
"name": "LightSalmon3"
},
{
"hex": "#af8787",
"name": "RosyBrown"
},
{
"hex": "#af87af",
"name": "Grey63"
},
{
"hex": "#af87d7",
"name": "MediumPurple2"
},
{
"hex": "#af87ff",
"name": "MediumPurple1"
},
{
"hex": "#afaf00",
"name": "Gold3"
},
{
"hex": "#afaf5f",
"name": "DarkKhaki"
},
{
"hex": "#afaf87",
"name": "NavajoWhite3"
},
{
"hex": "#afafaf",
"name": "Grey69"
},
{
"hex": "#afafd7",
"name": "LightSteelBlue3"
},
{
"hex": "#afafff",
"name": "LightSteelBlue"
},
{
"hex": "#afd700",
"name": "Yellow3"
},
{
"hex": "#afd75f",
"name": "DarkOliveGreen3"
},
{
"hex": "#afd787",
"name": "DarkSeaGreen3"
},
{
"hex": "#afd7af",
"name": "DarkSeaGreen2"
},
{
"hex": "#afd7d7",
"name": "LightCyan3"
},
{
"hex": "#afd7ff",
"name": "LightSkyBlue1"
},
{
"hex": "#afff00",
"name": "GreenYellow"
},
{
"hex": "#afff5f",
"name": "DarkOliveGreen2"
},
{
"hex": "#afff87",
"name": "PaleGreen1"
},
{
"hex": "#afffaf",
"name": "DarkSeaGreen2"
},
{
"hex": "#afffd7",
"name": "DarkSeaGreen1"
},
{
"hex": "#afffff",
"name": "PaleTurquoise1"
},
{
"hex": "#d70000",
"name": "Red3"
},
{
"hex": "#d7005f",
"name": "DeepPink3"
},
{
"hex": "#d70087",
"name": "DeepPink3"
},
{
"hex": "#d700af",
"name": "Magenta3"
},
{
"hex": "#d700d7",
"name": "Magenta3"
},
{
"hex": "#d700ff",
"name": "Magenta2"
},
{
"hex": "#d75f00",
"name": "DarkOrange3"
},
{
"hex": "#d75f5f",
"name": "IndianRed"
},
{
"hex": "#d75f87",
"name": "HotPink3"
},
{
"hex": "#d75faf",
"name": "HotPink2"
},
{
"hex": "#d75fd7",
"name": "Orchid"
},
{
"hex": "#d75fff",
"name": "MediumOrchid1"
},
{
"hex": "#d78700",
"name": "Orange3"
},
{
"hex": "#d7875f",
"name": "LightSalmon3"
},
{
"hex": "#d78787",
"name": "LightPink3"
},
{
"hex": "#d787af",
"name": "Pink3"
},
{
"hex": "#d787d7",
"name": "Plum3"
},
{
"hex": "#d787ff",
"name": "Violet"
},
{
"hex": "#d7af00",
"name": "Gold3"
},
{
"hex": "#d7af5f",
"name": "LightGoldenrod3"
},
{
"hex": "#d7af87",
"name": "Tan"
},
{
"hex": "#d7afaf",
"name": "PI:NAME:<NAME>END_PI"
},
{
"hex": "#d7afd7",
"name": "Thistle3"
},
{
"hex": "#d7afff",
"name": "Plum2"
},
{
"hex": "#d7d700",
"name": "Yellow3"
},
{
"hex": "#d7d75f",
"name": "Khaki3"
},
{
"hex": "#d7d787",
"name": "LightGoldenrod2"
},
{
"hex": "#d7d7af",
"name": "LightYellow3"
},
{
"hex": "#d7d7d7",
"name": "Grey84"
},
{
"hex": "#d7d7ff",
"name": "LightSteelBlue1"
},
{
"hex": "#d7ff00",
"name": "Yellow2"
},
{
"hex": "#d7ff5f",
"name": "DarkOliveGreen1"
},
{
"hex": "#d7ff87",
"name": "DarkOliveGreen1"
},
{
"hex": "#d7ffaf",
"name": "DarkSeaGreen1"
},
{
"hex": "#d7ffd7",
"name": "Honeydew2"
},
{
"hex": "#d7ffff",
"name": "LightCyan1"
},
{
"hex": "#ff0000",
"name": "Red1"
},
{
"hex": "#ff005f",
"name": "DeepPink2"
},
{
"hex": "#ff0087",
"name": "DeepPink1"
},
{
"hex": "#ff00af",
"name": "DeepPink1"
},
{
"hex": "#ff00d7",
"name": "Magenta2"
},
{
"hex": "#ff00ff",
"name": "Magenta1"
},
{
"hex": "#ff5f00",
"name": "OrangeRed1"
},
{
"hex": "#ff5f5f",
"name": "IndianRed1"
},
{
"hex": "#ff5f87",
"name": "IndianRed1"
},
{
"hex": "#ff5faf",
"name": "HotPink"
},
{
"hex": "#ff5fd7",
"name": "HotPink"
},
{
"hex": "#ff5fff",
"name": "MediumOrchid1"
},
{
"hex": "#ff8700",
"name": "DarkOrange"
},
{
"hex": "#ff875f",
"name": "Salmon1"
},
{
"hex": "#ff8787",
"name": "LightCoral"
},
{
"hex": "#ff87af",
"name": "PaleVioletRed1"
},
{
"hex": "#ff87d7",
"name": "Orchid2"
},
{
"hex": "#ff87ff",
"name": "Orchid1"
},
{
"hex": "#ffaf00",
"name": "Orange1"
},
{
"hex": "#ffaf5f",
"name": "SandyBrown"
},
{
"hex": "#ffaf87",
"name": "LightSalmon1"
},
{
"hex": "#ffafaf",
"name": "LightPink1"
},
{
"hex": "#ffafd7",
"name": "Pink1"
},
{
"hex": "#ffafff",
"name": "Plum1"
},
{
"hex": "#ffd700",
"name": "Gold1"
},
{
"hex": "#ffd75f",
"name": "LightGoldenrod2"
},
{
"hex": "#ffd787",
"name": "LightGoldenrod2"
},
{
"hex": "#ffd7af",
"name": "NavajoWhite1"
},
{
"hex": "#ffd7d7",
"name": "PI:NAME:<NAME>END_PI"
},
{
"hex": "#ffd7ff",
"name": "Thistle1"
},
{
"hex": "#ffff00",
"name": "Yellow1"
},
{
"hex": "#ffff5f",
"name": "LightGoldenrod1"
},
{
"hex": "#ffff87",
"name": "Khaki1"
},
{
"hex": "#ffffaf",
"name": "Wheat1"
},
{
"hex": "#ffffd7",
"name": "Cornsilk1"
},
{
"hex": "#ffffff",
"name": "Grey100"
},
{
"hex": "#080808",
"name": "Grey3"
},
{
"hex": "#121212",
"name": "Grey7"
},
{
"hex": "#1c1c1c",
"name": "Grey11"
},
{
"hex": "#262626",
"name": "Grey15"
},
{
"hex": "#303030",
"name": "Grey19"
},
{
"hex": "#3a3a3a",
"name": "Grey23"
},
{
"hex": "#444444",
"name": "Grey27"
},
{
"hex": "#4e4e4e",
"name": "Grey30"
},
{
"hex": "#585858",
"name": "Grey35"
},
{
"hex": "#626262",
"name": "Grey39"
},
{
"hex": "#6c6c6c",
"name": "Grey42"
},
{
"hex": "#767676",
"name": "Grey46"
},
{
"hex": "#808080",
"name": "Grey50"
},
{
"hex": "#8a8a8a",
"name": "Grey54"
},
{
"hex": "#949494",
"name": "Grey58"
},
{
"hex": "#9e9e9e",
"name": "Grey62"
},
{
"hex": "#a8a8a8",
"name": "Grey66"
},
{
"hex": "#b2b2b2",
"name": "Grey70"
},
{
"hex": "#bcbcbc",
"name": "Grey74"
},
{
"hex": "#c6c6c6",
"name": "Grey78"
},
{
"hex": "#d0d0d0",
"name": "Grey82"
},
{
"hex": "#dadada",
"name": "Grey85"
},
{
"hex": "#e4e4e4",
"name": "Grey89"
},
{
"hex": "#eeeeee",
"name": "Grey93"
}
]
|
[
{
"context": "### ^\nBSD 3-Clause License\n\nCopyright (c) 2017, Stephan Jorek\nAll rights reserved.\n\nRedistribution and use in s",
"end": 61,
"score": 0.9998363256454468,
"start": 48,
"tag": "NAME",
"value": "Stephan Jorek"
}
] | src/Compiler.coffee | sjorek/goatee-script.js | 0 | ### ^
BSD 3-Clause License
Copyright (c) 2017, Stephan Jorek
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
Expression = require './Expression'
{
aliases
} = require './Runtime'
{
arraySlice,
bindFunction,
isString,
isArray,
isNumber,
isFunction,
isExpression,
parse
} = require './Utility'
###
# Compiling …
# -----------
#
# … the goatee-scripts.
###
###*
# -------------
# @class Compiler
# @namespace GoateeScript
###
class Compiler
_aliasSymbol = /^[a-zA-Z$_]$/
_operations = Expression.operations
_scalar = _operations.scalar.name
_aliases = aliases().join(',')
_arguments = ",'" + aliases().join("','") + "'"
###*
# -------------
# @function _wrap
# @param {String} code
# @param {Object|Array} map (optional)
# @return {String}
# @private
###
_wrap = (code, map) ->
if map?
keys = if isArray map then map else (k for own k,v of map)
args = if keys.length is 0 then '' else ",'" + keys.join("','") + "'"
keys = keys.join ','
else
keys = _aliases
args = _arguments
"(function(#{keys}) { return #{code}; }).call(this#{args})"
###*
# -------------
# @param {Function} [parseImpl=GoateeScript.Utility.parse]
# @constructor
###
constructor: (@parseImpl = parse) ->
###*
# -------------
# @method compress
# @param {Array} ast
# @param {Object} [map={}] of aliases
# @return {Array.<Array,Object>}
###
compress: (ast, map = {}) ->
code = for o in ast
if not o?
'' + o
else if not o.length?
o
else if o.substring?
if _aliasSymbol.exec o
if map[o]? then ++map[o] else map[o]=1
o
else
JSON.stringify o
else
[c, map] = @compress(o, map)
c
["[#{code.join ','}]", map]
###*
# -------------
# @method expand
# @param {String} opcode A code-expression
# @return {Array}
###
expand: do ->
code = _wrap "function(opcode){ return eval('[' + opcode + '][0]'); }"
Function("return #{code}")()
###*
# -------------
# @method toExpression
# @param {Array|String|Number|Boolean} [opcode=null] ast
# @return {Expression}
###
toExpression: (opcode) ->
state = false
if not opcode? or not (state = isArray opcode) or 2 > (state = opcode.length)
return new Expression 'scalar', \
if state then opcode else [if state is 0 then undefined else opcode]
parameters = [].concat opcode
operator = parameters.shift()
for value, index in parameters
parameters[index] = if isArray value then @toExpression value else value
new Expression(operator, parameters)
###*
# -------------
# @method parse
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @return {Expression}
###
parse: (code) ->
return @parseImpl(code) if isString code
@toExpression(code)
###*
# -------------
# @method evaluate
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Object} context (optional)
# @param {Object} variables (optional)
# @param {Array} scope (optional)
# @param {Array} stack (optional)
# @return {mixed}
###
evaluate: (code, context, variables, scope, stack) ->
expression = @parse(code)
expression.evaluate(context, variables, scope, stack)
###*
# -------------
# @method render
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @return {String}
###
render: (code) ->
@parse(code).toString()
###*
# -------------
# @method save
# @param {Expression} expression
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Object.<String:op,Array:parameters>}
###
save: (expression, callback, compress = on) ->
if compress and expression.operator.name is _scalar
return expression.parameters
opcode = [
if compress and expression.operator.alias? \
then expression.operator.alias else expression.operator.name
]
opcode.push(
if isExpression parameter
@save parameter, callback, compress
else parameter
) for parameter in expression.parameters
opcode
###*
# -------------
# @method ast
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Array|String|Number|true|false|null}
###
ast: (data, callback, compress = on) ->
expression = if isExpression data then data else @parse(data)
ast = @save(expression, callback, compress)
if compress then @compress ast else ast
###*
# -------------
# @method stringyfy
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {String}
###
stringify: (data, callback, compress = on) ->
opcode = @ast(data, callback, compress)
if compress
"[#{opcode[0]},#{JSON.stringify opcode[1]}]"
else
JSON.stringify opcode
###*
# -------------
# @method closure
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Function}
###
closure: (data, callback, compress = on, prefix) ->
opcode = @ast(data, callback, compress)
if compress
code = _wrap(opcode)
else
code = JSON.stringify(opcode)
# …formerly:
#
# Function "#{prefix || ''}return [#{code}][0];"
#
Function "#{prefix || ''}return #{code};"
###*
# -------------
# @function _compile
# @param {Boolean} compress
# @param {String} operator
# @param {Array} [parameters]
# @return {String}
# @private
###
_compile = (compress, operator, parameters...) ->
return JSON.stringify(operator) if parameters.length is 0
operation = _operations[operator]
if isString operation
operator = operation
operation = _operations[operator]
return JSON.stringify(parameters[0]) if operator is _scalar
id = if compress then operation.alias else "_[\"#{operator}\"]"
parameters = for parameter in parameters
if isArray parameter
_compile.apply(null, [compress].concat(parameter))
else
JSON.stringify(parameter)
"#{id}(#{parameters.join ','})"
###*
# -------------
# @method load
# @param {String|Array} data opcode-String or -Array
# @param {Boolean} [compress=true]
# @return {String}
###
load: (data, compress = on) ->
opcode = if isArray data then data else @expand(data)
_compile.apply(null, [compress].concat(opcode))
###*
# -------------
# @method compile
# @param {Array|String|Object} code a String, opcode-Array or
# Object with toString method
# @param {Function} [callback]
# @param {Boolean} [compress=true]
# @return {String}
###
compile: (data, callback, compress = on) ->
opcode = if isArray data then data else @ast(data, callback, false)
@load(opcode, compress)
module.exports = Compiler
| 32471 | ### ^
BSD 3-Clause License
Copyright (c) 2017, <NAME>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
Expression = require './Expression'
{
aliases
} = require './Runtime'
{
arraySlice,
bindFunction,
isString,
isArray,
isNumber,
isFunction,
isExpression,
parse
} = require './Utility'
###
# Compiling …
# -----------
#
# … the goatee-scripts.
###
###*
# -------------
# @class Compiler
# @namespace GoateeScript
###
class Compiler
_aliasSymbol = /^[a-zA-Z$_]$/
_operations = Expression.operations
_scalar = _operations.scalar.name
_aliases = aliases().join(',')
_arguments = ",'" + aliases().join("','") + "'"
###*
# -------------
# @function _wrap
# @param {String} code
# @param {Object|Array} map (optional)
# @return {String}
# @private
###
_wrap = (code, map) ->
if map?
keys = if isArray map then map else (k for own k,v of map)
args = if keys.length is 0 then '' else ",'" + keys.join("','") + "'"
keys = keys.join ','
else
keys = _aliases
args = _arguments
"(function(#{keys}) { return #{code}; }).call(this#{args})"
###*
# -------------
# @param {Function} [parseImpl=GoateeScript.Utility.parse]
# @constructor
###
constructor: (@parseImpl = parse) ->
###*
# -------------
# @method compress
# @param {Array} ast
# @param {Object} [map={}] of aliases
# @return {Array.<Array,Object>}
###
compress: (ast, map = {}) ->
code = for o in ast
if not o?
'' + o
else if not o.length?
o
else if o.substring?
if _aliasSymbol.exec o
if map[o]? then ++map[o] else map[o]=1
o
else
JSON.stringify o
else
[c, map] = @compress(o, map)
c
["[#{code.join ','}]", map]
###*
# -------------
# @method expand
# @param {String} opcode A code-expression
# @return {Array}
###
expand: do ->
code = _wrap "function(opcode){ return eval('[' + opcode + '][0]'); }"
Function("return #{code}")()
###*
# -------------
# @method toExpression
# @param {Array|String|Number|Boolean} [opcode=null] ast
# @return {Expression}
###
toExpression: (opcode) ->
state = false
if not opcode? or not (state = isArray opcode) or 2 > (state = opcode.length)
return new Expression 'scalar', \
if state then opcode else [if state is 0 then undefined else opcode]
parameters = [].concat opcode
operator = parameters.shift()
for value, index in parameters
parameters[index] = if isArray value then @toExpression value else value
new Expression(operator, parameters)
###*
# -------------
# @method parse
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @return {Expression}
###
parse: (code) ->
return @parseImpl(code) if isString code
@toExpression(code)
###*
# -------------
# @method evaluate
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Object} context (optional)
# @param {Object} variables (optional)
# @param {Array} scope (optional)
# @param {Array} stack (optional)
# @return {mixed}
###
evaluate: (code, context, variables, scope, stack) ->
expression = @parse(code)
expression.evaluate(context, variables, scope, stack)
###*
# -------------
# @method render
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @return {String}
###
render: (code) ->
@parse(code).toString()
###*
# -------------
# @method save
# @param {Expression} expression
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Object.<String:op,Array:parameters>}
###
save: (expression, callback, compress = on) ->
if compress and expression.operator.name is _scalar
return expression.parameters
opcode = [
if compress and expression.operator.alias? \
then expression.operator.alias else expression.operator.name
]
opcode.push(
if isExpression parameter
@save parameter, callback, compress
else parameter
) for parameter in expression.parameters
opcode
###*
# -------------
# @method ast
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Array|String|Number|true|false|null}
###
ast: (data, callback, compress = on) ->
expression = if isExpression data then data else @parse(data)
ast = @save(expression, callback, compress)
if compress then @compress ast else ast
###*
# -------------
# @method stringyfy
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {String}
###
stringify: (data, callback, compress = on) ->
opcode = @ast(data, callback, compress)
if compress
"[#{opcode[0]},#{JSON.stringify opcode[1]}]"
else
JSON.stringify opcode
###*
# -------------
# @method closure
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Function}
###
closure: (data, callback, compress = on, prefix) ->
opcode = @ast(data, callback, compress)
if compress
code = _wrap(opcode)
else
code = JSON.stringify(opcode)
# …formerly:
#
# Function "#{prefix || ''}return [#{code}][0];"
#
Function "#{prefix || ''}return #{code};"
###*
# -------------
# @function _compile
# @param {Boolean} compress
# @param {String} operator
# @param {Array} [parameters]
# @return {String}
# @private
###
_compile = (compress, operator, parameters...) ->
return JSON.stringify(operator) if parameters.length is 0
operation = _operations[operator]
if isString operation
operator = operation
operation = _operations[operator]
return JSON.stringify(parameters[0]) if operator is _scalar
id = if compress then operation.alias else "_[\"#{operator}\"]"
parameters = for parameter in parameters
if isArray parameter
_compile.apply(null, [compress].concat(parameter))
else
JSON.stringify(parameter)
"#{id}(#{parameters.join ','})"
###*
# -------------
# @method load
# @param {String|Array} data opcode-String or -Array
# @param {Boolean} [compress=true]
# @return {String}
###
load: (data, compress = on) ->
opcode = if isArray data then data else @expand(data)
_compile.apply(null, [compress].concat(opcode))
###*
# -------------
# @method compile
# @param {Array|String|Object} code a String, opcode-Array or
# Object with toString method
# @param {Function} [callback]
# @param {Boolean} [compress=true]
# @return {String}
###
compile: (data, callback, compress = on) ->
opcode = if isArray data then data else @ast(data, callback, false)
@load(opcode, compress)
module.exports = Compiler
| true | ### ^
BSD 3-Clause License
Copyright (c) 2017, PI:NAME:<NAME>END_PI
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###
Expression = require './Expression'
{
aliases
} = require './Runtime'
{
arraySlice,
bindFunction,
isString,
isArray,
isNumber,
isFunction,
isExpression,
parse
} = require './Utility'
###
# Compiling …
# -----------
#
# … the goatee-scripts.
###
###*
# -------------
# @class Compiler
# @namespace GoateeScript
###
class Compiler
_aliasSymbol = /^[a-zA-Z$_]$/
_operations = Expression.operations
_scalar = _operations.scalar.name
_aliases = aliases().join(',')
_arguments = ",'" + aliases().join("','") + "'"
###*
# -------------
# @function _wrap
# @param {String} code
# @param {Object|Array} map (optional)
# @return {String}
# @private
###
_wrap = (code, map) ->
if map?
keys = if isArray map then map else (k for own k,v of map)
args = if keys.length is 0 then '' else ",'" + keys.join("','") + "'"
keys = keys.join ','
else
keys = _aliases
args = _arguments
"(function(#{keys}) { return #{code}; }).call(this#{args})"
###*
# -------------
# @param {Function} [parseImpl=GoateeScript.Utility.parse]
# @constructor
###
constructor: (@parseImpl = parse) ->
###*
# -------------
# @method compress
# @param {Array} ast
# @param {Object} [map={}] of aliases
# @return {Array.<Array,Object>}
###
compress: (ast, map = {}) ->
code = for o in ast
if not o?
'' + o
else if not o.length?
o
else if o.substring?
if _aliasSymbol.exec o
if map[o]? then ++map[o] else map[o]=1
o
else
JSON.stringify o
else
[c, map] = @compress(o, map)
c
["[#{code.join ','}]", map]
###*
# -------------
# @method expand
# @param {String} opcode A code-expression
# @return {Array}
###
expand: do ->
code = _wrap "function(opcode){ return eval('[' + opcode + '][0]'); }"
Function("return #{code}")()
###*
# -------------
# @method toExpression
# @param {Array|String|Number|Boolean} [opcode=null] ast
# @return {Expression}
###
toExpression: (opcode) ->
state = false
if not opcode? or not (state = isArray opcode) or 2 > (state = opcode.length)
return new Expression 'scalar', \
if state then opcode else [if state is 0 then undefined else opcode]
parameters = [].concat opcode
operator = parameters.shift()
for value, index in parameters
parameters[index] = if isArray value then @toExpression value else value
new Expression(operator, parameters)
###*
# -------------
# @method parse
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @return {Expression}
###
parse: (code) ->
return @parseImpl(code) if isString code
@toExpression(code)
###*
# -------------
# @method evaluate
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Object} context (optional)
# @param {Object} variables (optional)
# @param {Array} scope (optional)
# @param {Array} stack (optional)
# @return {mixed}
###
evaluate: (code, context, variables, scope, stack) ->
expression = @parse(code)
expression.evaluate(context, variables, scope, stack)
###*
# -------------
# @method render
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @return {String}
###
render: (code) ->
@parse(code).toString()
###*
# -------------
# @method save
# @param {Expression} expression
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Object.<String:op,Array:parameters>}
###
save: (expression, callback, compress = on) ->
if compress and expression.operator.name is _scalar
return expression.parameters
opcode = [
if compress and expression.operator.alias? \
then expression.operator.alias else expression.operator.name
]
opcode.push(
if isExpression parameter
@save parameter, callback, compress
else parameter
) for parameter in expression.parameters
opcode
###*
# -------------
# @method ast
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Array|String|Number|true|false|null}
###
ast: (data, callback, compress = on) ->
expression = if isExpression data then data else @parse(data)
ast = @save(expression, callback, compress)
if compress then @compress ast else ast
###*
# -------------
# @method stringyfy
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {String}
###
stringify: (data, callback, compress = on) ->
opcode = @ast(data, callback, compress)
if compress
"[#{opcode[0]},#{JSON.stringify opcode[1]}]"
else
JSON.stringify opcode
###*
# -------------
# @method closure
# @param {Array|String|Object} code, a String, opcode-Array or Object with
# toString method
# @param {Function} callback (optional)
# @param {Boolean} [compress=true]
# @return {Function}
###
closure: (data, callback, compress = on, prefix) ->
opcode = @ast(data, callback, compress)
if compress
code = _wrap(opcode)
else
code = JSON.stringify(opcode)
# …formerly:
#
# Function "#{prefix || ''}return [#{code}][0];"
#
Function "#{prefix || ''}return #{code};"
###*
# -------------
# @function _compile
# @param {Boolean} compress
# @param {String} operator
# @param {Array} [parameters]
# @return {String}
# @private
###
_compile = (compress, operator, parameters...) ->
return JSON.stringify(operator) if parameters.length is 0
operation = _operations[operator]
if isString operation
operator = operation
operation = _operations[operator]
return JSON.stringify(parameters[0]) if operator is _scalar
id = if compress then operation.alias else "_[\"#{operator}\"]"
parameters = for parameter in parameters
if isArray parameter
_compile.apply(null, [compress].concat(parameter))
else
JSON.stringify(parameter)
"#{id}(#{parameters.join ','})"
###*
# -------------
# @method load
# @param {String|Array} data opcode-String or -Array
# @param {Boolean} [compress=true]
# @return {String}
###
load: (data, compress = on) ->
opcode = if isArray data then data else @expand(data)
_compile.apply(null, [compress].concat(opcode))
###*
# -------------
# @method compile
# @param {Array|String|Object} code a String, opcode-Array or
# Object with toString method
# @param {Function} [callback]
# @param {Boolean} [compress=true]
# @return {String}
###
compile: (data, callback, compress = on) ->
opcode = if isArray data then data else @ast(data, callback, false)
@load(opcode, compress)
module.exports = Compiler
|
[
{
"context": "er - v2.3.3 (2014-08-06)\n# https://github.com/jylauril/jquery-runner/\n# (c) 2014 Jyrki Laurila <http",
"end": 75,
"score": 0.9994071125984192,
"start": 67,
"tag": "USERNAME",
"value": "jylauril"
},
{
"context": "/github.com/jylauril/jquery-runner/\n# (c) 2014 Jyrki Laurila <https://github.com/jylauril>\n# ## Helper methods",
"end": 119,
"score": 0.9998741745948792,
"start": 106,
"tag": "NAME",
"value": "Jyrki Laurila"
},
{
"context": "\n# (c) 2014 Jyrki Laurila <https://github.com/jylauril>\n# ## Helper methods\n\n# Meta object that gets pre",
"end": 148,
"score": 0.9992830753326416,
"start": 140,
"tag": "USERNAME",
"value": "jylauril"
}
] | build/jquery.runner.coffee | jylauril/jquery-runner | 25 | # jQuery-runner - v2.3.3 (2014-08-06)
# https://github.com/jylauril/jquery-runner/
# (c) 2014 Jyrki Laurila <https://github.com/jylauril>
# ## Helper methods
# Meta object that gets prepopulated with version info, etc.
meta = {
version: "2.3.3"
name: "jQuery-runner"
}
_$ = @jQuery or @Zepto or @$
unless _$ and _$.fn
# Require jQuery or any other jQuery-like library
throw new Error('[' + meta.name + '] jQuery or jQuery-like library is required for this plugin to work')
# A place to store the runners
runners = {}
# Pad numbers so they are always two characters
pad = (num) -> (if num < 10 then '0' else '') + num
_uid = 1
# Helper method to generate a unique identifier
uid = -> 'runner' + _uid++
# Resolve a browser specific method for `requestAnimationFrame`
_requestAnimationFrame = ((win, raf) ->
win['r' + raf] or win['webkitR' + raf] or win['mozR' + raf] or win['msR' + raf] or (fn) -> setTimeout(fn, 30)
)(@, 'equestAnimationFrame')
# Helper method to generate a time string from a timestamp
formatTime = (time, settings) ->
settings = settings or {}
# Steps: hours, minutes, seconds, milliseconds
steps = [3600000, 60000, 1000, 10]
separator = ['', ':', ':', '.']
prefix = ''
output = ''
ms = settings.milliseconds
len = steps.length
value = 0
# Check if we are in negative values and mark the prefix
if time < 0
time = Math.abs(time)
prefix = '-'
# Go through the steps and generate time string
for step, i in steps
value = 0
# Check if we have enough time left for the next step
if time >= step
value = Math.floor(time / step)
time -= value * step
if (value or i > 1 or output) and (i isnt len - 1 or ms)
output += (if output then separator[i] else '') + pad(value)
prefix + output
# ## The Runner class
class Runner
constructor: (items, options, start) ->
# Allow runner to be called as a function by returning an instance
return new Runner(items, options, start) unless (@ instanceof Runner)
@items = items
id = @id = uid()
@settings = _$.extend({}, @settings, options)
# Store reference to this instance
runners[id] = @
items.each((index, element) ->
# Also save reference to each element
_$(element).data('runner', id)
return
)
# Set initial value
@value(@settings.startAt)
# Start the runner if `autostart` is defined
@start() if start or @settings.autostart
# Runtime states for the runner instance
running: false
updating: false
finished: false
interval: null
# Place to store times during runtime
total: 0
lastTime: 0
startTime: 0
lastLap: 0
lapTime: 0
# Settings for the runner instance
settings: {
autostart: false
countdown: false
stopAt: null
startAt: 0
milliseconds: true
format: null
}
# Method to update current time value to runner's elements
value: (value) ->
@items.each((item, element) =>
item = _$(element)
# If the element is an input, we need to use `val` instead of `text`
action = if item.is('input') then 'val' else 'text'
item[action](@format(value))
return
)
return
# Method that handles the formatting of the current time to a string
format: (value) ->
format = @settings.format
# If custom format method is defined, use it, otherwise use the default formatter
format = if _$.isFunction(format) then format else formatTime
format(value, @settings)
# Method to update runner cycle
update: ->
# Make sure we are not already updating the cycle
unless @updating
@updating = true
settings = @settings
time = _$.now()
stopAt = settings.stopAt
countdown = settings.countdown
delta = time - @lastTime
@lastTime = time
# Check if we are counting up or down and update delta accordingly
if countdown then @total -= delta else @total += delta
# If `stopAt` is defined and we have reached the end, finish the cycle
if stopAt isnt null and ((countdown and @total <= stopAt) or (not countdown and @total >= stopAt))
@total = stopAt
@finished = true
@stop()
@fire('runnerFinish')
# Update current value
@value(@total)
@updating = false
return
# Method to fire runner events to the element
fire: (event) ->
@items.trigger(event, @info())
return
# Method to start the runner
start: ->
# Make sure we're not already running
unless @running
@running = true
# Reset the current time value if we were not paused
@reset() if not @startTime or @finished
@lastTime = _$.now()
step = =>
if @running
# Update cycle if we are still running
@update()
# Request a new update cycle
_requestAnimationFrame(step)
return
_requestAnimationFrame(step)
@fire('runnerStart')
return
# Method to stop the runner
stop: ->
# Make sure we're actually running
if @running
@running = false
@update()
@fire('runnerStop')
return
# Method to toggle current runner state
toggle: ->
if @running then @stop() else @start()
return
# Method to request the current lap time
lap: ->
last = @lastTime
lap = last - @lapTime
if @settings.countdown
lap = -lap
if @running or lap
@lastLap = lap
@lapTime = last
last = @format(@lastLap)
@fire('runnerLap')
return last
# Method to reset the runner to original state
reset: (stop) ->
# If we passed in a boolean true, stop the runner
@stop() if stop
nowTime = _$.now()
if typeof @settings.startAt is 'number' and not @settings.countdown
nowTime -= @settings.startAt
@startTime = @lapTime = @lastTime = nowTime
@total = @settings.startAt
# Update runner value back to original state
@value(@total)
@finished = false
@fire('runnerReset')
return
# Method to return the current runner state
info: ->
lap = @lastLap or 0
{
running: @running
finished: @finished
time: @total
formattedTime: @format(@total)
startTime: @startTime
lapTime: lap
formattedLapTime: @format(lap)
settings: @settings
}
# Expose the runner as jQuery method
_$.fn.runner = (method, options, start) ->
if not method
method = 'init'
# Normalize params
if typeof method is 'object'
start = options
options = method
method = 'init'
# Check if runner is already defined for this element
id = @data('runner')
runner = if id then runners[id] else false
switch method
when 'init' then new Runner(@, options, start)
when 'info' then return runner.info() if runner
when 'reset' then runner.reset(options) if runner
when 'lap' then return runner.lap() if runner
when 'start', 'stop', 'toggle' then return runner[method]() if runner
when 'version' then return meta.version
else _$.error('[' + meta.name + '] Method ' + method + ' does not exist')
return @
# Expose the default format method
_$.fn.runner.format = formatTime
| 198452 | # jQuery-runner - v2.3.3 (2014-08-06)
# https://github.com/jylauril/jquery-runner/
# (c) 2014 <NAME> <https://github.com/jylauril>
# ## Helper methods
# Meta object that gets prepopulated with version info, etc.
meta = {
version: "2.3.3"
name: "jQuery-runner"
}
_$ = @jQuery or @Zepto or @$
unless _$ and _$.fn
# Require jQuery or any other jQuery-like library
throw new Error('[' + meta.name + '] jQuery or jQuery-like library is required for this plugin to work')
# A place to store the runners
runners = {}
# Pad numbers so they are always two characters
pad = (num) -> (if num < 10 then '0' else '') + num
_uid = 1
# Helper method to generate a unique identifier
uid = -> 'runner' + _uid++
# Resolve a browser specific method for `requestAnimationFrame`
_requestAnimationFrame = ((win, raf) ->
win['r' + raf] or win['webkitR' + raf] or win['mozR' + raf] or win['msR' + raf] or (fn) -> setTimeout(fn, 30)
)(@, 'equestAnimationFrame')
# Helper method to generate a time string from a timestamp
formatTime = (time, settings) ->
settings = settings or {}
# Steps: hours, minutes, seconds, milliseconds
steps = [3600000, 60000, 1000, 10]
separator = ['', ':', ':', '.']
prefix = ''
output = ''
ms = settings.milliseconds
len = steps.length
value = 0
# Check if we are in negative values and mark the prefix
if time < 0
time = Math.abs(time)
prefix = '-'
# Go through the steps and generate time string
for step, i in steps
value = 0
# Check if we have enough time left for the next step
if time >= step
value = Math.floor(time / step)
time -= value * step
if (value or i > 1 or output) and (i isnt len - 1 or ms)
output += (if output then separator[i] else '') + pad(value)
prefix + output
# ## The Runner class
class Runner
constructor: (items, options, start) ->
# Allow runner to be called as a function by returning an instance
return new Runner(items, options, start) unless (@ instanceof Runner)
@items = items
id = @id = uid()
@settings = _$.extend({}, @settings, options)
# Store reference to this instance
runners[id] = @
items.each((index, element) ->
# Also save reference to each element
_$(element).data('runner', id)
return
)
# Set initial value
@value(@settings.startAt)
# Start the runner if `autostart` is defined
@start() if start or @settings.autostart
# Runtime states for the runner instance
running: false
updating: false
finished: false
interval: null
# Place to store times during runtime
total: 0
lastTime: 0
startTime: 0
lastLap: 0
lapTime: 0
# Settings for the runner instance
settings: {
autostart: false
countdown: false
stopAt: null
startAt: 0
milliseconds: true
format: null
}
# Method to update current time value to runner's elements
value: (value) ->
@items.each((item, element) =>
item = _$(element)
# If the element is an input, we need to use `val` instead of `text`
action = if item.is('input') then 'val' else 'text'
item[action](@format(value))
return
)
return
# Method that handles the formatting of the current time to a string
format: (value) ->
format = @settings.format
# If custom format method is defined, use it, otherwise use the default formatter
format = if _$.isFunction(format) then format else formatTime
format(value, @settings)
# Method to update runner cycle
update: ->
# Make sure we are not already updating the cycle
unless @updating
@updating = true
settings = @settings
time = _$.now()
stopAt = settings.stopAt
countdown = settings.countdown
delta = time - @lastTime
@lastTime = time
# Check if we are counting up or down and update delta accordingly
if countdown then @total -= delta else @total += delta
# If `stopAt` is defined and we have reached the end, finish the cycle
if stopAt isnt null and ((countdown and @total <= stopAt) or (not countdown and @total >= stopAt))
@total = stopAt
@finished = true
@stop()
@fire('runnerFinish')
# Update current value
@value(@total)
@updating = false
return
# Method to fire runner events to the element
fire: (event) ->
@items.trigger(event, @info())
return
# Method to start the runner
start: ->
# Make sure we're not already running
unless @running
@running = true
# Reset the current time value if we were not paused
@reset() if not @startTime or @finished
@lastTime = _$.now()
step = =>
if @running
# Update cycle if we are still running
@update()
# Request a new update cycle
_requestAnimationFrame(step)
return
_requestAnimationFrame(step)
@fire('runnerStart')
return
# Method to stop the runner
stop: ->
# Make sure we're actually running
if @running
@running = false
@update()
@fire('runnerStop')
return
# Method to toggle current runner state
toggle: ->
if @running then @stop() else @start()
return
# Method to request the current lap time
lap: ->
last = @lastTime
lap = last - @lapTime
if @settings.countdown
lap = -lap
if @running or lap
@lastLap = lap
@lapTime = last
last = @format(@lastLap)
@fire('runnerLap')
return last
# Method to reset the runner to original state
reset: (stop) ->
# If we passed in a boolean true, stop the runner
@stop() if stop
nowTime = _$.now()
if typeof @settings.startAt is 'number' and not @settings.countdown
nowTime -= @settings.startAt
@startTime = @lapTime = @lastTime = nowTime
@total = @settings.startAt
# Update runner value back to original state
@value(@total)
@finished = false
@fire('runnerReset')
return
# Method to return the current runner state
info: ->
lap = @lastLap or 0
{
running: @running
finished: @finished
time: @total
formattedTime: @format(@total)
startTime: @startTime
lapTime: lap
formattedLapTime: @format(lap)
settings: @settings
}
# Expose the runner as jQuery method
_$.fn.runner = (method, options, start) ->
if not method
method = 'init'
# Normalize params
if typeof method is 'object'
start = options
options = method
method = 'init'
# Check if runner is already defined for this element
id = @data('runner')
runner = if id then runners[id] else false
switch method
when 'init' then new Runner(@, options, start)
when 'info' then return runner.info() if runner
when 'reset' then runner.reset(options) if runner
when 'lap' then return runner.lap() if runner
when 'start', 'stop', 'toggle' then return runner[method]() if runner
when 'version' then return meta.version
else _$.error('[' + meta.name + '] Method ' + method + ' does not exist')
return @
# Expose the default format method
_$.fn.runner.format = formatTime
| true | # jQuery-runner - v2.3.3 (2014-08-06)
# https://github.com/jylauril/jquery-runner/
# (c) 2014 PI:NAME:<NAME>END_PI <https://github.com/jylauril>
# ## Helper methods
# Meta object that gets prepopulated with version info, etc.
meta = {
version: "2.3.3"
name: "jQuery-runner"
}
_$ = @jQuery or @Zepto or @$
unless _$ and _$.fn
# Require jQuery or any other jQuery-like library
throw new Error('[' + meta.name + '] jQuery or jQuery-like library is required for this plugin to work')
# A place to store the runners
runners = {}
# Pad numbers so they are always two characters
pad = (num) -> (if num < 10 then '0' else '') + num
_uid = 1
# Helper method to generate a unique identifier
uid = -> 'runner' + _uid++
# Resolve a browser specific method for `requestAnimationFrame`
_requestAnimationFrame = ((win, raf) ->
win['r' + raf] or win['webkitR' + raf] or win['mozR' + raf] or win['msR' + raf] or (fn) -> setTimeout(fn, 30)
)(@, 'equestAnimationFrame')
# Helper method to generate a time string from a timestamp
formatTime = (time, settings) ->
settings = settings or {}
# Steps: hours, minutes, seconds, milliseconds
steps = [3600000, 60000, 1000, 10]
separator = ['', ':', ':', '.']
prefix = ''
output = ''
ms = settings.milliseconds
len = steps.length
value = 0
# Check if we are in negative values and mark the prefix
if time < 0
time = Math.abs(time)
prefix = '-'
# Go through the steps and generate time string
for step, i in steps
value = 0
# Check if we have enough time left for the next step
if time >= step
value = Math.floor(time / step)
time -= value * step
if (value or i > 1 or output) and (i isnt len - 1 or ms)
output += (if output then separator[i] else '') + pad(value)
prefix + output
# ## The Runner class
class Runner
constructor: (items, options, start) ->
# Allow runner to be called as a function by returning an instance
return new Runner(items, options, start) unless (@ instanceof Runner)
@items = items
id = @id = uid()
@settings = _$.extend({}, @settings, options)
# Store reference to this instance
runners[id] = @
items.each((index, element) ->
# Also save reference to each element
_$(element).data('runner', id)
return
)
# Set initial value
@value(@settings.startAt)
# Start the runner if `autostart` is defined
@start() if start or @settings.autostart
# Runtime states for the runner instance
running: false
updating: false
finished: false
interval: null
# Place to store times during runtime
total: 0
lastTime: 0
startTime: 0
lastLap: 0
lapTime: 0
# Settings for the runner instance
settings: {
autostart: false
countdown: false
stopAt: null
startAt: 0
milliseconds: true
format: null
}
# Method to update current time value to runner's elements
value: (value) ->
@items.each((item, element) =>
item = _$(element)
# If the element is an input, we need to use `val` instead of `text`
action = if item.is('input') then 'val' else 'text'
item[action](@format(value))
return
)
return
# Method that handles the formatting of the current time to a string
format: (value) ->
format = @settings.format
# If custom format method is defined, use it, otherwise use the default formatter
format = if _$.isFunction(format) then format else formatTime
format(value, @settings)
# Method to update runner cycle
update: ->
# Make sure we are not already updating the cycle
unless @updating
@updating = true
settings = @settings
time = _$.now()
stopAt = settings.stopAt
countdown = settings.countdown
delta = time - @lastTime
@lastTime = time
# Check if we are counting up or down and update delta accordingly
if countdown then @total -= delta else @total += delta
# If `stopAt` is defined and we have reached the end, finish the cycle
if stopAt isnt null and ((countdown and @total <= stopAt) or (not countdown and @total >= stopAt))
@total = stopAt
@finished = true
@stop()
@fire('runnerFinish')
# Update current value
@value(@total)
@updating = false
return
# Method to fire runner events to the element
fire: (event) ->
@items.trigger(event, @info())
return
# Method to start the runner
start: ->
# Make sure we're not already running
unless @running
@running = true
# Reset the current time value if we were not paused
@reset() if not @startTime or @finished
@lastTime = _$.now()
step = =>
if @running
# Update cycle if we are still running
@update()
# Request a new update cycle
_requestAnimationFrame(step)
return
_requestAnimationFrame(step)
@fire('runnerStart')
return
# Method to stop the runner
stop: ->
# Make sure we're actually running
if @running
@running = false
@update()
@fire('runnerStop')
return
# Method to toggle current runner state
toggle: ->
if @running then @stop() else @start()
return
# Method to request the current lap time
lap: ->
last = @lastTime
lap = last - @lapTime
if @settings.countdown
lap = -lap
if @running or lap
@lastLap = lap
@lapTime = last
last = @format(@lastLap)
@fire('runnerLap')
return last
# Method to reset the runner to original state
reset: (stop) ->
# If we passed in a boolean true, stop the runner
@stop() if stop
nowTime = _$.now()
if typeof @settings.startAt is 'number' and not @settings.countdown
nowTime -= @settings.startAt
@startTime = @lapTime = @lastTime = nowTime
@total = @settings.startAt
# Update runner value back to original state
@value(@total)
@finished = false
@fire('runnerReset')
return
# Method to return the current runner state
info: ->
lap = @lastLap or 0
{
running: @running
finished: @finished
time: @total
formattedTime: @format(@total)
startTime: @startTime
lapTime: lap
formattedLapTime: @format(lap)
settings: @settings
}
# Expose the runner as jQuery method
_$.fn.runner = (method, options, start) ->
if not method
method = 'init'
# Normalize params
if typeof method is 'object'
start = options
options = method
method = 'init'
# Check if runner is already defined for this element
id = @data('runner')
runner = if id then runners[id] else false
switch method
when 'init' then new Runner(@, options, start)
when 'info' then return runner.info() if runner
when 'reset' then runner.reset(options) if runner
when 'lap' then return runner.lap() if runner
when 'start', 'stop', 'toggle' then return runner[method]() if runner
when 'version' then return meta.version
else _$.error('[' + meta.name + '] Method ' + method + ' does not exist')
return @
# Expose the default format method
_$.fn.runner.format = formatTime
|
[
{
"context": " @redisHost = process.env.T_KUE_REDIS_HOST or '127.0.0.1'\n @redisPort = +process.env.T_KUE_REDIS_PORT o",
"end": 979,
"score": 0.999772310256958,
"start": 970,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "9\n @redisPass = process.env.T_KUE_REDIS_PASS or null\n @redisDBNumber = +process.env.T_KUE_REDIS_NUM",
"end": 1089,
"score": 0.7017777562141418,
"start": 1085,
"tag": "PASSWORD",
"value": "null"
},
{
"context": "\n db: @redisDBNumber\n auth_pass: @redisPass\n @monitor.listen @port, () =>\n consol",
"end": 2282,
"score": 0.8205789923667908,
"start": 2272,
"tag": "PASSWORD",
"value": "@redisPass"
}
] | src/tasks/worker.coffee | evanhuang8/teresa | 0 | ###
Task worker
###
co = require 'co'
Queue = require 'bull'
toureiro = require 'toureiro'
db = require '../db'
module.exports = class TaskWorker
# @property [String] Redis host
redisHost: undefined
# @property [Number] Redis port
redisPort: undefined
# @property [String] Redis password
redisPass: undefined
# @property [Number] Redis database number
redisDBNumber: undefined
# @property [Queue] Bull queue instance
queue: undefined
# @property [Express] Express server instance
app: undefined
# @property [Number] Kue monitor port
port: undefined
# @property [Boolean] Should start queue monitor
watch: undefined
# @property [Boolean] Should enable logging
logging: undefined
# @property [Array] Collection of processors
processors: undefined
# @property [Toureiro] Toureiro monitor
monitor: undefined
# Constructor
constructor: (watch = true, logging = true) ->
@redisHost = process.env.T_KUE_REDIS_HOST or '127.0.0.1'
@redisPort = +process.env.T_KUE_REDIS_PORT or 6379
@redisPass = process.env.T_KUE_REDIS_PASS or null
@redisDBNumber = +process.env.T_KUE_REDIS_NUMBER or 1
@port = +process.env.T_KUE_PORT or 3000
@watch = watch
@logging = logging
# Processors
@processors =
general: require './general'
return
# Start worker
start: () ->
# Create queue
params =
host: @redisHost
port: @redisPort
DB: @redisDBNumber
if @redisPass?
params.opts =
auth_pass: @redisPass
@queue = new Queue 'tsaq',
redis: params
@queue.on 'error', (err) ->
console.log err.stack
return
# Synchronize with database
yield db.client.sync()
# Setup task processors
@setupProcessors()
# Graceful shutdown
process.on 'SIGTERM', (signal) =>
try
if @monitor?
@monitor.close()
catch err
console.log err.stack
@queue.close().then () ->
process.exit 0
return
.catch (err) ->
console.log err.stack
process.exit 1
return
return
# Setup monitor
if @watch
@monitor = toureiro
redis:
host: @redisHost
port: @redisPort
db: @redisDBNumber
auth_pass: @redisPass
@monitor.listen @port, () =>
console.log 'Queue monitor is now up and running...'
return
return
# Setup job processors
setupProcessors: () ->
@queue.process 5, (job, done) =>
# Validate again job type and category
processor = @processors[job.data._category]
if not processor?
err = new Error 'Invalid job category:', job.data._category
if @logging
console.log err
done err
return
if not processor[job.data.type]? or typeof processor[job.data.type] isnt 'function'
err = new Error "Invalid job not processed: #{job.data.type}"
if @logging
console.log err
done err
return
# Setup hooks for detailed logging
eta = job.timestamp
if not isNaN(job.timestamp) and not isNaN(job.delay)
eta = job.timestamp + job.delay
co () =>
# Execute job
job.id = job.jobId
result = yield processor[job.data.type] job.data, job
# Mark as done
done null, result
return
.catch (err) =>
if @logging
console.log err
return done err
return
return
| 147198 | ###
Task worker
###
co = require 'co'
Queue = require 'bull'
toureiro = require 'toureiro'
db = require '../db'
module.exports = class TaskWorker
# @property [String] Redis host
redisHost: undefined
# @property [Number] Redis port
redisPort: undefined
# @property [String] Redis password
redisPass: undefined
# @property [Number] Redis database number
redisDBNumber: undefined
# @property [Queue] Bull queue instance
queue: undefined
# @property [Express] Express server instance
app: undefined
# @property [Number] Kue monitor port
port: undefined
# @property [Boolean] Should start queue monitor
watch: undefined
# @property [Boolean] Should enable logging
logging: undefined
# @property [Array] Collection of processors
processors: undefined
# @property [Toureiro] Toureiro monitor
monitor: undefined
# Constructor
constructor: (watch = true, logging = true) ->
@redisHost = process.env.T_KUE_REDIS_HOST or '127.0.0.1'
@redisPort = +process.env.T_KUE_REDIS_PORT or 6379
@redisPass = process.env.T_KUE_REDIS_PASS or <PASSWORD>
@redisDBNumber = +process.env.T_KUE_REDIS_NUMBER or 1
@port = +process.env.T_KUE_PORT or 3000
@watch = watch
@logging = logging
# Processors
@processors =
general: require './general'
return
# Start worker
start: () ->
# Create queue
params =
host: @redisHost
port: @redisPort
DB: @redisDBNumber
if @redisPass?
params.opts =
auth_pass: @redisPass
@queue = new Queue 'tsaq',
redis: params
@queue.on 'error', (err) ->
console.log err.stack
return
# Synchronize with database
yield db.client.sync()
# Setup task processors
@setupProcessors()
# Graceful shutdown
process.on 'SIGTERM', (signal) =>
try
if @monitor?
@monitor.close()
catch err
console.log err.stack
@queue.close().then () ->
process.exit 0
return
.catch (err) ->
console.log err.stack
process.exit 1
return
return
# Setup monitor
if @watch
@monitor = toureiro
redis:
host: @redisHost
port: @redisPort
db: @redisDBNumber
auth_pass: <PASSWORD>
@monitor.listen @port, () =>
console.log 'Queue monitor is now up and running...'
return
return
# Setup job processors
setupProcessors: () ->
@queue.process 5, (job, done) =>
# Validate again job type and category
processor = @processors[job.data._category]
if not processor?
err = new Error 'Invalid job category:', job.data._category
if @logging
console.log err
done err
return
if not processor[job.data.type]? or typeof processor[job.data.type] isnt 'function'
err = new Error "Invalid job not processed: #{job.data.type}"
if @logging
console.log err
done err
return
# Setup hooks for detailed logging
eta = job.timestamp
if not isNaN(job.timestamp) and not isNaN(job.delay)
eta = job.timestamp + job.delay
co () =>
# Execute job
job.id = job.jobId
result = yield processor[job.data.type] job.data, job
# Mark as done
done null, result
return
.catch (err) =>
if @logging
console.log err
return done err
return
return
| true | ###
Task worker
###
co = require 'co'
Queue = require 'bull'
toureiro = require 'toureiro'
db = require '../db'
module.exports = class TaskWorker
# @property [String] Redis host
redisHost: undefined
# @property [Number] Redis port
redisPort: undefined
# @property [String] Redis password
redisPass: undefined
# @property [Number] Redis database number
redisDBNumber: undefined
# @property [Queue] Bull queue instance
queue: undefined
# @property [Express] Express server instance
app: undefined
# @property [Number] Kue monitor port
port: undefined
# @property [Boolean] Should start queue monitor
watch: undefined
# @property [Boolean] Should enable logging
logging: undefined
# @property [Array] Collection of processors
processors: undefined
# @property [Toureiro] Toureiro monitor
monitor: undefined
# Constructor
constructor: (watch = true, logging = true) ->
@redisHost = process.env.T_KUE_REDIS_HOST or '127.0.0.1'
@redisPort = +process.env.T_KUE_REDIS_PORT or 6379
@redisPass = process.env.T_KUE_REDIS_PASS or PI:PASSWORD:<PASSWORD>END_PI
@redisDBNumber = +process.env.T_KUE_REDIS_NUMBER or 1
@port = +process.env.T_KUE_PORT or 3000
@watch = watch
@logging = logging
# Processors
@processors =
general: require './general'
return
# Start worker
start: () ->
# Create queue
params =
host: @redisHost
port: @redisPort
DB: @redisDBNumber
if @redisPass?
params.opts =
auth_pass: @redisPass
@queue = new Queue 'tsaq',
redis: params
@queue.on 'error', (err) ->
console.log err.stack
return
# Synchronize with database
yield db.client.sync()
# Setup task processors
@setupProcessors()
# Graceful shutdown
process.on 'SIGTERM', (signal) =>
try
if @monitor?
@monitor.close()
catch err
console.log err.stack
@queue.close().then () ->
process.exit 0
return
.catch (err) ->
console.log err.stack
process.exit 1
return
return
# Setup monitor
if @watch
@monitor = toureiro
redis:
host: @redisHost
port: @redisPort
db: @redisDBNumber
auth_pass: PI:PASSWORD:<PASSWORD>END_PI
@monitor.listen @port, () =>
console.log 'Queue monitor is now up and running...'
return
return
# Setup job processors
setupProcessors: () ->
@queue.process 5, (job, done) =>
# Validate again job type and category
processor = @processors[job.data._category]
if not processor?
err = new Error 'Invalid job category:', job.data._category
if @logging
console.log err
done err
return
if not processor[job.data.type]? or typeof processor[job.data.type] isnt 'function'
err = new Error "Invalid job not processed: #{job.data.type}"
if @logging
console.log err
done err
return
# Setup hooks for detailed logging
eta = job.timestamp
if not isNaN(job.timestamp) and not isNaN(job.delay)
eta = job.timestamp + job.delay
co () =>
# Execute job
job.id = job.jobId
result = yield processor[job.data.type] job.data, job
# Mark as done
done null, result
return
.catch (err) =>
if @logging
console.log err
return done err
return
return
|
[
{
"context": "ame\", ->\n @artwork.toAltText().should.equal \"Andy Warhol, 'Skull,' 1999, Gagosian Gallery\"\n\n it \"Works ",
"end": 13847,
"score": 0.9998779892921448,
"start": 13836,
"tag": "NAME",
"value": "Andy Warhol"
},
{
"context": "(title: \"title\", forsale: false, artist: { name: \"john doe\" }).artistsNames().should.equal \"john doe\"\n ",
"end": 15412,
"score": 0.999718964099884,
"start": 15404,
"tag": "NAME",
"value": "john doe"
},
{
"context": " name: \"john doe\" }).artistsNames().should.equal \"john doe\"\n new Artwork(title: \"title\", forsale: false",
"end": 15454,
"score": 0.9995413422584534,
"start": 15446,
"tag": "NAME",
"value": "john doe"
},
{
"context": "itle: \"title\", forsale: false, artists: [{ name: \"john doe\" }, { name: \"mark twain\" }]).artistsNames().shoul",
"end": 15533,
"score": 0.9997916221618652,
"start": 15525,
"tag": "NAME",
"value": "john doe"
},
{
"context": ": false, artists: [{ name: \"john doe\" }, { name: \"mark twain\" }]).artistsNames().should.equal \"john doe and ma",
"end": 15557,
"score": 0.9871698021888733,
"start": 15547,
"tag": "NAME",
"value": "mark twain"
},
{
"context": "me: \"mark twain\" }]).artistsNames().should.equal \"john doe and mark twain\"\n new Artwork(title: \"title\",",
"end": 15600,
"score": 0.999606192111969,
"start": 15592,
"tag": "NAME",
"value": "john doe"
},
{
"context": "ain\" }]).artistsNames().should.equal \"john doe and mark twain\"\n new Artwork(title: \"title\", forsale:",
"end": 15609,
"score": 0.71993488073349,
"start": 15605,
"tag": "NAME",
"value": "mark"
},
{
"context": "e: false, artists: [{ name: undefined }, { name: \"mark twain\" }]).artistsNames().should.equal \"mark twain\"\n ",
"end": 15717,
"score": 0.9981786608695984,
"start": 15707,
"tag": "NAME",
"value": "mark twain"
},
{
"context": "itle: \"title\", forsale: false, artists: [{ name: \"john doe\" }, { name: \"mark twain\" }, { name: \"joey peppero",
"end": 15841,
"score": 0.9997966289520264,
"start": 15833,
"tag": "NAME",
"value": "john doe"
},
{
"context": ": false, artists: [{ name: \"john doe\" }, { name: \"mark twain\" }, { name: \"joey pepperoni\" }]).artistsNames().s",
"end": 15865,
"score": 0.9985671043395996,
"start": 15855,
"tag": "NAME",
"value": "mark twain"
},
{
"context": "e: \"john doe\" }, { name: \"mark twain\" }, { name: \"joey pepperoni\" }]).artistsNames().should.equal \"john doe, mark ",
"end": 15893,
"score": 0.999767005443573,
"start": 15879,
"tag": "NAME",
"value": "joey pepperoni"
},
{
"context": "\"joey pepperoni\" }]).artistsNames().should.equal \"john doe, mark twain and joey pepperoni\"\n new Artwork",
"end": 15936,
"score": 0.9993448257446289,
"start": 15928,
"tag": "NAME",
"value": "john doe"
},
{
"context": "istsNames().should.equal \"john doe, mark twain and joey pepperoni\"\n new Artwork(title: \"title\", forsale:",
"end": 15961,
"score": 0.875218391418457,
"start": 15953,
"tag": "NAME",
"value": "joey pep"
},
{
"context": "e: false, artists: [{ name: undefined }, { name: \"mark twain\" }, { name: \"joey pepperoni\" }]).artistsNames().s",
"end": 16069,
"score": 0.9998171329498291,
"start": 16059,
"tag": "NAME",
"value": "mark twain"
},
{
"context": "me: undefined }, { name: \"mark twain\" }, { name: \"joey pepperoni\" }]).artistsNames().should.equal \"mark twain and ",
"end": 16097,
"score": 0.9998534321784973,
"start": 16083,
"tag": "NAME",
"value": "joey pepperoni"
},
{
"context": "\"joey pepperoni\" }]).artistsNames().should.equal \"mark twain and joey pepperoni\"\n\n describe \"#toPageTitle\", -",
"end": 16142,
"score": 0.9994701743125916,
"start": 16132,
"tag": "NAME",
"value": "mark twain"
},
{
"context": "i\" }]).artistsNames().should.equal \"mark twain and joey pepperoni\"\n\n describe \"#toPageTitle\", ->\n it \"renders c",
"end": 16161,
"score": 0.9988107681274414,
"start": 16147,
"tag": "NAME",
"value": "joey pepperoni"
},
{
"context": "(title: \"title\", forsale: false, artist: { name: \"john doe\" }).toPageTitle().should.equal \"john doe | title ",
"end": 16585,
"score": 0.9998536705970764,
"start": 16577,
"tag": "NAME",
"value": "john doe"
},
{
"context": "{ name: \"john doe\" }).toPageTitle().should.equal \"john doe | title | Artsy\"\n new Artwork(title: \"title\"",
"end": 16626,
"score": 0.999828040599823,
"start": 16618,
"tag": "NAME",
"value": "john doe"
},
{
"context": "itle: \"title\", forsale: false, artists: [{ name: \"john doe\" }, { name: \"santa claus\" }]).toPageTitle().shoul",
"end": 16721,
"score": 0.9998548626899719,
"start": 16713,
"tag": "NAME",
"value": "john doe"
},
{
"context": ": false, artists: [{ name: \"john doe\" }, { name: \"santa claus\" }]).toPageTitle().should.equal \"john doe and san",
"end": 16746,
"score": 0.9997336864471436,
"start": 16735,
"tag": "NAME",
"value": "santa claus"
},
{
"context": "me: \"santa claus\" }]).toPageTitle().should.equal \"john doe and santa claus | title | Artsy\"\n new Artwor",
"end": 16788,
"score": 0.9998500943183899,
"start": 16780,
"tag": "NAME",
"value": "john doe"
},
{
"context": "laus\" }]).toPageTitle().should.equal \"john doe and santa claus | title | Artsy\"\n new Artwork(title: \"title\"",
"end": 16804,
"score": 0.9992610216140747,
"start": 16793,
"tag": "NAME",
"value": "santa claus"
},
{
"context": "itle: \"title\", forsale: false, artists: [{ name: \"john doe\" }, { name: \"santa claus\" }, { name: \"hello kitty",
"end": 16899,
"score": 0.9998489022254944,
"start": 16891,
"tag": "NAME",
"value": "john doe"
},
{
"context": ": false, artists: [{ name: \"john doe\" }, { name: \"santa claus\" }, { name: \"hello kitty\" }]).toPageTitle().shoul",
"end": 16924,
"score": 0.9997971057891846,
"start": 16913,
"tag": "NAME",
"value": "santa claus"
},
{
"context": "me: \"hello kitty\" }]).toPageTitle().should.equal \"john doe, santa claus and hello kitty | title | Artsy\"\n ",
"end": 16991,
"score": 0.9998556971549988,
"start": 16983,
"tag": "NAME",
"value": "john doe"
},
{
"context": "kitty\" }]).toPageTitle().should.equal \"john doe, santa claus and hello kitty | title | Artsy\"\n new ",
"end": 16998,
"score": 0.9929700493812561,
"start": 16994,
"tag": "NAME",
"value": "anta"
},
{
"context": "]).toPageTitle().should.equal \"john doe, santa claus and hello kitty | title | Artsy\"\n new Artwor",
"end": 17004,
"score": 0.8924153447151184,
"start": 17002,
"tag": "NAME",
"value": "us"
},
{
"context": "ic: 'cm', medium: \"Awesomeness\", artist: { name: \"first last\" }, forsale: false).toPageDescription().should.eq",
"end": 19426,
"score": 0.9628577828407288,
"start": 19416,
"tag": "NAME",
"value": "first last"
},
{
"context": "qual 'CreativeWork'\n json.name.should.equal 'Skull'\n",
"end": 19762,
"score": 0.9965564012527466,
"start": 19757,
"tag": "NAME",
"value": "Skull"
}
] | src/desktop/test/models/artwork.coffee | kanaabe/force | 0 | _ = require 'underscore'
sinon = require 'sinon'
should = require 'should'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Artwork = require '../../models/artwork'
describe 'Artwork', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@artwork = new Artwork fabricate('artwork'), parse: true
afterEach ->
Backbone.sync.restore()
describe '#saleMessage', ->
it 'returns sold when artwork is sold (w/ or w/o price)', ->
@artwork.set sale_message: '$6,000 - Sold'
@artwork.saleMessage().should.equal 'Sold'
@artwork.set sale_message: 'Sold'
@artwork.saleMessage().should.equal 'Sold'
it 'returns On loan when artwork is on loan', ->
@artwork.set availability: 'on loan'
@artwork.saleMessage().should.equal 'On loan'
it 'returns the price when on hold', ->
@artwork.set availability: 'on hold', price: '$420'
@artwork.saleMessage().should.equal '$420, on hold'
@artwork.unset 'price'
@artwork.saleMessage().should.equal 'On hold'
describe 'sale_message is "Contact for Price" or availability is "not for sale" or "permanent collection"', ->
it 'returns undefined', ->
@artwork.set availability: 'permanent collection'
_.isUndefined(@artwork.saleMessage()).should.be.true()
@artwork.set sale_message: 'Contact For Price', price: '$6,000', availability: 'for sale'
_.isUndefined(@artwork.saleMessage()).should.be.true()
@artwork.unset 'sale_message', 'price'
@artwork.set availability: 'not for sale'
_.isUndefined(@artwork.saleMessage()).should.be.true()
describe '#downloadableFilename', ->
it 'returns a human readable filename', ->
@artwork.downloadableFilename().should.equal 'andy-warhol-skull-1999.jpg'
describe '#downloadableUrl', ->
describe 'as a normal user', ->
it 'returns the URL to the "larger" file', ->
@artwork.downloadableUrl().should.containEql 'larger.jpg'
@artwork.downloadableUrl(isAdmin: -> false).should.containEql 'larger.jpg'
describe 'as an admin', ->
it 'returns the URL to the "original" file', ->
@artwork.downloadableUrl(isAdmin: -> true).should.containEql 'original.jpg'
describe 'display conditions:', ->
describe 'can be downloadable', ->
it 'is downloadable if it is downloadable', ->
@artwork.defaultImage().set 'downloadable', false
@artwork.isDownloadable().should.be.false()
@artwork.defaultImage().set 'downloadable', true
@artwork.isDownloadable().should.be.true()
it 'is downloadable no matter what if the user is an admin', ->
@artwork.defaultImage().set 'downloadable', false
@artwork.isDownloadable().should.be.false()
@artwork.isDownloadable(isAdmin: -> false).should.be.false()
@artwork.isDownloadable(isAdmin: -> true).should.be.true()
it 'can have a price displayed', ->
sinon.stub(@artwork, 'isMultipleEditions').returns false
sinon.stub(@artwork, 'isUnavailableButInquireable').returns false
@artwork.set { price: 'existy', inquireable: true }
@artwork.isPriceDisplayable().should.be.true()
@artwork.set { inquireable: false, sold: true }
@artwork.isPriceDisplayable().should.be.true()
@artwork.set { inquireable: false, sold: false }
@artwork.isPriceDisplayable().should.be.false()
@artwork.set { inquireable: true, price: undefined }
@artwork.isPriceDisplayable().should.be.false()
@artwork.set { inquireable: true, price: 'existy' }
@artwork.isPriceDisplayable().should.be.true()
@artwork.isMultipleEditions.restore()
@artwork.isUnavailableButInquireable.restore()
it 'can have multiple editions', ->
@artwork.set 'edition_sets', undefined
@artwork.isMultipleEditions().should.be.false()
@artwork.set 'edition_sets', [0]
@artwork.isMultipleEditions().should.be.false()
@artwork.set 'edition_sets', [0, 0]
@artwork.isMultipleEditions().should.be.true()
it 'normalizes dimensions', ->
@artwork.set dimensions: cm: '10 × 200 × 30cm'
@artwork.normalizedDimensions().should.eql [10, 200, 30]
@artwork.set dimensions: cm: '10 × 200 × 30'
@artwork.normalizedDimensions().should.eql [10, 200, 30]
@artwork.set dimensions: cm: '101 × 20cm'
@artwork.normalizedDimensions().should.eql [101, 20]
@artwork.set dimensions: cm: '1525cm'
@artwork.normalizedDimensions().should.eql [1525]
it 'might be too big (more than 1524 cmches on a side)', ->
@artwork.set dimensions: cm: '10 × 20cm'
@artwork.tooBig().should.be.false()
@artwork.set dimensions: cm: '1524 × 1524cm'
@artwork.tooBig().should.be.false()
@artwork.set dimensions: cm: '1524.5 × 1524cm'
@artwork.tooBig().should.be.true()
@artwork.set dimensions: cm: '1524 × 1525cm'
@artwork.tooBig().should.be.true()
it 'can be hung', ->
@artwork.set { depth: undefined, height: 1, width: '1' }
@artwork.set 'category', 'Design'
@artwork.isHangable().should.be.false()
@artwork.set 'category', 'Painting'
@artwork.isHangable().should.be.true()
@artwork.set 'depth', 1
@artwork.isHangable().should.be.false()
@artwork.unset 'depth'
@artwork.set dimensions: cm: '1524 × 20cm'
@artwork.isHangable().should.be.true()
@artwork.set dimensions: cm: '1525 × 20cm'
@artwork.isHangable().should.be.false()
@artwork.set dimensions: cm: '1524 × 20cm'
@artwork.isHangable().should.be.true()
@artwork.set 'diameter', 1
@artwork.isHangable().should.be.false()
describe '#isPartOfAuction', ->
beforeEach ->
@artwork.related().sales.reset()
it 'returns true if the artwork has a related auction', ->
@artwork.isPartOfAuction().should.be.false()
# Adds a promo
@artwork.related().sales.add sale_type: 'auction promo', auction_state: 'preview'
@artwork.isPartOfAuction().should.be.false()
# Adds auction
@artwork.related().sales.add is_auction: true
@artwork.isPartOfAuction().should.be.true()
describe '#isPartOfAuctionPromo', ->
beforeEach ->
@artwork.related().sales.reset()
it 'might be part of an auction promo', ->
@artwork.related().sales.add is_auction: true
@artwork.isPartOfAuctionPromo().should.be.false()
@artwork.related().sales.add sale_type: 'auction promo'
@artwork.isPartOfAuctionPromo().should.be.true()
describe '#isContactable', ->
it 'can be contacted given the correct flags', ->
@artwork.set forsale: true, partner: 'existy', acquireable: false
@artwork.isContactable().should.be.true()
@artwork.set forsale: true, partner: 'existy', acquireable: true
@artwork.isContactable().should.be.false()
@artwork.set forsale: false, partner: 'existy', acquireable: false
@artwork.isContactable().should.be.false()
@artwork.set forsale: true, partner: undefined, acquireable: false
@artwork.isContactable().should.be.false()
describe 'with auction promo', ->
beforeEach ->
@artwork.related().sales.reset()
it 'is contactable given an auction promo in the preview state', ->
@artwork.set forsale: true, partner: 'existy', acquireable: true
# Despite being normally uncontactable
@artwork.isContactable().should.be.false()
# Becomes contactable in the presence of a previeable promo
@artwork.related().sales.add sale_type: 'auction promo', auction_state: 'preview'
@artwork.isContactable().should.be.true()
describe 'with an auction', ->
beforeEach ->
@artwork.related().sales.reset()
it 'is not contactable at all', ->
@artwork.set forsale: true, partner: 'existy', acquireable: false
# Contactable at first
@artwork.isContactable().should.be.true()
# Auction enters
@artwork.related().sales.add is_auction: true
# No longer contactable
@artwork.isContactable().should.be.false()
it 'might be unavailable... but inquireable', ->
@artwork.set { forsale: false, inquireable: true, sold: false }
@artwork.isUnavailableButInquireable().should.be.true()
@artwork.set { forsale: true, inquireable: true, sold: false }
@artwork.isUnavailableButInquireable().should.be.false()
@artwork.set { forsale: false, inquireable: true, sold: true }
@artwork.isUnavailableButInquireable().should.be.false()
describe '#hasDimension', ->
it 'returns true on any attribute vaguely numeric', ->
@artwork.set { width: 1 }
@artwork.hasDimension('width').should.be.true()
@artwork.set { width: 'nope' }
@artwork.hasDimension('width').should.be.false()
@artwork.set { width: '1 nope' }
@artwork.hasDimension('width').should.be.true()
@artwork.set { width: '1 1/2 in' }
@artwork.hasDimension('width').should.be.true()
@artwork.unset 'width'
@artwork.hasDimension('width').should.be.false()
describe '#hasMoreInfo', ->
it 'has more info', ->
@artwork.set { provenance: undefined, exhibition_history: '', signature: '', additional_information: undefined, literature: undefined }
@artwork.hasMoreInfo().should.be.false()
@artwork.set 'literature', 'existy'
@artwork.hasMoreInfo().should.be.true()
it 'has more info when there is a blurb', ->
@artwork.clear()
@artwork.hasMoreInfo().should.be.false()
@artwork.set 'blurb', 'existy'
@artwork.hasMoreInfo().should.be.true()
describe '#contactLabel', ->
it 'says to contact the appropriate thing', ->
@artwork.set 'partner', { type: 'Gallery' }
@artwork.contactLabel().should.equal 'gallery'
@artwork.set 'partner', { type: 'Institution' }
@artwork.contactLabel().should.equal 'seller'
@artwork.unset 'partner'
@artwork.contactLabel().should.equal 'seller'
describe '#priceDisplay', ->
it 'displays the price or not', ->
@artwork.set { availability: 'for sale', price_hidden: false, price: '$_$' }
@artwork.priceDisplay().should.equal '$_$'
@artwork.set { availability: 'for sale', price_hidden: false, price: undefined, sale_message: 'Contact For Price' }
@artwork.priceDisplay().should.equal 'Contact For Price'
@artwork.set { availability: 'for sale', price_hidden: true, price: '$_$' }
@artwork.priceDisplay().should.equal 'Contact For Price'
describe '#editionStatus', ->
it 'displays what kind of edition it is otherwise is undefined', ->
@artwork.set { unique: true }
@artwork.editions = new Backbone.Collection
@artwork.editionStatus().should.equal 'Unique'
@artwork.set { unique: false }
_.isUndefined(@artwork.editionStatus()).should.be.true()
@artwork.editions.add { editions: '1 of 5' }
@artwork.editionStatus().should.equal '1 of 5'
describe '#defaultImageUrl', ->
it 'returns the first medium image url by default', ->
@artwork.defaultImageUrl().should.match(
/// /local/additional_images/.*/medium.jpg ///
)
# Have to unset the images attribute as well as resetting the collection
# due to #defaultImage falling back to wrapping the first element
# of the images attribute
it 'works if there are no images', ->
@artwork.unset('images')
@artwork.related().images.reset()
@artwork.defaultImageUrl().should.equal @artwork.defaultImage().missingImageUrl()
describe '#defaultImage', ->
it 'works if artwork.images is null but has images', ->
@artwork.images = null
@artwork.defaultImage().get('id').should.equal @artwork.get('images')[1].id
describe '#titleAndYear', ->
it 'returns empty string without title or year', ->
@artwork.set title: false, date: false
@artwork.titleAndYear().should.equal ''
it 'renderes correctly with just a date', ->
@artwork.set title: false, date: '1905'
@artwork.titleAndYear().should.equal '1905'
it 'emphasises the title', ->
@artwork.set title: 'title', date: '1905'
@artwork.titleAndYear().should.equal '<em>title</em>, 1905'
describe '#partnerName', ->
it "partner name", ->
@artwork.set partner: fabricate 'partner'
@artwork.unset 'collecting_institution'
@artwork.partnerName().should.equal 'Gagosian Gallery'
it "partner name with collecting institution", ->
@artwork.set partner: fabricate 'partner'
@artwork.partnerName().should.equal 'MOMA'
describe '#partnerLink', ->
it "empty without partner", ->
@artwork.unset 'partner'
should.strictEqual(undefined, @artwork.partnerLink())
it "partner profile", ->
@artwork.get('partner').default_profile_public = true
@artwork.get('partner').default_profile_id = 'profile-id'
@artwork.partnerLink().should.equal '/profile-id'
it "doesn't render an external website", ->
@artwork.get('partner').default_profile_public = false
@artwork.get('partner').default_profile_id = 'profile-id'
@artwork.get('partner').website = 'mah-website.com'
should.strictEqual(undefined, @artwork.partnerLink())
it "partner website if profile and profile is private", ->
@artwork.get('partner').type = 'Auction'
should.strictEqual(undefined, @artwork.partnerLink())
describe '#href', ->
it 'creates an href for linking to this artwork', ->
@artwork.href().should.equal "/artwork/#{@artwork.get('id')}"
describe '#toAltText', ->
it "Includes title, date and artist name", ->
@artwork.toAltText().should.equal "Andy Warhol, 'Skull,' 1999, Gagosian Gallery"
it "Works without title, date, partner, and artist name", ->
@artwork.set
artist: undefined
date: undefined
title: undefined
partner: undefined
@artwork.toAltText().should.equal ""
describe "artistName", ->
it "renders correctly", ->
new Artwork(title: "title", forsale: false).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: undefined }).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }]).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: "popeye the sailor" }).artistName().should.equal "popeye the sailor"
new Artwork(title: "title", forsale: false, artists: [{ name: "cap'n crunch" }]).artistName().should.equal "cap'n crunch"
new Artwork(title: "title", forsale: false, artists: [{ name: "cap'n crunch" }, { name: "popeye the sailor" }]).artistName().should.equal "cap'n crunch"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "so and so" }]).artistName().should.equal "so and so"
new Artwork(title: "title", forsale: false, artist: { name: undefined }, artists: [{ name: "so and so" }]).artistName().should.equal "so and so"
describe "artistsNames", ->
it "renders correctly", ->
new Artwork(title: "title", forsale: false).artistsNames().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: "john doe" }).artistsNames().should.equal "john doe"
new Artwork(title: "title", forsale: false, artists: [{ name: "john doe" }, { name: "mark twain" }]).artistsNames().should.equal "john doe and mark twain"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "mark twain" }]).artistsNames().should.equal "mark twain"
new Artwork(title: "title", forsale: false, artists: [{ name: "john doe" }, { name: "mark twain" }, { name: "joey pepperoni" }]).artistsNames().should.equal "john doe, mark twain and joey pepperoni"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "mark twain" }, { name: "joey pepperoni" }]).artistsNames().should.equal "mark twain and joey pepperoni"
describe "#toPageTitle", ->
it "renders correctly", ->
new Artwork(title: "", forsale: false).toPageTitle().should.equal "Artsy"
new Artwork(title: "title", forsale: false).toPageTitle().should.equal "title | Artsy"
new Artwork(title: "title", forsale: true).toPageTitle().should.equal "title, Available for Sale | Artsy"
new Artwork(title: "title", forsale: false, artist: { name: "john doe" }).toPageTitle().should.equal "john doe | title | Artsy"
new Artwork(title: "title", forsale: false, artists: [{ name: "john doe" }, { name: "santa claus" }]).toPageTitle().should.equal "john doe and santa claus | title | Artsy"
new Artwork(title: "title", forsale: false, artists: [{ name: "john doe" }, { name: "santa claus" }, { name: "hello kitty" }]).toPageTitle().should.equal "john doe, santa claus and hello kitty | title | Artsy"
new Artwork(title: "", forsale: false, artist: { name: "last" }).toPageTitle().should.equal "last | Artsy"
new Artwork(title: "title", forsale: false, date: "2010" ).toPageTitle().should.equal "title (2010) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010", artist: { name: "last" }).toPageTitle().should.equal "last | title (2010) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010-2011", artist: { name: "first last" }).toPageTitle().should.equal "first last | title (2010-2011) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010, 2011, 2012", artist: { name: "first last" }).toPageTitle().should.equal "first last | title (2010, 2011, 2012) | Artsy"
describe "#toPageDescription", ->
it "renders correctly", ->
new Artwork(title: "title").toPageDescription().should.equal "title"
new Artwork(title: "title", partner: { name: 'partner' }, forsale: false).toPageDescription().should.equal "From partner, title"
new Artwork(title: "title", partner: { name: 'partner' }, forsale: true).toPageDescription().should.equal "Available for sale from partner, title"
new Artwork(title: "title", dimensions: { in: "2 × 1 × 3 in" }, metric: 'in', forsale: false).toPageDescription().should.equal "title, 2 × 1 × 3 in"
new Artwork(title: "title", dimensions: { in: "2 × 1 × 3 in" }, metric: 'in', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 2 × 1 × 3 in"
new Artwork(title: "title", dimensions: { cm: "45000000 × 2000000000 cm" }, metric: 'cm', forsale: false).toPageDescription().should.equal "title, 45000000 × 2000000000 cm"
new Artwork(title: "title", dimensions: { cm: "45000000 × 2000000000 cm" }, metric: 'cm', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 45000000 × 2000000000 cm"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', forsale: false).toPageDescription().should.equal "title, 20 cm diameter"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 20 cm diameter"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', medium: "Awesomeness", artist: { name: "first last" }, forsale: false).toPageDescription().should.equal "first last, title, Awesomeness, 20 cm diameter"
describe '#toJSONLD', ->
it 'returns valid json', ->
json = @artwork.toJSONLD()
json['@context'].should.equal 'http://schema.org'
json['@type'].should.equal 'CreativeWork'
json.name.should.equal 'Skull'
| 82912 | _ = require 'underscore'
sinon = require 'sinon'
should = require 'should'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Artwork = require '../../models/artwork'
describe 'Artwork', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@artwork = new Artwork fabricate('artwork'), parse: true
afterEach ->
Backbone.sync.restore()
describe '#saleMessage', ->
it 'returns sold when artwork is sold (w/ or w/o price)', ->
@artwork.set sale_message: '$6,000 - Sold'
@artwork.saleMessage().should.equal 'Sold'
@artwork.set sale_message: 'Sold'
@artwork.saleMessage().should.equal 'Sold'
it 'returns On loan when artwork is on loan', ->
@artwork.set availability: 'on loan'
@artwork.saleMessage().should.equal 'On loan'
it 'returns the price when on hold', ->
@artwork.set availability: 'on hold', price: '$420'
@artwork.saleMessage().should.equal '$420, on hold'
@artwork.unset 'price'
@artwork.saleMessage().should.equal 'On hold'
describe 'sale_message is "Contact for Price" or availability is "not for sale" or "permanent collection"', ->
it 'returns undefined', ->
@artwork.set availability: 'permanent collection'
_.isUndefined(@artwork.saleMessage()).should.be.true()
@artwork.set sale_message: 'Contact For Price', price: '$6,000', availability: 'for sale'
_.isUndefined(@artwork.saleMessage()).should.be.true()
@artwork.unset 'sale_message', 'price'
@artwork.set availability: 'not for sale'
_.isUndefined(@artwork.saleMessage()).should.be.true()
describe '#downloadableFilename', ->
it 'returns a human readable filename', ->
@artwork.downloadableFilename().should.equal 'andy-warhol-skull-1999.jpg'
describe '#downloadableUrl', ->
describe 'as a normal user', ->
it 'returns the URL to the "larger" file', ->
@artwork.downloadableUrl().should.containEql 'larger.jpg'
@artwork.downloadableUrl(isAdmin: -> false).should.containEql 'larger.jpg'
describe 'as an admin', ->
it 'returns the URL to the "original" file', ->
@artwork.downloadableUrl(isAdmin: -> true).should.containEql 'original.jpg'
describe 'display conditions:', ->
describe 'can be downloadable', ->
it 'is downloadable if it is downloadable', ->
@artwork.defaultImage().set 'downloadable', false
@artwork.isDownloadable().should.be.false()
@artwork.defaultImage().set 'downloadable', true
@artwork.isDownloadable().should.be.true()
it 'is downloadable no matter what if the user is an admin', ->
@artwork.defaultImage().set 'downloadable', false
@artwork.isDownloadable().should.be.false()
@artwork.isDownloadable(isAdmin: -> false).should.be.false()
@artwork.isDownloadable(isAdmin: -> true).should.be.true()
it 'can have a price displayed', ->
sinon.stub(@artwork, 'isMultipleEditions').returns false
sinon.stub(@artwork, 'isUnavailableButInquireable').returns false
@artwork.set { price: 'existy', inquireable: true }
@artwork.isPriceDisplayable().should.be.true()
@artwork.set { inquireable: false, sold: true }
@artwork.isPriceDisplayable().should.be.true()
@artwork.set { inquireable: false, sold: false }
@artwork.isPriceDisplayable().should.be.false()
@artwork.set { inquireable: true, price: undefined }
@artwork.isPriceDisplayable().should.be.false()
@artwork.set { inquireable: true, price: 'existy' }
@artwork.isPriceDisplayable().should.be.true()
@artwork.isMultipleEditions.restore()
@artwork.isUnavailableButInquireable.restore()
it 'can have multiple editions', ->
@artwork.set 'edition_sets', undefined
@artwork.isMultipleEditions().should.be.false()
@artwork.set 'edition_sets', [0]
@artwork.isMultipleEditions().should.be.false()
@artwork.set 'edition_sets', [0, 0]
@artwork.isMultipleEditions().should.be.true()
it 'normalizes dimensions', ->
@artwork.set dimensions: cm: '10 × 200 × 30cm'
@artwork.normalizedDimensions().should.eql [10, 200, 30]
@artwork.set dimensions: cm: '10 × 200 × 30'
@artwork.normalizedDimensions().should.eql [10, 200, 30]
@artwork.set dimensions: cm: '101 × 20cm'
@artwork.normalizedDimensions().should.eql [101, 20]
@artwork.set dimensions: cm: '1525cm'
@artwork.normalizedDimensions().should.eql [1525]
it 'might be too big (more than 1524 cmches on a side)', ->
@artwork.set dimensions: cm: '10 × 20cm'
@artwork.tooBig().should.be.false()
@artwork.set dimensions: cm: '1524 × 1524cm'
@artwork.tooBig().should.be.false()
@artwork.set dimensions: cm: '1524.5 × 1524cm'
@artwork.tooBig().should.be.true()
@artwork.set dimensions: cm: '1524 × 1525cm'
@artwork.tooBig().should.be.true()
it 'can be hung', ->
@artwork.set { depth: undefined, height: 1, width: '1' }
@artwork.set 'category', 'Design'
@artwork.isHangable().should.be.false()
@artwork.set 'category', 'Painting'
@artwork.isHangable().should.be.true()
@artwork.set 'depth', 1
@artwork.isHangable().should.be.false()
@artwork.unset 'depth'
@artwork.set dimensions: cm: '1524 × 20cm'
@artwork.isHangable().should.be.true()
@artwork.set dimensions: cm: '1525 × 20cm'
@artwork.isHangable().should.be.false()
@artwork.set dimensions: cm: '1524 × 20cm'
@artwork.isHangable().should.be.true()
@artwork.set 'diameter', 1
@artwork.isHangable().should.be.false()
describe '#isPartOfAuction', ->
beforeEach ->
@artwork.related().sales.reset()
it 'returns true if the artwork has a related auction', ->
@artwork.isPartOfAuction().should.be.false()
# Adds a promo
@artwork.related().sales.add sale_type: 'auction promo', auction_state: 'preview'
@artwork.isPartOfAuction().should.be.false()
# Adds auction
@artwork.related().sales.add is_auction: true
@artwork.isPartOfAuction().should.be.true()
describe '#isPartOfAuctionPromo', ->
beforeEach ->
@artwork.related().sales.reset()
it 'might be part of an auction promo', ->
@artwork.related().sales.add is_auction: true
@artwork.isPartOfAuctionPromo().should.be.false()
@artwork.related().sales.add sale_type: 'auction promo'
@artwork.isPartOfAuctionPromo().should.be.true()
describe '#isContactable', ->
it 'can be contacted given the correct flags', ->
@artwork.set forsale: true, partner: 'existy', acquireable: false
@artwork.isContactable().should.be.true()
@artwork.set forsale: true, partner: 'existy', acquireable: true
@artwork.isContactable().should.be.false()
@artwork.set forsale: false, partner: 'existy', acquireable: false
@artwork.isContactable().should.be.false()
@artwork.set forsale: true, partner: undefined, acquireable: false
@artwork.isContactable().should.be.false()
describe 'with auction promo', ->
beforeEach ->
@artwork.related().sales.reset()
it 'is contactable given an auction promo in the preview state', ->
@artwork.set forsale: true, partner: 'existy', acquireable: true
# Despite being normally uncontactable
@artwork.isContactable().should.be.false()
# Becomes contactable in the presence of a previeable promo
@artwork.related().sales.add sale_type: 'auction promo', auction_state: 'preview'
@artwork.isContactable().should.be.true()
describe 'with an auction', ->
beforeEach ->
@artwork.related().sales.reset()
it 'is not contactable at all', ->
@artwork.set forsale: true, partner: 'existy', acquireable: false
# Contactable at first
@artwork.isContactable().should.be.true()
# Auction enters
@artwork.related().sales.add is_auction: true
# No longer contactable
@artwork.isContactable().should.be.false()
it 'might be unavailable... but inquireable', ->
@artwork.set { forsale: false, inquireable: true, sold: false }
@artwork.isUnavailableButInquireable().should.be.true()
@artwork.set { forsale: true, inquireable: true, sold: false }
@artwork.isUnavailableButInquireable().should.be.false()
@artwork.set { forsale: false, inquireable: true, sold: true }
@artwork.isUnavailableButInquireable().should.be.false()
describe '#hasDimension', ->
it 'returns true on any attribute vaguely numeric', ->
@artwork.set { width: 1 }
@artwork.hasDimension('width').should.be.true()
@artwork.set { width: 'nope' }
@artwork.hasDimension('width').should.be.false()
@artwork.set { width: '1 nope' }
@artwork.hasDimension('width').should.be.true()
@artwork.set { width: '1 1/2 in' }
@artwork.hasDimension('width').should.be.true()
@artwork.unset 'width'
@artwork.hasDimension('width').should.be.false()
describe '#hasMoreInfo', ->
it 'has more info', ->
@artwork.set { provenance: undefined, exhibition_history: '', signature: '', additional_information: undefined, literature: undefined }
@artwork.hasMoreInfo().should.be.false()
@artwork.set 'literature', 'existy'
@artwork.hasMoreInfo().should.be.true()
it 'has more info when there is a blurb', ->
@artwork.clear()
@artwork.hasMoreInfo().should.be.false()
@artwork.set 'blurb', 'existy'
@artwork.hasMoreInfo().should.be.true()
describe '#contactLabel', ->
it 'says to contact the appropriate thing', ->
@artwork.set 'partner', { type: 'Gallery' }
@artwork.contactLabel().should.equal 'gallery'
@artwork.set 'partner', { type: 'Institution' }
@artwork.contactLabel().should.equal 'seller'
@artwork.unset 'partner'
@artwork.contactLabel().should.equal 'seller'
describe '#priceDisplay', ->
it 'displays the price or not', ->
@artwork.set { availability: 'for sale', price_hidden: false, price: '$_$' }
@artwork.priceDisplay().should.equal '$_$'
@artwork.set { availability: 'for sale', price_hidden: false, price: undefined, sale_message: 'Contact For Price' }
@artwork.priceDisplay().should.equal 'Contact For Price'
@artwork.set { availability: 'for sale', price_hidden: true, price: '$_$' }
@artwork.priceDisplay().should.equal 'Contact For Price'
describe '#editionStatus', ->
it 'displays what kind of edition it is otherwise is undefined', ->
@artwork.set { unique: true }
@artwork.editions = new Backbone.Collection
@artwork.editionStatus().should.equal 'Unique'
@artwork.set { unique: false }
_.isUndefined(@artwork.editionStatus()).should.be.true()
@artwork.editions.add { editions: '1 of 5' }
@artwork.editionStatus().should.equal '1 of 5'
describe '#defaultImageUrl', ->
it 'returns the first medium image url by default', ->
@artwork.defaultImageUrl().should.match(
/// /local/additional_images/.*/medium.jpg ///
)
# Have to unset the images attribute as well as resetting the collection
# due to #defaultImage falling back to wrapping the first element
# of the images attribute
it 'works if there are no images', ->
@artwork.unset('images')
@artwork.related().images.reset()
@artwork.defaultImageUrl().should.equal @artwork.defaultImage().missingImageUrl()
describe '#defaultImage', ->
it 'works if artwork.images is null but has images', ->
@artwork.images = null
@artwork.defaultImage().get('id').should.equal @artwork.get('images')[1].id
describe '#titleAndYear', ->
it 'returns empty string without title or year', ->
@artwork.set title: false, date: false
@artwork.titleAndYear().should.equal ''
it 'renderes correctly with just a date', ->
@artwork.set title: false, date: '1905'
@artwork.titleAndYear().should.equal '1905'
it 'emphasises the title', ->
@artwork.set title: 'title', date: '1905'
@artwork.titleAndYear().should.equal '<em>title</em>, 1905'
describe '#partnerName', ->
it "partner name", ->
@artwork.set partner: fabricate 'partner'
@artwork.unset 'collecting_institution'
@artwork.partnerName().should.equal 'Gagosian Gallery'
it "partner name with collecting institution", ->
@artwork.set partner: fabricate 'partner'
@artwork.partnerName().should.equal 'MOMA'
describe '#partnerLink', ->
it "empty without partner", ->
@artwork.unset 'partner'
should.strictEqual(undefined, @artwork.partnerLink())
it "partner profile", ->
@artwork.get('partner').default_profile_public = true
@artwork.get('partner').default_profile_id = 'profile-id'
@artwork.partnerLink().should.equal '/profile-id'
it "doesn't render an external website", ->
@artwork.get('partner').default_profile_public = false
@artwork.get('partner').default_profile_id = 'profile-id'
@artwork.get('partner').website = 'mah-website.com'
should.strictEqual(undefined, @artwork.partnerLink())
it "partner website if profile and profile is private", ->
@artwork.get('partner').type = 'Auction'
should.strictEqual(undefined, @artwork.partnerLink())
describe '#href', ->
it 'creates an href for linking to this artwork', ->
@artwork.href().should.equal "/artwork/#{@artwork.get('id')}"
describe '#toAltText', ->
it "Includes title, date and artist name", ->
@artwork.toAltText().should.equal "<NAME>, 'Skull,' 1999, Gagosian Gallery"
it "Works without title, date, partner, and artist name", ->
@artwork.set
artist: undefined
date: undefined
title: undefined
partner: undefined
@artwork.toAltText().should.equal ""
describe "artistName", ->
it "renders correctly", ->
new Artwork(title: "title", forsale: false).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: undefined }).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }]).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: "popeye the sailor" }).artistName().should.equal "popeye the sailor"
new Artwork(title: "title", forsale: false, artists: [{ name: "cap'n crunch" }]).artistName().should.equal "cap'n crunch"
new Artwork(title: "title", forsale: false, artists: [{ name: "cap'n crunch" }, { name: "popeye the sailor" }]).artistName().should.equal "cap'n crunch"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "so and so" }]).artistName().should.equal "so and so"
new Artwork(title: "title", forsale: false, artist: { name: undefined }, artists: [{ name: "so and so" }]).artistName().should.equal "so and so"
describe "artistsNames", ->
it "renders correctly", ->
new Artwork(title: "title", forsale: false).artistsNames().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: "<NAME>" }).artistsNames().should.equal "<NAME>"
new Artwork(title: "title", forsale: false, artists: [{ name: "<NAME>" }, { name: "<NAME>" }]).artistsNames().should.equal "<NAME> and <NAME> twain"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "<NAME>" }]).artistsNames().should.equal "mark twain"
new Artwork(title: "title", forsale: false, artists: [{ name: "<NAME>" }, { name: "<NAME>" }, { name: "<NAME>" }]).artistsNames().should.equal "<NAME>, mark twain and <NAME>peroni"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "<NAME>" }, { name: "<NAME>" }]).artistsNames().should.equal "<NAME> and <NAME>"
describe "#toPageTitle", ->
it "renders correctly", ->
new Artwork(title: "", forsale: false).toPageTitle().should.equal "Artsy"
new Artwork(title: "title", forsale: false).toPageTitle().should.equal "title | Artsy"
new Artwork(title: "title", forsale: true).toPageTitle().should.equal "title, Available for Sale | Artsy"
new Artwork(title: "title", forsale: false, artist: { name: "<NAME>" }).toPageTitle().should.equal "<NAME> | title | Artsy"
new Artwork(title: "title", forsale: false, artists: [{ name: "<NAME>" }, { name: "<NAME>" }]).toPageTitle().should.equal "<NAME> and <NAME> | title | Artsy"
new Artwork(title: "title", forsale: false, artists: [{ name: "<NAME>" }, { name: "<NAME>" }, { name: "hello kitty" }]).toPageTitle().should.equal "<NAME>, s<NAME> cla<NAME> and hello kitty | title | Artsy"
new Artwork(title: "", forsale: false, artist: { name: "last" }).toPageTitle().should.equal "last | Artsy"
new Artwork(title: "title", forsale: false, date: "2010" ).toPageTitle().should.equal "title (2010) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010", artist: { name: "last" }).toPageTitle().should.equal "last | title (2010) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010-2011", artist: { name: "first last" }).toPageTitle().should.equal "first last | title (2010-2011) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010, 2011, 2012", artist: { name: "first last" }).toPageTitle().should.equal "first last | title (2010, 2011, 2012) | Artsy"
describe "#toPageDescription", ->
it "renders correctly", ->
new Artwork(title: "title").toPageDescription().should.equal "title"
new Artwork(title: "title", partner: { name: 'partner' }, forsale: false).toPageDescription().should.equal "From partner, title"
new Artwork(title: "title", partner: { name: 'partner' }, forsale: true).toPageDescription().should.equal "Available for sale from partner, title"
new Artwork(title: "title", dimensions: { in: "2 × 1 × 3 in" }, metric: 'in', forsale: false).toPageDescription().should.equal "title, 2 × 1 × 3 in"
new Artwork(title: "title", dimensions: { in: "2 × 1 × 3 in" }, metric: 'in', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 2 × 1 × 3 in"
new Artwork(title: "title", dimensions: { cm: "45000000 × 2000000000 cm" }, metric: 'cm', forsale: false).toPageDescription().should.equal "title, 45000000 × 2000000000 cm"
new Artwork(title: "title", dimensions: { cm: "45000000 × 2000000000 cm" }, metric: 'cm', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 45000000 × 2000000000 cm"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', forsale: false).toPageDescription().should.equal "title, 20 cm diameter"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 20 cm diameter"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', medium: "Awesomeness", artist: { name: "<NAME>" }, forsale: false).toPageDescription().should.equal "first last, title, Awesomeness, 20 cm diameter"
describe '#toJSONLD', ->
it 'returns valid json', ->
json = @artwork.toJSONLD()
json['@context'].should.equal 'http://schema.org'
json['@type'].should.equal 'CreativeWork'
json.name.should.equal '<NAME>'
| true | _ = require 'underscore'
sinon = require 'sinon'
should = require 'should'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Artwork = require '../../models/artwork'
describe 'Artwork', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@artwork = new Artwork fabricate('artwork'), parse: true
afterEach ->
Backbone.sync.restore()
describe '#saleMessage', ->
it 'returns sold when artwork is sold (w/ or w/o price)', ->
@artwork.set sale_message: '$6,000 - Sold'
@artwork.saleMessage().should.equal 'Sold'
@artwork.set sale_message: 'Sold'
@artwork.saleMessage().should.equal 'Sold'
it 'returns On loan when artwork is on loan', ->
@artwork.set availability: 'on loan'
@artwork.saleMessage().should.equal 'On loan'
it 'returns the price when on hold', ->
@artwork.set availability: 'on hold', price: '$420'
@artwork.saleMessage().should.equal '$420, on hold'
@artwork.unset 'price'
@artwork.saleMessage().should.equal 'On hold'
describe 'sale_message is "Contact for Price" or availability is "not for sale" or "permanent collection"', ->
it 'returns undefined', ->
@artwork.set availability: 'permanent collection'
_.isUndefined(@artwork.saleMessage()).should.be.true()
@artwork.set sale_message: 'Contact For Price', price: '$6,000', availability: 'for sale'
_.isUndefined(@artwork.saleMessage()).should.be.true()
@artwork.unset 'sale_message', 'price'
@artwork.set availability: 'not for sale'
_.isUndefined(@artwork.saleMessage()).should.be.true()
describe '#downloadableFilename', ->
it 'returns a human readable filename', ->
@artwork.downloadableFilename().should.equal 'andy-warhol-skull-1999.jpg'
describe '#downloadableUrl', ->
describe 'as a normal user', ->
it 'returns the URL to the "larger" file', ->
@artwork.downloadableUrl().should.containEql 'larger.jpg'
@artwork.downloadableUrl(isAdmin: -> false).should.containEql 'larger.jpg'
describe 'as an admin', ->
it 'returns the URL to the "original" file', ->
@artwork.downloadableUrl(isAdmin: -> true).should.containEql 'original.jpg'
describe 'display conditions:', ->
describe 'can be downloadable', ->
it 'is downloadable if it is downloadable', ->
@artwork.defaultImage().set 'downloadable', false
@artwork.isDownloadable().should.be.false()
@artwork.defaultImage().set 'downloadable', true
@artwork.isDownloadable().should.be.true()
it 'is downloadable no matter what if the user is an admin', ->
@artwork.defaultImage().set 'downloadable', false
@artwork.isDownloadable().should.be.false()
@artwork.isDownloadable(isAdmin: -> false).should.be.false()
@artwork.isDownloadable(isAdmin: -> true).should.be.true()
it 'can have a price displayed', ->
sinon.stub(@artwork, 'isMultipleEditions').returns false
sinon.stub(@artwork, 'isUnavailableButInquireable').returns false
@artwork.set { price: 'existy', inquireable: true }
@artwork.isPriceDisplayable().should.be.true()
@artwork.set { inquireable: false, sold: true }
@artwork.isPriceDisplayable().should.be.true()
@artwork.set { inquireable: false, sold: false }
@artwork.isPriceDisplayable().should.be.false()
@artwork.set { inquireable: true, price: undefined }
@artwork.isPriceDisplayable().should.be.false()
@artwork.set { inquireable: true, price: 'existy' }
@artwork.isPriceDisplayable().should.be.true()
@artwork.isMultipleEditions.restore()
@artwork.isUnavailableButInquireable.restore()
it 'can have multiple editions', ->
@artwork.set 'edition_sets', undefined
@artwork.isMultipleEditions().should.be.false()
@artwork.set 'edition_sets', [0]
@artwork.isMultipleEditions().should.be.false()
@artwork.set 'edition_sets', [0, 0]
@artwork.isMultipleEditions().should.be.true()
it 'normalizes dimensions', ->
@artwork.set dimensions: cm: '10 × 200 × 30cm'
@artwork.normalizedDimensions().should.eql [10, 200, 30]
@artwork.set dimensions: cm: '10 × 200 × 30'
@artwork.normalizedDimensions().should.eql [10, 200, 30]
@artwork.set dimensions: cm: '101 × 20cm'
@artwork.normalizedDimensions().should.eql [101, 20]
@artwork.set dimensions: cm: '1525cm'
@artwork.normalizedDimensions().should.eql [1525]
it 'might be too big (more than 1524 cmches on a side)', ->
@artwork.set dimensions: cm: '10 × 20cm'
@artwork.tooBig().should.be.false()
@artwork.set dimensions: cm: '1524 × 1524cm'
@artwork.tooBig().should.be.false()
@artwork.set dimensions: cm: '1524.5 × 1524cm'
@artwork.tooBig().should.be.true()
@artwork.set dimensions: cm: '1524 × 1525cm'
@artwork.tooBig().should.be.true()
it 'can be hung', ->
@artwork.set { depth: undefined, height: 1, width: '1' }
@artwork.set 'category', 'Design'
@artwork.isHangable().should.be.false()
@artwork.set 'category', 'Painting'
@artwork.isHangable().should.be.true()
@artwork.set 'depth', 1
@artwork.isHangable().should.be.false()
@artwork.unset 'depth'
@artwork.set dimensions: cm: '1524 × 20cm'
@artwork.isHangable().should.be.true()
@artwork.set dimensions: cm: '1525 × 20cm'
@artwork.isHangable().should.be.false()
@artwork.set dimensions: cm: '1524 × 20cm'
@artwork.isHangable().should.be.true()
@artwork.set 'diameter', 1
@artwork.isHangable().should.be.false()
describe '#isPartOfAuction', ->
beforeEach ->
@artwork.related().sales.reset()
it 'returns true if the artwork has a related auction', ->
@artwork.isPartOfAuction().should.be.false()
# Adds a promo
@artwork.related().sales.add sale_type: 'auction promo', auction_state: 'preview'
@artwork.isPartOfAuction().should.be.false()
# Adds auction
@artwork.related().sales.add is_auction: true
@artwork.isPartOfAuction().should.be.true()
describe '#isPartOfAuctionPromo', ->
beforeEach ->
@artwork.related().sales.reset()
it 'might be part of an auction promo', ->
@artwork.related().sales.add is_auction: true
@artwork.isPartOfAuctionPromo().should.be.false()
@artwork.related().sales.add sale_type: 'auction promo'
@artwork.isPartOfAuctionPromo().should.be.true()
describe '#isContactable', ->
it 'can be contacted given the correct flags', ->
@artwork.set forsale: true, partner: 'existy', acquireable: false
@artwork.isContactable().should.be.true()
@artwork.set forsale: true, partner: 'existy', acquireable: true
@artwork.isContactable().should.be.false()
@artwork.set forsale: false, partner: 'existy', acquireable: false
@artwork.isContactable().should.be.false()
@artwork.set forsale: true, partner: undefined, acquireable: false
@artwork.isContactable().should.be.false()
describe 'with auction promo', ->
beforeEach ->
@artwork.related().sales.reset()
it 'is contactable given an auction promo in the preview state', ->
@artwork.set forsale: true, partner: 'existy', acquireable: true
# Despite being normally uncontactable
@artwork.isContactable().should.be.false()
# Becomes contactable in the presence of a previeable promo
@artwork.related().sales.add sale_type: 'auction promo', auction_state: 'preview'
@artwork.isContactable().should.be.true()
describe 'with an auction', ->
beforeEach ->
@artwork.related().sales.reset()
it 'is not contactable at all', ->
@artwork.set forsale: true, partner: 'existy', acquireable: false
# Contactable at first
@artwork.isContactable().should.be.true()
# Auction enters
@artwork.related().sales.add is_auction: true
# No longer contactable
@artwork.isContactable().should.be.false()
it 'might be unavailable... but inquireable', ->
@artwork.set { forsale: false, inquireable: true, sold: false }
@artwork.isUnavailableButInquireable().should.be.true()
@artwork.set { forsale: true, inquireable: true, sold: false }
@artwork.isUnavailableButInquireable().should.be.false()
@artwork.set { forsale: false, inquireable: true, sold: true }
@artwork.isUnavailableButInquireable().should.be.false()
describe '#hasDimension', ->
it 'returns true on any attribute vaguely numeric', ->
@artwork.set { width: 1 }
@artwork.hasDimension('width').should.be.true()
@artwork.set { width: 'nope' }
@artwork.hasDimension('width').should.be.false()
@artwork.set { width: '1 nope' }
@artwork.hasDimension('width').should.be.true()
@artwork.set { width: '1 1/2 in' }
@artwork.hasDimension('width').should.be.true()
@artwork.unset 'width'
@artwork.hasDimension('width').should.be.false()
describe '#hasMoreInfo', ->
it 'has more info', ->
@artwork.set { provenance: undefined, exhibition_history: '', signature: '', additional_information: undefined, literature: undefined }
@artwork.hasMoreInfo().should.be.false()
@artwork.set 'literature', 'existy'
@artwork.hasMoreInfo().should.be.true()
it 'has more info when there is a blurb', ->
@artwork.clear()
@artwork.hasMoreInfo().should.be.false()
@artwork.set 'blurb', 'existy'
@artwork.hasMoreInfo().should.be.true()
describe '#contactLabel', ->
it 'says to contact the appropriate thing', ->
@artwork.set 'partner', { type: 'Gallery' }
@artwork.contactLabel().should.equal 'gallery'
@artwork.set 'partner', { type: 'Institution' }
@artwork.contactLabel().should.equal 'seller'
@artwork.unset 'partner'
@artwork.contactLabel().should.equal 'seller'
describe '#priceDisplay', ->
it 'displays the price or not', ->
@artwork.set { availability: 'for sale', price_hidden: false, price: '$_$' }
@artwork.priceDisplay().should.equal '$_$'
@artwork.set { availability: 'for sale', price_hidden: false, price: undefined, sale_message: 'Contact For Price' }
@artwork.priceDisplay().should.equal 'Contact For Price'
@artwork.set { availability: 'for sale', price_hidden: true, price: '$_$' }
@artwork.priceDisplay().should.equal 'Contact For Price'
describe '#editionStatus', ->
it 'displays what kind of edition it is otherwise is undefined', ->
@artwork.set { unique: true }
@artwork.editions = new Backbone.Collection
@artwork.editionStatus().should.equal 'Unique'
@artwork.set { unique: false }
_.isUndefined(@artwork.editionStatus()).should.be.true()
@artwork.editions.add { editions: '1 of 5' }
@artwork.editionStatus().should.equal '1 of 5'
describe '#defaultImageUrl', ->
it 'returns the first medium image url by default', ->
@artwork.defaultImageUrl().should.match(
/// /local/additional_images/.*/medium.jpg ///
)
# Have to unset the images attribute as well as resetting the collection
# due to #defaultImage falling back to wrapping the first element
# of the images attribute
it 'works if there are no images', ->
@artwork.unset('images')
@artwork.related().images.reset()
@artwork.defaultImageUrl().should.equal @artwork.defaultImage().missingImageUrl()
describe '#defaultImage', ->
it 'works if artwork.images is null but has images', ->
@artwork.images = null
@artwork.defaultImage().get('id').should.equal @artwork.get('images')[1].id
describe '#titleAndYear', ->
it 'returns empty string without title or year', ->
@artwork.set title: false, date: false
@artwork.titleAndYear().should.equal ''
it 'renderes correctly with just a date', ->
@artwork.set title: false, date: '1905'
@artwork.titleAndYear().should.equal '1905'
it 'emphasises the title', ->
@artwork.set title: 'title', date: '1905'
@artwork.titleAndYear().should.equal '<em>title</em>, 1905'
describe '#partnerName', ->
it "partner name", ->
@artwork.set partner: fabricate 'partner'
@artwork.unset 'collecting_institution'
@artwork.partnerName().should.equal 'Gagosian Gallery'
it "partner name with collecting institution", ->
@artwork.set partner: fabricate 'partner'
@artwork.partnerName().should.equal 'MOMA'
describe '#partnerLink', ->
it "empty without partner", ->
@artwork.unset 'partner'
should.strictEqual(undefined, @artwork.partnerLink())
it "partner profile", ->
@artwork.get('partner').default_profile_public = true
@artwork.get('partner').default_profile_id = 'profile-id'
@artwork.partnerLink().should.equal '/profile-id'
it "doesn't render an external website", ->
@artwork.get('partner').default_profile_public = false
@artwork.get('partner').default_profile_id = 'profile-id'
@artwork.get('partner').website = 'mah-website.com'
should.strictEqual(undefined, @artwork.partnerLink())
it "partner website if profile and profile is private", ->
@artwork.get('partner').type = 'Auction'
should.strictEqual(undefined, @artwork.partnerLink())
describe '#href', ->
it 'creates an href for linking to this artwork', ->
@artwork.href().should.equal "/artwork/#{@artwork.get('id')}"
describe '#toAltText', ->
it "Includes title, date and artist name", ->
@artwork.toAltText().should.equal "PI:NAME:<NAME>END_PI, 'Skull,' 1999, Gagosian Gallery"
it "Works without title, date, partner, and artist name", ->
@artwork.set
artist: undefined
date: undefined
title: undefined
partner: undefined
@artwork.toAltText().should.equal ""
describe "artistName", ->
it "renders correctly", ->
new Artwork(title: "title", forsale: false).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: undefined }).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }]).artistName().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: "popeye the sailor" }).artistName().should.equal "popeye the sailor"
new Artwork(title: "title", forsale: false, artists: [{ name: "cap'n crunch" }]).artistName().should.equal "cap'n crunch"
new Artwork(title: "title", forsale: false, artists: [{ name: "cap'n crunch" }, { name: "popeye the sailor" }]).artistName().should.equal "cap'n crunch"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "so and so" }]).artistName().should.equal "so and so"
new Artwork(title: "title", forsale: false, artist: { name: undefined }, artists: [{ name: "so and so" }]).artistName().should.equal "so and so"
describe "artistsNames", ->
it "renders correctly", ->
new Artwork(title: "title", forsale: false).artistsNames().should.equal ""
new Artwork(title: "title", forsale: false, artist: { name: "PI:NAME:<NAME>END_PI" }).artistsNames().should.equal "PI:NAME:<NAME>END_PI"
new Artwork(title: "title", forsale: false, artists: [{ name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }]).artistsNames().should.equal "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI twain"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "PI:NAME:<NAME>END_PI" }]).artistsNames().should.equal "mark twain"
new Artwork(title: "title", forsale: false, artists: [{ name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }]).artistsNames().should.equal "PI:NAME:<NAME>END_PI, mark twain and PI:NAME:<NAME>END_PIperoni"
new Artwork(title: "title", forsale: false, artists: [{ name: undefined }, { name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }]).artistsNames().should.equal "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"
describe "#toPageTitle", ->
it "renders correctly", ->
new Artwork(title: "", forsale: false).toPageTitle().should.equal "Artsy"
new Artwork(title: "title", forsale: false).toPageTitle().should.equal "title | Artsy"
new Artwork(title: "title", forsale: true).toPageTitle().should.equal "title, Available for Sale | Artsy"
new Artwork(title: "title", forsale: false, artist: { name: "PI:NAME:<NAME>END_PI" }).toPageTitle().should.equal "PI:NAME:<NAME>END_PI | title | Artsy"
new Artwork(title: "title", forsale: false, artists: [{ name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }]).toPageTitle().should.equal "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI | title | Artsy"
new Artwork(title: "title", forsale: false, artists: [{ name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }, { name: "hello kitty" }]).toPageTitle().should.equal "PI:NAME:<NAME>END_PI, sPI:NAME:<NAME>END_PI claPI:NAME:<NAME>END_PI and hello kitty | title | Artsy"
new Artwork(title: "", forsale: false, artist: { name: "last" }).toPageTitle().should.equal "last | Artsy"
new Artwork(title: "title", forsale: false, date: "2010" ).toPageTitle().should.equal "title (2010) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010", artist: { name: "last" }).toPageTitle().should.equal "last | title (2010) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010-2011", artist: { name: "first last" }).toPageTitle().should.equal "first last | title (2010-2011) | Artsy"
new Artwork(title: "title", forsale: false, date: "2010, 2011, 2012", artist: { name: "first last" }).toPageTitle().should.equal "first last | title (2010, 2011, 2012) | Artsy"
describe "#toPageDescription", ->
it "renders correctly", ->
new Artwork(title: "title").toPageDescription().should.equal "title"
new Artwork(title: "title", partner: { name: 'partner' }, forsale: false).toPageDescription().should.equal "From partner, title"
new Artwork(title: "title", partner: { name: 'partner' }, forsale: true).toPageDescription().should.equal "Available for sale from partner, title"
new Artwork(title: "title", dimensions: { in: "2 × 1 × 3 in" }, metric: 'in', forsale: false).toPageDescription().should.equal "title, 2 × 1 × 3 in"
new Artwork(title: "title", dimensions: { in: "2 × 1 × 3 in" }, metric: 'in', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 2 × 1 × 3 in"
new Artwork(title: "title", dimensions: { cm: "45000000 × 2000000000 cm" }, metric: 'cm', forsale: false).toPageDescription().should.equal "title, 45000000 × 2000000000 cm"
new Artwork(title: "title", dimensions: { cm: "45000000 × 2000000000 cm" }, metric: 'cm', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 45000000 × 2000000000 cm"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', forsale: false).toPageDescription().should.equal "title, 20 cm diameter"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', medium: "Awesomeness", forsale: false).toPageDescription().should.equal "title, Awesomeness, 20 cm diameter"
new Artwork(title: "title", dimensions: { cm: "20 cm diameter" }, metric: 'cm', medium: "Awesomeness", artist: { name: "PI:NAME:<NAME>END_PI" }, forsale: false).toPageDescription().should.equal "first last, title, Awesomeness, 20 cm diameter"
describe '#toJSONLD', ->
it 'returns valid json', ->
json = @artwork.toJSONLD()
json['@context'].should.equal 'http://schema.org'
json['@type'].should.equal 'CreativeWork'
json.name.should.equal 'PI:NAME:<NAME>END_PI'
|
[
{
"context": "er.Models.AccountGroup(\n id: 10\n name: \"Personal\"\n )\n\n createView = (model = createModel())->\n",
"end": 146,
"score": 0.8795560002326965,
"start": 138,
"tag": "NAME",
"value": "Personal"
}
] | spec/javascripts/dot_ledger/views/account_groups/list_item_spec.js.coffee | malclocke/dotledger | 0 | describe "DotLedger.Views.AccountGroups.ListItem", ->
createModel = ->
new DotLedger.Models.AccountGroup(
id: 10
name: "Personal"
)
createView = (model = createModel())->
new DotLedger.Views.AccountGroups.ListItem(
model: model
)
it "should be defined", ->
expect(DotLedger.Views.AccountGroups.ListItem).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.AccountGroups.ListItem).toUseTemplate('account_groups/list_item')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the name", ->
view = createView().render()
expect(view.$el).toContainText('Personal')
it "renders the edit button", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/account-groups/10/edit"]')
expect(view.$el).toContainText('Edit')
it "renders the delete button", ->
view = createView().render()
expect(view.$el).toContainElement('a.delete-account-group')
expect(view.$el).toContainText('Delete')
| 30855 | describe "DotLedger.Views.AccountGroups.ListItem", ->
createModel = ->
new DotLedger.Models.AccountGroup(
id: 10
name: "<NAME>"
)
createView = (model = createModel())->
new DotLedger.Views.AccountGroups.ListItem(
model: model
)
it "should be defined", ->
expect(DotLedger.Views.AccountGroups.ListItem).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.AccountGroups.ListItem).toUseTemplate('account_groups/list_item')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the name", ->
view = createView().render()
expect(view.$el).toContainText('Personal')
it "renders the edit button", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/account-groups/10/edit"]')
expect(view.$el).toContainText('Edit')
it "renders the delete button", ->
view = createView().render()
expect(view.$el).toContainElement('a.delete-account-group')
expect(view.$el).toContainText('Delete')
| true | describe "DotLedger.Views.AccountGroups.ListItem", ->
createModel = ->
new DotLedger.Models.AccountGroup(
id: 10
name: "PI:NAME:<NAME>END_PI"
)
createView = (model = createModel())->
new DotLedger.Views.AccountGroups.ListItem(
model: model
)
it "should be defined", ->
expect(DotLedger.Views.AccountGroups.ListItem).toBeDefined()
it "should use the correct template", ->
expect(DotLedger.Views.AccountGroups.ListItem).toUseTemplate('account_groups/list_item')
it "can be rendered", ->
view = createView()
expect(view.render).not.toThrow()
it "renders the name", ->
view = createView().render()
expect(view.$el).toContainText('Personal')
it "renders the edit button", ->
view = createView().render()
expect(view.$el).toContainElement('a[href="/account-groups/10/edit"]')
expect(view.$el).toContainText('Edit')
it "renders the delete button", ->
view = createView().render()
expect(view.$el).toContainElement('a.delete-account-group')
expect(view.$el).toContainText('Delete')
|
[
{
"context": "equest.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken())\n#\t\t\t\t\terror: (jqXHR, textStatus, err",
"end": 2071,
"score": 0.5372979640960693,
"start": 2065,
"tag": "KEY",
"value": "stored"
}
] | packages/steedos-application-package/models/application_package.coffee | zonglu233/fuel-car | 0 | Creator.Objects.application_package =
name: "application_package"
icon: "custom.custom42"
label: "软件包"
fields:
name:
type: "text"
label: "名称"
apps:
type: "lookup"
label: "应用"
type: "lookup"
reference_to: "apps"
multiple: true
optionsFunction: ()->
_options = []
_.forEach Creator.Apps, (o, k)->
_options.push {label: o.name, value: k, icon: o.icon_slds}
return _options
objects:
type: "lookup"
label: "对象"
reference_to: "objects"
multiple: true
optionsFunction: ()->
_options = []
_.forEach Creator.objectsByName, (o, k)->
if !o.hidden
_options.push { label: o.label, value: k, icon: o.icon }
return _options
list_views:
type: "lookup"
label: "列表视图"
multiple: true
reference_to: "object_listviews"
optionsMethod: "creator.listviews_options"
permission_set:
type: "lookup"
label: "权限组"
multiple: true
reference_to: "permission_set"
permission_objects:
type: "lookup"
label: "权限集"
multiple: true
reference_to: "permission_objects"
reports:
type: "lookup"
label: "报表"
multiple: true
reference_to: "reports"
list_views:
all:
columns: ["name"]
filter_scope: "space"
actions:
init_data:
label: "初始化"
visible: true
on: "record"
todo: (object_name, record_id, fields)->
console.log(object_name, record_id, fields)
Meteor.call "appPackage.init_export_data", Session.get("spaceId"), record_id,(error, result)->
if error
toastr.error(error.reason)
else
toastr.success("初始化完成")
export:
label: "导出"
visible: true
on: "record"
todo: (object_name, record_id, fields)->
console.log("导出#{object_name}->#{record_id}")
url = Steedos.absoluteUrl "/api/creator/app_package/export/#{Session.get("spaceId")}/#{record_id}"
window.open(url)
# $.ajax
# type: "post"
# url: url
# dataType: "json"
# beforeSend: (request) ->
# request.setRequestHeader('X-User-Id', Meteor.userId())
# request.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken())
# error: (jqXHR, textStatus, errorThrown) ->
# error = jqXHR.responseJSON
# console.error error
# if error?.reason
# toastr?.error?(TAPi18n.__(error.reason))
# else if error?.message
# toastr?.error?(TAPi18n.__(error.message))
# else
# toastr?.error?(error)
# success: (result) ->
# console.log("result...................#{result}")
import:
label: "导入"
visible: true
on: "list"
todo: (object_name)->
console.log("object_name", object_name)
Modal.show("APPackageImportModal")
| 211567 | Creator.Objects.application_package =
name: "application_package"
icon: "custom.custom42"
label: "软件包"
fields:
name:
type: "text"
label: "名称"
apps:
type: "lookup"
label: "应用"
type: "lookup"
reference_to: "apps"
multiple: true
optionsFunction: ()->
_options = []
_.forEach Creator.Apps, (o, k)->
_options.push {label: o.name, value: k, icon: o.icon_slds}
return _options
objects:
type: "lookup"
label: "对象"
reference_to: "objects"
multiple: true
optionsFunction: ()->
_options = []
_.forEach Creator.objectsByName, (o, k)->
if !o.hidden
_options.push { label: o.label, value: k, icon: o.icon }
return _options
list_views:
type: "lookup"
label: "列表视图"
multiple: true
reference_to: "object_listviews"
optionsMethod: "creator.listviews_options"
permission_set:
type: "lookup"
label: "权限组"
multiple: true
reference_to: "permission_set"
permission_objects:
type: "lookup"
label: "权限集"
multiple: true
reference_to: "permission_objects"
reports:
type: "lookup"
label: "报表"
multiple: true
reference_to: "reports"
list_views:
all:
columns: ["name"]
filter_scope: "space"
actions:
init_data:
label: "初始化"
visible: true
on: "record"
todo: (object_name, record_id, fields)->
console.log(object_name, record_id, fields)
Meteor.call "appPackage.init_export_data", Session.get("spaceId"), record_id,(error, result)->
if error
toastr.error(error.reason)
else
toastr.success("初始化完成")
export:
label: "导出"
visible: true
on: "record"
todo: (object_name, record_id, fields)->
console.log("导出#{object_name}->#{record_id}")
url = Steedos.absoluteUrl "/api/creator/app_package/export/#{Session.get("spaceId")}/#{record_id}"
window.open(url)
# $.ajax
# type: "post"
# url: url
# dataType: "json"
# beforeSend: (request) ->
# request.setRequestHeader('X-User-Id', Meteor.userId())
# request.setRequestHeader('X-Auth-Token', Accounts._<KEY>LoginToken())
# error: (jqXHR, textStatus, errorThrown) ->
# error = jqXHR.responseJSON
# console.error error
# if error?.reason
# toastr?.error?(TAPi18n.__(error.reason))
# else if error?.message
# toastr?.error?(TAPi18n.__(error.message))
# else
# toastr?.error?(error)
# success: (result) ->
# console.log("result...................#{result}")
import:
label: "导入"
visible: true
on: "list"
todo: (object_name)->
console.log("object_name", object_name)
Modal.show("APPackageImportModal")
| true | Creator.Objects.application_package =
name: "application_package"
icon: "custom.custom42"
label: "软件包"
fields:
name:
type: "text"
label: "名称"
apps:
type: "lookup"
label: "应用"
type: "lookup"
reference_to: "apps"
multiple: true
optionsFunction: ()->
_options = []
_.forEach Creator.Apps, (o, k)->
_options.push {label: o.name, value: k, icon: o.icon_slds}
return _options
objects:
type: "lookup"
label: "对象"
reference_to: "objects"
multiple: true
optionsFunction: ()->
_options = []
_.forEach Creator.objectsByName, (o, k)->
if !o.hidden
_options.push { label: o.label, value: k, icon: o.icon }
return _options
list_views:
type: "lookup"
label: "列表视图"
multiple: true
reference_to: "object_listviews"
optionsMethod: "creator.listviews_options"
permission_set:
type: "lookup"
label: "权限组"
multiple: true
reference_to: "permission_set"
permission_objects:
type: "lookup"
label: "权限集"
multiple: true
reference_to: "permission_objects"
reports:
type: "lookup"
label: "报表"
multiple: true
reference_to: "reports"
list_views:
all:
columns: ["name"]
filter_scope: "space"
actions:
init_data:
label: "初始化"
visible: true
on: "record"
todo: (object_name, record_id, fields)->
console.log(object_name, record_id, fields)
Meteor.call "appPackage.init_export_data", Session.get("spaceId"), record_id,(error, result)->
if error
toastr.error(error.reason)
else
toastr.success("初始化完成")
export:
label: "导出"
visible: true
on: "record"
todo: (object_name, record_id, fields)->
console.log("导出#{object_name}->#{record_id}")
url = Steedos.absoluteUrl "/api/creator/app_package/export/#{Session.get("spaceId")}/#{record_id}"
window.open(url)
# $.ajax
# type: "post"
# url: url
# dataType: "json"
# beforeSend: (request) ->
# request.setRequestHeader('X-User-Id', Meteor.userId())
# request.setRequestHeader('X-Auth-Token', Accounts._PI:KEY:<KEY>END_PILoginToken())
# error: (jqXHR, textStatus, errorThrown) ->
# error = jqXHR.responseJSON
# console.error error
# if error?.reason
# toastr?.error?(TAPi18n.__(error.reason))
# else if error?.message
# toastr?.error?(TAPi18n.__(error.message))
# else
# toastr?.error?(error)
# success: (result) ->
# console.log("result...................#{result}")
import:
label: "导入"
visible: true
on: "list"
todo: (object_name)->
console.log("object_name", object_name)
Modal.show("APPackageImportModal")
|
[
{
"context": "\nmodule.exports =\n \n password:\n saltSize: 16\n keySize: 4\n iterations: 1500\n ",
"end": 53,
"score": 0.7247660756111145,
"start": 45,
"tag": "PASSWORD",
"value": "saltSize"
},
{
"context": "le.exports =\n \n password:\n saltSize: 16\n keySize: 4\n iterations: 1500\n ",
"end": 57,
"score": 0.8146454095840454,
"start": 55,
"tag": "PASSWORD",
"value": "16"
}
] | modules/crypto/config/index.coffee | nero-networks/floyd | 0 |
module.exports =
password:
saltSize: 16
keySize: 4
iterations: 1500
hasher: 'SHA256'
| 124040 |
module.exports =
password:
<PASSWORD>: <PASSWORD>
keySize: 4
iterations: 1500
hasher: 'SHA256'
| true |
module.exports =
password:
PI:PASSWORD:<PASSWORD>END_PI: PI:PASSWORD:<PASSWORD>END_PI
keySize: 4
iterations: 1500
hasher: 'SHA256'
|
[
{
"context": "###\n@authors\nNicolas Laplante - https://plus.google.com/108189012221374960701\nN",
"end": 29,
"score": 0.9998895525932312,
"start": 13,
"tag": "NAME",
"value": "Nicolas Laplante"
},
{
"context": "e - https://plus.google.com/108189012221374960701\nNicholas McCready - https://twitter.com/nmccready\n###\n\n###\nMap info",
"end": 95,
"score": 0.9998817443847656,
"start": 78,
"tag": "NAME",
"value": "Nicholas McCready"
},
{
"context": "374960701\nNicholas McCready - https://twitter.com/nmccready\n###\n\n###\nMap info window directive\n\nThis directiv",
"end": 127,
"score": 0.9995477199554443,
"start": 118,
"tag": "USERNAME",
"value": "nmccready"
}
] | public/bower_components/angular-google-maps/src/coffee/directives/windows.coffee | arslannaseem/notasoft | 1 | ###
@authors
Nicolas Laplante - https://plus.google.com/108189012221374960701
Nicholas McCready - https://twitter.com/nmccready
###
###
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
###
angular.module("uiGmapgoogle-maps")
.directive "uiGmapWindows", ["$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows",
($timeout, $compile, $http, $templateCache, $interpolate, Windows) ->
new Windows($timeout, $compile, $http, $templateCache, $interpolate)
]
| 80823 | ###
@authors
<NAME> - https://plus.google.com/108189012221374960701
<NAME> - https://twitter.com/nmccready
###
###
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
###
angular.module("uiGmapgoogle-maps")
.directive "uiGmapWindows", ["$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows",
($timeout, $compile, $http, $templateCache, $interpolate, Windows) ->
new Windows($timeout, $compile, $http, $templateCache, $interpolate)
]
| true | ###
@authors
PI:NAME:<NAME>END_PI - https://plus.google.com/108189012221374960701
PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
###
###
Map info window directive
This directive is used to create an info window on an existing map.
This directive creates a new scope.
{attribute coords required} object containing latitude and longitude properties
{attribute show optional} map will show when this expression returns true
###
angular.module("uiGmapgoogle-maps")
.directive "uiGmapWindows", ["$timeout", "$compile", "$http", "$templateCache", "$interpolate", "uiGmapWindows",
($timeout, $compile, $http, $templateCache, $interpolate, Windows) ->
new Windows($timeout, $compile, $http, $templateCache, $interpolate)
]
|
[
{
"context": "tch\r\n when passwordPrompt then \"password: #{@sshObj.server.password}\"\r\n when passphras",
"end": 8959,
"score": 0.8145740032196045,
"start": 8959,
"tag": "PASSWORD",
"value": ""
},
{
"context": " when passwordPrompt then \"password: #{@sshObj.server.password}\"\r\n when passphrasePrompt",
"end": 8969,
"score": 0.518282413482666,
"start": 8969,
"tag": "PASSWORD",
"value": ""
},
{
"context": "shObj.server.userName\r\n password: @sshObj.server.password\r\n agent: @",
"end": 27581,
"score": 0.8369202613830566,
"start": 27577,
"tag": "PASSWORD",
"value": "@ssh"
},
{
"context": "Obj.server.privateKey\r\n passphrase: @sshObj.server.passPhrase\r\n localHostname: ",
"end": 27796,
"score": 0.6105784177780151,
"start": 27792,
"tag": "PASSWORD",
"value": "@ssh"
},
{
"context": "er.privateKey\r\n passphrase: @sshObj.server.passPhrase\r\n localHostname: @ss",
"end": 27799,
"score": 0.5280774831771851,
"start": 27799,
"tag": "PASSWORD",
"value": ""
}
] | controlRoom_server/server/node_modules/ssh2shell/src/ssh2shell.coffee | benamrou/controlRoom | 0 | #================================
# SSH2Shel
#================================
# Description
# SSH2 wrapper for creating a SSH shell connection and running multiple commands sequentially.
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
Stream = require('stream');
class SSH2Shell extends Stream
sshObj: {}
command: ""
hosts: []
_primaryhostSessionText: ""
_allSessions: ""
_connections: []
_stream: {}
_buffer: ""
idleTime: 5000
asciiFilter: ""
textColorFilter: ""
passwordPromt: ""
passphrasePromt: ""
standardPrompt: ""
_callback: =>
onCommandProcessing:=>
onCommandComplete: =>
onCommandTimeout: =>
onEnd: =>
_onData: ( data )=>
#add host response data to buffer
@_buffer += data
if @command.length > 0 and not @standardPrompt.test(@_sanitizeResponse())
#continue loading the buffer and set/reset a timeout
@.emit 'commandProcessing' , @command, @_buffer, @sshObj, @_stream
clearTimeout @idleTimer if @idleTimer
@idleTimer = setTimeout( =>
@.emit 'commandTimeout', @.command, @._buffer, @._stream, @._connection
, @idleTime)
else if @command.length < 1 and not @standardPrompt.test(@_buffer)
@.emit 'commandProcessing' , @command, @_buffer, @sshObj, @_stream
#Set a timer to fire when no more data events are received
#and then process the buffer based on command and prompt combinations
clearTimeout @dataReceivedTimer if @dataReceivedTimer
@dataReceivedTimer = setTimeout( =>
#clear the command and SSH timeout timer
clearTimeout @idleTimer if @idleTimer
#remove test coloring from responses like [32m[31m
unless @.sshObj.disableColorFilter
@emit 'msg', "#{@sshObj.server.host}: text formatting filter: "+@sshObj.textColorFilter+", filtered: "+@textColorFilter.test(@_buffer) if @sshObj.verbose and @sshObj.debug
@_buffer = @_buffer.replace(@textColorFilter, "")
#remove non-standard ascii from terminal responses
unless @.sshObj.disableASCIIFilter
@emit 'msg', "#{@sshObj.server.host}: Non-standard ASCII filtered: "+@asciiFilter.test(@_buffer) if @sshObj.verbose and @sshObj.debug
@_buffer = @_buffer.replace(@asciiFilter, "")
switch (true)
#check if sudo password is needed
when @command.length > 0 and @command.indexOf("sudo ") isnt -1
@emit 'msg', "#{@sshObj.server.host}: Sudo command data" if @sshObj.debug
@_processPasswordPrompt()
#check if ssh authentication needs to be handled
when @command.length > 0 and @command.indexOf("ssh ") isnt -1
@emit 'msg', "#{@sshObj.server.host}: SSH command data" if @sshObj.debug
@_processSSHPrompt()
#check for standard prompt from a command
when @command.length > 0 and @standardPrompt.test(@_sanitizeResponse())
@emit 'msg', "#{@sshObj.server.host}: Normal prompt detected" if @sshObj.debug
@sshObj.pwSent = false #reset sudo prompt checkable
@_commandComplete()
#check for no command but first prompt detected
when @command.length < 1 and @standardPrompt.test(@_buffer)
@emit 'msg', "#{@sshObj.server.host}: First prompt detected" if @sshObj.debug
@sshObj.sessionText += @_buffer if @sshObj.showBanner
@_nextCommand()
else
@emit 'msg', "Data processing: data received timeout" if @sshObj.debug
@idleTimer = setTimeout( =>
@.emit 'commandTimeout', @.command, @._buffer, @._stream, @._connection
, @idleTime)
, @dataIdleTime)
_sanitizeResponse: =>
return @_buffer.replace(@command.substr(0, @_buffer.length), "")
_processPasswordPrompt: =>
#First test for password prompt
response = @_sanitizeResponse().trim()
passwordPrompt = @passwordPromt.test(response)
passphrase = @passphrasePromt.test(response)
standardPrompt = @standardPrompt.test(response)
@.emit 'msg', "#{@sshObj.server.host}: Password previously sent: #{@sshObj.pwSent}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Password previously sent: #{@sshObj.pwSent}" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Response: #{response}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Sudo Password Prompt: #{passwordPrompt}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Sudo Password: #{@sshObj.server.password}" if @sshObj.verbose
#normal prompt so continue with next command
if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Standard prompt detected" if @sshObj.debug
@_commandComplete()
@sshObj.pwSent = true
#Password prompt detection
else unless @sshObj.pwSent
if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Buffer: #{response}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Send password " if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Sent password: #{@sshObj.server.password}" if @sshObj.verbose
#send password
@sshObj.pwSent = true
@_runCommand("#{@sshObj.server.password}")
else
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: not detected first test" if @sshObj.debug
#password sent so either check for failure or run next command
else if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: Sudo password faied: response: #{response}" if @sshObj.verbose
@.emit 'error', "#{@sshObj.server.host}: Sudo password was incorrect for #{@sshObj.server.userName}", "Sudo authentication" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Failed password prompt: Password: [#{@sshObj.server.password}]" if @sshObj.debug
#add buffer to sessionText so the sudo response can be seen
@sshObj.sessionText += "#{@_buffer}"
@_buffer = ""
#@sshObj.commands = []
@command = ""
@_stream.write '\x03'
_processSSHPrompt: =>
#not authenticated yet so detect prompts
response = @_sanitizeResponse().trim()
clearTimeout @idleTimer if @idleTimer
passwordPrompt = @passwordPromt.test(response) and not @sshObj.server.hasOwnProperty("passPhrase")
passphrasePrompt = @passphrasePromt.test(response) and @sshObj.server.hasOwnProperty("passPhrase")
standardPrompt = @standardPrompt.test(response)
@.emit 'msg', "#{@sshObj.server.host}: SSH: Password previously sent: #{@sshObj.sshAuth}" if @sshObj.verbose
unless @sshObj.sshAuth
@.emit 'msg', "#{@sshObj.server.host}: First SSH prompt detection" if @sshObj.debug
#provide password
if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH send password" if @sshObj.debug
@sshObj.sshAuth = true
@_buffer = ""
@_runCommand("#{@sshObj.server.password}")
#provide passphrase
else if passphrasePrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH send passphrase" if @sshObj.debug
@sshObj.sshAuth = true
@_buffer = ""
@_runCommand("#{@sshObj.server.passPhrase}")
#normal prompt so continue with next command
else if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH: standard prompt: connection failed" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: SSH connection failed"
@.emit 'msg', "#{@sshObj.server.host}: SSH failed response: #{response}"
@sshObj.sessionText += "#{@sshObj.server.host}: SSH failed: response: #{response}"
@_runExit()
else
@.emit 'msg', "#{@sshObj.server.host}: SSH post authentication prompt detection" if @sshObj.debug
#normal prompt after authentication, start running commands.
if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH complete: normal prompt" if @sshObj.debug
@sshObj.exitCommands.push "exit"
@.emit 'msg', "#{@sshObj.connectedMessage}"
@.emit 'msg', "#{@sshObj.readyMessage}"
@_nextCommand()
#Password or passphase detected a second time after authentication indicating failure.
else if (passwordPrompt or passphrasePrompt)
@.emit 'msg', "#{@sshObj.server.host}: SSH authentication failed"
@.emit 'msg', "#{@sshObj.server.host}: SSH auth failed" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: SSH: failed response: #{response}" if @sshObj.verbose
@sshObj.sshAuth = false
using = switch
when passwordPrompt then "password: #{@sshObj.server.password}"
when passphrasePrompt then "passphrase: #{@sshObj.server.passPhrase}"
@.emit 'error', "#{@sshObj.server.host}: SSH authentication failed for #{@sshObj.server.userName}@#{@sshObj.server.host}", "Nested host authentication"
@.emit 'msg', "#{@sshObj.server.host}: SSH auth failed: Using " + using if @sshObj.debug
#no connection so drop back to first host settings if there was one
#@sshObj.sessionText += "#{@_buffer}"
@.emit 'msg', "#{@sshObj.server.host}: SSH resonse: #{response}" if @sshObj.verbose and @sshObj.debug
if @_connections.length > 0
return @_previousHost()
@_runExit()
_processNotifications: =>
#check for notifications in commands
if @command
#this is a message for the sessionText like an echo command in bash
if (sessionNote = @command.match(/^`(.*)`$/))
@.emit 'msg', "#{@sshObj.server.host}: Notifications: sessionText output" if @sshObj.debug
if @_connections.length > 0
@sshObj.sessionText += "#{@sshObj.server.host}: Note: #{sessionNote[1]}#{@sshObj.enter}"
else
@sshObj.sessionText += "Note: #{sessionNote[1]}#{@sshObj.enter}"
@.emit 'msg', sessionNote[1] if @sshObj.verbose
@_nextCommand()
#this is a message to output in process
else if (msgNote = @command.match(/^msg:(.*)$/))
@.emit 'msg', "#{@sshObj.server.host}: Notifications: msg to output" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Note: #{msgNote[1]}"
@_nextCommand()
else
@.emit 'msg', "#{@sshObj.server.host}: Notifications: Normal Command to run" if @sshObj.debug
@_checkCommand()
_commandComplete: =>
response = @_buffer.trim() #replace(@command, "")
#check sudo su has been authenticated and add an extra exit command
if @command.indexOf("sudo su") isnt -1
@.emit 'msg', "#{@sshObj.server.host}: Sudo su adding exit." if @sshObj.debug
@sshObj.exitCommands.push "exit"
if @command isnt "" and @command isnt "exit" and @command.indexOf("ssh ") is -1
@.emit 'msg', "#{@sshObj.server.host}: Command complete:\nCommand:\n #{@command}\nResponse: #{response}" if @sshObj.verbose
#Not running an exit command or first prompt detection after connection
#load the full buffer into sessionText and raise a commandComplete event
@sshObj.sessionText += response
@.emit 'msg', "#{@sshObj.server.host}: Raising commandComplete event" if @sshObj.debug
@.emit 'commandComplete', @command, @_buffer, @sshObj
if @command.indexOf("exit") != -1
@_runExit()
else
@_nextCommand()
_nextCommand: =>
@_buffer = ""
#process the next command if there are any
if @sshObj.commands.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Host.commands: #{@sshObj.commands}" if @sshObj.verbose
@command = @sshObj.commands.shift()
@.emit 'msg', "#{@sshObj.server.host}: Next command from host.commands: #{@command}" if @sshObj.verbose
@_processNotifications()
else
@.emit 'msg', "#{@sshObj.server.host}: No commands so exit" if @sshObj.debug
#no more commands so exit
@_runExit()
_checkCommand: =>
#if there is still a command to run then run it or exit
if @command != ""
@_runCommand(@command)
else
#no more commands so exit
@.emit 'msg', "#{@sshObj.server.host}: No command so exit" if @sshObj.debug
@_runExit()
_runCommand: (command) =>
@.emit 'msg', "#{@sshObj.server.host}: sending: #{command}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: run command" if @sshObj.debug
@_stream.write "#{command}#{@sshObj.enter}"
_previousHost: =>
@.emit 'msg', "#{@sshObj.server.host}: Load previous host config" if @sshObj.debug
@.emit 'end', "#{@sshObj.server.host}: \n#{@sshObj.sessionText}", @sshObj
@.emit 'msg', "#{@sshObj.server.host}: Previous hosts: #{@_connections.length}" if @sshObj.debug
if @_connections.length > 0
@sshObj = @_connections.pop()
@.emit 'msg', "#{@sshObj.server.host}: Reload previous host" if @sshObj.debug
@_loadDefaults(@_runExit)
else
@_runExit()
_nextHost: =>
nextHost = @sshObj.hosts.shift()
@.emit 'msg', "#{@sshObj.server.host}: SSH to #{nextHost.server.host}" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Clearing previous event handlers" if @sshObj.debug
@_connections.push(@sshObj)
@sshObj = nextHost
@_initiate(@_sshConnect)
_nextPrimaryHost: ( callback )=>
if typeIsArray(@hosts) and @hosts.length > 0
if @sshObj.server
@.emit 'msg', "#{@sshObj.server.host}: Current primary host" if @sshObj.debug
@sshObj = @hosts.shift()
@_primaryhostSessionText = "#{@sshObj.server.host}: "
@.emit 'msg', "#{@sshObj.server.host}: Next primary host" if @sshObj.debug
@_initiate(callback)
else
@.emit 'msg', "#{@sshObj.server.host}: No more primary hosts" if @sshObj.debug
@_runExit
_sshConnect: =>
#add ssh commandline options from host.server.ssh
sshFlags = "-x"
sshOptions = ""
if @sshObj.server.ssh
sshFlags += @sshObj.server.ssh.forceProtocolVersion if @sshObj.server.ssh.forceProtocolVersion
sshFlags += @sshObj.server.ssh.forceAddressType if @sshObj.server.ssh.forceAddressType
sshFlags += "T" if @sshObj.server.ssh.disablePseudoTTY
sshFlags += "t" if @sshObj.server.ssh.forcePseudoTTY
sshFlags += "v" if @sshObj.server.ssh.verbose
sshOptions += " -c " + @sshObj.server.ssh.cipherSpec if @sshObj.server.ssh.cipherSpec
sshOptions += " -e " + @sshObj.server.ssh.escape if @sshObj.server.ssh.escape
sshOptions += " -E " + @sshObj.server.ssh.logFile if @sshObj.server.ssh.logFile
sshOptions += " -F " + @sshObj.server.ssh.configFile if @sshObj.server.ssh.configFile
sshOptions += " -i " + @sshObj.server.ssh.identityFile if @sshObj.server.ssh.identityFile
sshOptions += " -l " + @sshObj.server.ssh.loginName if @sshObj.server.ssh.loginName
sshOptions += " -m " + @sshObj.server.ssh.macSpec if @sshObj.server.ssh.macSpec
sshOptions += ' -o "#{option}={#value}"' for option,value of @sshObj.server.ssh.Options
sshOptions += ' -o "StrictHostKeyChecking=no"'
sshOptions += " -p #{@sshObj.server.port}"
@sshObj.sshAuth = false
@command = "ssh #{sshFlags} #{sshOptions} #{@sshObj.server.userName}@#{@sshObj.server.host}"
@.emit 'msg', "#{@sshObj.server.host}: SSH command: connect" if @sshObj.debug
@_runCommand(@command)
_runExit: =>
@.emit 'msg', "#{@sshObj.server.host}: Process an exit" if @sshObj.debug
#run the exit commands loaded by ssh and sudo su commands
if @sshObj.exitCommands and @sshObj.exitCommands.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Queued exit commands: #{@sshObj.exitCommands.length}" if @sshObj.debug
@command = @sshObj.exitCommands.pop()
@_connections[0].sessionText += "\n#{@sshObj.server.host}: #{@sshObj.sessionText}"
@_runCommand(@command)
#more hosts to connect to so process the next one
else if @sshObj.hosts and @sshObj.hosts.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Next host from this host" if @sshObj.debug
@_nextHost()
#Leaving last host so load previous host
else if @_connections and @_connections.length > 0
@.emit 'msg', "#{@sshObj.server.host}: load previous host" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: #{@sshObj.closedMessage}"
@_previousHost()
#else if typeIsArray(@hosts) and @hosts.length > 0
#@connection.end()
#Nothing more to do so end the stream with last exit
else
@.emit 'msg', "#{@sshObj.server.host}: Exit command: Stream: close" if @sshObj.debug
#@.command = "stream.end()"
@_stream.close() #"exit#{@sshObj.enter}"
_removeEvents: =>
@.emit 'msg', "#{@sshObj.server.host}: Clearing host event handlers" if @sshObj.debug
@.removeAllListeners 'keyboard-interactive'
@.removeAllListeners "error"
@.removeListener "data", @sshObj.onData if typeof @sshObj.onData == 'function'
@.removeListener "stderrData", @sshObj.onStderrData if typeof @sshObj.onStderrData == 'function'
@.removeAllListeners 'end'
@.removeAllListeners 'commandProcessing'
@.removeAllListeners 'commandComplete'
@.removeAllListeners 'commandTimeout'
@.removeAllListeners 'msg'
clearTimeout @idleTimer if @idleTimer
clearTimeout @dataReceivedTimer if @dataReceivedTimer
constructor: (hosts) ->
if typeIsArray(hosts)
@hosts = hosts
else
@hosts = [hosts]
@ssh2Client = require('ssh2')
@.on "newPrimmaryHost", @_nextPrimaryHost
@.on "data", (data) =>
#@.emit 'msg', "#{@sshObj.server.host}: data event: #{data}" if @sshObj.verbose
@_onData( data )
@.on "stderrData", (data) =>
console.error data
@_allSessions = ""
_initiate: (callback)=>
@_removeEvents()
if typeof @sshObj.msg == 'function'
@.on "msg", @sshObj.msg.send
else
@.on "msg", ( message ) =>
console.log message
@_loadDefaults()
@.emit 'msg', "#{@sshObj.server.host}: initiate" if @sshObj.debug
#event handlers
@.on "keyboard-interactive", ( name, instructions, instructionsLang, prompts, finish ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.keyboard-interactive" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Keyboard-interactive: finish([response, array]) not called in class event handler." if @sshObj.debug
if @sshObj.verbose
@.emit 'msg', "name: " + name
@.emit 'msg', "instructions: " + instructions
str = JSON.stringify(prompts, null, 4)
@.emit 'msg', "Prompts object: " + str
@.on "error", (err, type, close = false, callback) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.error" if @sshObj.debug
if ( err instanceof Error )
@.emit 'msg', "Error: " + err.message + ", Level: " + err.level
else
@.emit 'msg', "#{type} error: " + err
callback(err, type) if typeof callback == 'function'
@connection.end() if close
@.on "end", ( sessionText, sshObj ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.end" if @sshObj.debug
if typeof callback == 'function'
callback()
_loadDefaults: (callback) =>
@.emit 'msg', "#{@sshObj.server.host}: Load Defaults" if @sshObj.debug
@command = ""
@_buffer = ""
@sshObj.connectedMessage = "Connected" unless @sshObj.connectedMessage
@sshObj.readyMessage = "Ready" unless @sshObj.readyMessage
@sshObj.closedMessage = "Closed" unless @sshObj.closedMessage
@sshObj.showBanner = false unless @sshObj.showBanner
@sshObj.verbose = false unless @sshObj.verbose
@sshObj.debug = false unless @sshObj.debug
@sshObj.hosts = [] unless @sshObj.hosts
@sshObj.commands = [] unless @sshObj.commands
@sshObj.standardPrompt = ">$%#" unless @sshObj.standardPrompt
@sshObj.passwordPromt = ":" unless @sshObj.passwordPromt
@sshObj.passphrasePromt = ":" unless @sshObj.passphrasePromt
@sshObj.passPromptText = "Password" unless @sshObj.passPromptText
@sshObj.enter = "\n" unless @sshObj.enter #windows = "\r\n", Linux = "\n", Mac = "\r"
@sshObj.asciiFilter = "[^\r\n\x20-\x7e]" unless @sshObj.asciiFilter
@sshObj.disableColorFilter = false unless @sshObj.disableColorFilter is true
@sshObj.disableASCIIFilter = false unless @sshObj.disableASCIIFilter is true
@sshObj.textColorFilter = "(\[{1}[0-9;]+m{1})" unless @sshObj.textColorFilter
@sshObj.exitCommands = [] unless @sshObj.exitCommands
@sshObj.pwSent = false
@sshObj.sshAuth = false
@sshObj.server.hashKey = @sshObj.server.hashKey ? ""
@sshObj.sessionText = "" unless @sshObj.sessionText
@sshObj.streamEncoding = @sshObj.streamEncoding ? "utf8"
@sshObj.window = true unless @sshObj.window
@sshObj.pty = true unless @sshObj.pty
@idleTime = @sshObj.idleTimeOut ? 5000
@dataIdleTime = @sshObj.dataIdleTime ? 500
@asciiFilter = new RegExp(@sshObj.asciiFilter,"g") unless @asciiFilter
@textColorFilter = new RegExp(@sshObj.textColorFilter,"g") unless @textColorFilter
@passwordPromt = new RegExp(@sshObj.passPromptText+".*" + @sshObj.passwordPromt + "\\s?$","i") unless @passwordPromt
@passphrasePromt = new RegExp(@sshObj.passPromptText+".*" + @sshObj.passphrasePromt + "\\s?$","i") unless @passphrasePromt
@standardPrompt = new RegExp("[" + @sshObj.standardPrompt + "]\\s?$") unless @standardPrompt
#@_callback = @sshObj.callback if @sshObj.callback
@sshObj.onCommandProcessing = @sshObj.onCommandProcessing ? ( command, response, sshObj, stream ) =>
@sshObj.onCommandComplete = @sshObj.onCommandComplete ? ( command, response, sshObj ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.commandComplete" if @sshObj.debug
@sshObj.onCommandTimeout = @sshObj.onCommandTimeout ? ( command, response, stream, connection ) =>
response = response.replace(@command, "")
@.emit 'msg', "#{@sshObj.server.host}: Class.commandTimeout" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Timeout command: #{command} response: #{response}" if @sshObj.verbose
@_runExit()
@.emit "error", "#{@sshObj.server.host}: Command timed out after #{@.idleTime/1000} seconds", "Timeout", true, (err, type)=>
@sshObj.sessionText += @_buffer
@.on "keyboard-interactive", @sshObj.onKeyboardInteractive if typeof @sshObj.onKeyboardInteractive == 'function'
@.on "error", @sshObj.onError if typeof @sshObj.onError == 'function'
@.on "data", @sshObj.onData if typeof @sshObj.onData == 'function'
@.on "stderrData", @sshObj.onStderrData if typeof @sshObj.onStderrData == 'function'
@.on "commandProcessing", @sshObj.onCommandProcessing
@.on "commandComplete", @sshObj.onCommandComplete
@.on "commandTimeout", @sshObj.onCommandTimeout
@.on "end", @sshObj.onEnd if typeof @sshObj.onEnd == 'function'
@.emit 'msg', "#{@sshObj.server.host}: Host loaded" if @sshObj.verbose
@.emit 'msg', @sshObj if @sshObj.verbose
if typeof callback == 'function'
callback()
connect: (callback)=>
@_callback = callback if typeof callback == 'function'
@.emit "newPrimaryHost", @_nextPrimaryHost(@_connect)
_connect: =>
@connection = new @ssh2Client()
@connection.on "keyboard-interactive", (name, instructions, instructionsLang, prompts, finish) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.keyboard-interactive" if @sshObj.debug
@.emit "keyboard-interactive", name, instructions, instructionsLang, prompts, finish
@connection.on "connect", =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.connect" if @sshObj.debug
@.emit 'msg', @sshObj.connectedMessage
@connection.on "ready", =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.ready" if @sshObj.debug
@.emit 'msg', @sshObj.readyMessage
#open a shell
@connection.shell @sshObj.window, { pty: @sshObj.pty }, (err, @_stream) =>
if err instanceof Error
@.emit 'error', err, "Shell", true
return
@.emit 'msg', "#{@sshObj.server.host}: Connection.shell" if @sshObj.debug
@_stream.setEncoding(@sshObj.streamEncoding);
@_stream.on "error", (err) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.error" if @sshObj.debug
@.emit 'error', err, "Stream"
@_stream.stderr.on 'data', (data) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.stderr.data" if @sshObj.debug
@.emit 'stderrData', data
@_stream.on "data", (data)=>
try
@.emit 'data', data
catch e
err = new Error("#{e} #{e.stack}")
err.level = "Data handling"
@.emit 'error', err, "Stream.read", true
@_stream.on "finish", =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.finish" if @sshObj.debug
@_primaryhostSessionText += @sshObj.sessionText+"\n"
@_allSessions += @_primaryhostSessionText
if typeIsArray(@hosts) and @hosts.length == 0
@.emit 'end', @_allSessions, @sshObj
@_removeEvents()
@_stream.on "close", (code, signal) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.close" if @sshObj.debug
@connection.end()
@connection.on "error", (err) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.error" if @sshObj.debug
@.emit "error", err, "Connection"
@connection.on "close", (had_error) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.close" if @sshObj.debug
if had_error
@.emit "error", had_error, "Connection close"
else
@.emit 'msg', @sshObj.closedMessage
if typeIsArray(@hosts) and @hosts.length == 0
if typeof @_callback == 'function'
@_callback @_allSessions
else
@.emit "newPrimaryHost", @_nextPrimaryHost(@_connect)
if @sshObj.server and @sshObj.commands
try
@connection.connect
host: @sshObj.server.host
port: @sshObj.server.port
forceIPv4: @sshObj.server.forceIPv4
forceIPv6: @sshObj.server.forceIPv6
hostHash: @sshObj.server.hashMethod
hostVerifier: @sshObj.server.hostVerifier
username: @sshObj.server.userName
password: @sshObj.server.password
agent: @sshObj.server.agent
agentForward: @sshObj.server.agentForward
privateKey: @sshObj.server.privateKey
passphrase: @sshObj.server.passPhrase
localHostname: @sshObj.server.localHostname
localUsername: @sshObj.server.localUsername
tryKeyboard: @sshObj.server.tryKeyboard
keepaliveInterval:@sshObj.server.keepaliveInterval
keepaliveCountMax:@sshObj.server.keepaliveCountMax
readyTimeout: @sshObj.server.readyTimeout
sock: @sshObj.server.sock
strictVendor: @sshObj.server.strictVendor
algorithms: @sshObj.server.algorithms
compress: @sshObj.server.compress
debug: @sshObj.server.debug
catch e
@.emit 'error', "#{e} #{e.stack}", "Connection.connect", true
else
@.emit 'error', "Missing connection parameters", "Parameters", false, ( err, type, close ) ->
@.emit 'msg', @sshObj.server
@.emit 'msg', @sshObj.commands
return @_stream
module.exports = SSH2Shell
| 47816 | #================================
# SSH2Shel
#================================
# Description
# SSH2 wrapper for creating a SSH shell connection and running multiple commands sequentially.
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
Stream = require('stream');
class SSH2Shell extends Stream
sshObj: {}
command: ""
hosts: []
_primaryhostSessionText: ""
_allSessions: ""
_connections: []
_stream: {}
_buffer: ""
idleTime: 5000
asciiFilter: ""
textColorFilter: ""
passwordPromt: ""
passphrasePromt: ""
standardPrompt: ""
_callback: =>
onCommandProcessing:=>
onCommandComplete: =>
onCommandTimeout: =>
onEnd: =>
_onData: ( data )=>
#add host response data to buffer
@_buffer += data
if @command.length > 0 and not @standardPrompt.test(@_sanitizeResponse())
#continue loading the buffer and set/reset a timeout
@.emit 'commandProcessing' , @command, @_buffer, @sshObj, @_stream
clearTimeout @idleTimer if @idleTimer
@idleTimer = setTimeout( =>
@.emit 'commandTimeout', @.command, @._buffer, @._stream, @._connection
, @idleTime)
else if @command.length < 1 and not @standardPrompt.test(@_buffer)
@.emit 'commandProcessing' , @command, @_buffer, @sshObj, @_stream
#Set a timer to fire when no more data events are received
#and then process the buffer based on command and prompt combinations
clearTimeout @dataReceivedTimer if @dataReceivedTimer
@dataReceivedTimer = setTimeout( =>
#clear the command and SSH timeout timer
clearTimeout @idleTimer if @idleTimer
#remove test coloring from responses like [32m[31m
unless @.sshObj.disableColorFilter
@emit 'msg', "#{@sshObj.server.host}: text formatting filter: "+@sshObj.textColorFilter+", filtered: "+@textColorFilter.test(@_buffer) if @sshObj.verbose and @sshObj.debug
@_buffer = @_buffer.replace(@textColorFilter, "")
#remove non-standard ascii from terminal responses
unless @.sshObj.disableASCIIFilter
@emit 'msg', "#{@sshObj.server.host}: Non-standard ASCII filtered: "+@asciiFilter.test(@_buffer) if @sshObj.verbose and @sshObj.debug
@_buffer = @_buffer.replace(@asciiFilter, "")
switch (true)
#check if sudo password is needed
when @command.length > 0 and @command.indexOf("sudo ") isnt -1
@emit 'msg', "#{@sshObj.server.host}: Sudo command data" if @sshObj.debug
@_processPasswordPrompt()
#check if ssh authentication needs to be handled
when @command.length > 0 and @command.indexOf("ssh ") isnt -1
@emit 'msg', "#{@sshObj.server.host}: SSH command data" if @sshObj.debug
@_processSSHPrompt()
#check for standard prompt from a command
when @command.length > 0 and @standardPrompt.test(@_sanitizeResponse())
@emit 'msg', "#{@sshObj.server.host}: Normal prompt detected" if @sshObj.debug
@sshObj.pwSent = false #reset sudo prompt checkable
@_commandComplete()
#check for no command but first prompt detected
when @command.length < 1 and @standardPrompt.test(@_buffer)
@emit 'msg', "#{@sshObj.server.host}: First prompt detected" if @sshObj.debug
@sshObj.sessionText += @_buffer if @sshObj.showBanner
@_nextCommand()
else
@emit 'msg', "Data processing: data received timeout" if @sshObj.debug
@idleTimer = setTimeout( =>
@.emit 'commandTimeout', @.command, @._buffer, @._stream, @._connection
, @idleTime)
, @dataIdleTime)
_sanitizeResponse: =>
return @_buffer.replace(@command.substr(0, @_buffer.length), "")
_processPasswordPrompt: =>
#First test for password prompt
response = @_sanitizeResponse().trim()
passwordPrompt = @passwordPromt.test(response)
passphrase = @passphrasePromt.test(response)
standardPrompt = @standardPrompt.test(response)
@.emit 'msg', "#{@sshObj.server.host}: Password previously sent: #{@sshObj.pwSent}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Password previously sent: #{@sshObj.pwSent}" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Response: #{response}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Sudo Password Prompt: #{passwordPrompt}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Sudo Password: #{@sshObj.server.password}" if @sshObj.verbose
#normal prompt so continue with next command
if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Standard prompt detected" if @sshObj.debug
@_commandComplete()
@sshObj.pwSent = true
#Password prompt detection
else unless @sshObj.pwSent
if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Buffer: #{response}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Send password " if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Sent password: #{@sshObj.server.password}" if @sshObj.verbose
#send password
@sshObj.pwSent = true
@_runCommand("#{@sshObj.server.password}")
else
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: not detected first test" if @sshObj.debug
#password sent so either check for failure or run next command
else if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: Sudo password faied: response: #{response}" if @sshObj.verbose
@.emit 'error', "#{@sshObj.server.host}: Sudo password was incorrect for #{@sshObj.server.userName}", "Sudo authentication" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Failed password prompt: Password: [#{@sshObj.server.password}]" if @sshObj.debug
#add buffer to sessionText so the sudo response can be seen
@sshObj.sessionText += "#{@_buffer}"
@_buffer = ""
#@sshObj.commands = []
@command = ""
@_stream.write '\x03'
_processSSHPrompt: =>
#not authenticated yet so detect prompts
response = @_sanitizeResponse().trim()
clearTimeout @idleTimer if @idleTimer
passwordPrompt = @passwordPromt.test(response) and not @sshObj.server.hasOwnProperty("passPhrase")
passphrasePrompt = @passphrasePromt.test(response) and @sshObj.server.hasOwnProperty("passPhrase")
standardPrompt = @standardPrompt.test(response)
@.emit 'msg', "#{@sshObj.server.host}: SSH: Password previously sent: #{@sshObj.sshAuth}" if @sshObj.verbose
unless @sshObj.sshAuth
@.emit 'msg', "#{@sshObj.server.host}: First SSH prompt detection" if @sshObj.debug
#provide password
if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH send password" if @sshObj.debug
@sshObj.sshAuth = true
@_buffer = ""
@_runCommand("#{@sshObj.server.password}")
#provide passphrase
else if passphrasePrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH send passphrase" if @sshObj.debug
@sshObj.sshAuth = true
@_buffer = ""
@_runCommand("#{@sshObj.server.passPhrase}")
#normal prompt so continue with next command
else if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH: standard prompt: connection failed" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: SSH connection failed"
@.emit 'msg', "#{@sshObj.server.host}: SSH failed response: #{response}"
@sshObj.sessionText += "#{@sshObj.server.host}: SSH failed: response: #{response}"
@_runExit()
else
@.emit 'msg', "#{@sshObj.server.host}: SSH post authentication prompt detection" if @sshObj.debug
#normal prompt after authentication, start running commands.
if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH complete: normal prompt" if @sshObj.debug
@sshObj.exitCommands.push "exit"
@.emit 'msg', "#{@sshObj.connectedMessage}"
@.emit 'msg', "#{@sshObj.readyMessage}"
@_nextCommand()
#Password or passphase detected a second time after authentication indicating failure.
else if (passwordPrompt or passphrasePrompt)
@.emit 'msg', "#{@sshObj.server.host}: SSH authentication failed"
@.emit 'msg', "#{@sshObj.server.host}: SSH auth failed" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: SSH: failed response: #{response}" if @sshObj.verbose
@sshObj.sshAuth = false
using = switch
when passwordPrompt then "password:<PASSWORD> #{@sshObj<PASSWORD>.server.password}"
when passphrasePrompt then "passphrase: #{@sshObj.server.passPhrase}"
@.emit 'error', "#{@sshObj.server.host}: SSH authentication failed for #{@sshObj.server.userName}@#{@sshObj.server.host}", "Nested host authentication"
@.emit 'msg', "#{@sshObj.server.host}: SSH auth failed: Using " + using if @sshObj.debug
#no connection so drop back to first host settings if there was one
#@sshObj.sessionText += "#{@_buffer}"
@.emit 'msg', "#{@sshObj.server.host}: SSH resonse: #{response}" if @sshObj.verbose and @sshObj.debug
if @_connections.length > 0
return @_previousHost()
@_runExit()
_processNotifications: =>
#check for notifications in commands
if @command
#this is a message for the sessionText like an echo command in bash
if (sessionNote = @command.match(/^`(.*)`$/))
@.emit 'msg', "#{@sshObj.server.host}: Notifications: sessionText output" if @sshObj.debug
if @_connections.length > 0
@sshObj.sessionText += "#{@sshObj.server.host}: Note: #{sessionNote[1]}#{@sshObj.enter}"
else
@sshObj.sessionText += "Note: #{sessionNote[1]}#{@sshObj.enter}"
@.emit 'msg', sessionNote[1] if @sshObj.verbose
@_nextCommand()
#this is a message to output in process
else if (msgNote = @command.match(/^msg:(.*)$/))
@.emit 'msg', "#{@sshObj.server.host}: Notifications: msg to output" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Note: #{msgNote[1]}"
@_nextCommand()
else
@.emit 'msg', "#{@sshObj.server.host}: Notifications: Normal Command to run" if @sshObj.debug
@_checkCommand()
_commandComplete: =>
response = @_buffer.trim() #replace(@command, "")
#check sudo su has been authenticated and add an extra exit command
if @command.indexOf("sudo su") isnt -1
@.emit 'msg', "#{@sshObj.server.host}: Sudo su adding exit." if @sshObj.debug
@sshObj.exitCommands.push "exit"
if @command isnt "" and @command isnt "exit" and @command.indexOf("ssh ") is -1
@.emit 'msg', "#{@sshObj.server.host}: Command complete:\nCommand:\n #{@command}\nResponse: #{response}" if @sshObj.verbose
#Not running an exit command or first prompt detection after connection
#load the full buffer into sessionText and raise a commandComplete event
@sshObj.sessionText += response
@.emit 'msg', "#{@sshObj.server.host}: Raising commandComplete event" if @sshObj.debug
@.emit 'commandComplete', @command, @_buffer, @sshObj
if @command.indexOf("exit") != -1
@_runExit()
else
@_nextCommand()
_nextCommand: =>
@_buffer = ""
#process the next command if there are any
if @sshObj.commands.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Host.commands: #{@sshObj.commands}" if @sshObj.verbose
@command = @sshObj.commands.shift()
@.emit 'msg', "#{@sshObj.server.host}: Next command from host.commands: #{@command}" if @sshObj.verbose
@_processNotifications()
else
@.emit 'msg', "#{@sshObj.server.host}: No commands so exit" if @sshObj.debug
#no more commands so exit
@_runExit()
_checkCommand: =>
#if there is still a command to run then run it or exit
if @command != ""
@_runCommand(@command)
else
#no more commands so exit
@.emit 'msg', "#{@sshObj.server.host}: No command so exit" if @sshObj.debug
@_runExit()
_runCommand: (command) =>
@.emit 'msg', "#{@sshObj.server.host}: sending: #{command}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: run command" if @sshObj.debug
@_stream.write "#{command}#{@sshObj.enter}"
_previousHost: =>
@.emit 'msg', "#{@sshObj.server.host}: Load previous host config" if @sshObj.debug
@.emit 'end', "#{@sshObj.server.host}: \n#{@sshObj.sessionText}", @sshObj
@.emit 'msg', "#{@sshObj.server.host}: Previous hosts: #{@_connections.length}" if @sshObj.debug
if @_connections.length > 0
@sshObj = @_connections.pop()
@.emit 'msg', "#{@sshObj.server.host}: Reload previous host" if @sshObj.debug
@_loadDefaults(@_runExit)
else
@_runExit()
_nextHost: =>
nextHost = @sshObj.hosts.shift()
@.emit 'msg', "#{@sshObj.server.host}: SSH to #{nextHost.server.host}" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Clearing previous event handlers" if @sshObj.debug
@_connections.push(@sshObj)
@sshObj = nextHost
@_initiate(@_sshConnect)
_nextPrimaryHost: ( callback )=>
if typeIsArray(@hosts) and @hosts.length > 0
if @sshObj.server
@.emit 'msg', "#{@sshObj.server.host}: Current primary host" if @sshObj.debug
@sshObj = @hosts.shift()
@_primaryhostSessionText = "#{@sshObj.server.host}: "
@.emit 'msg', "#{@sshObj.server.host}: Next primary host" if @sshObj.debug
@_initiate(callback)
else
@.emit 'msg', "#{@sshObj.server.host}: No more primary hosts" if @sshObj.debug
@_runExit
_sshConnect: =>
#add ssh commandline options from host.server.ssh
sshFlags = "-x"
sshOptions = ""
if @sshObj.server.ssh
sshFlags += @sshObj.server.ssh.forceProtocolVersion if @sshObj.server.ssh.forceProtocolVersion
sshFlags += @sshObj.server.ssh.forceAddressType if @sshObj.server.ssh.forceAddressType
sshFlags += "T" if @sshObj.server.ssh.disablePseudoTTY
sshFlags += "t" if @sshObj.server.ssh.forcePseudoTTY
sshFlags += "v" if @sshObj.server.ssh.verbose
sshOptions += " -c " + @sshObj.server.ssh.cipherSpec if @sshObj.server.ssh.cipherSpec
sshOptions += " -e " + @sshObj.server.ssh.escape if @sshObj.server.ssh.escape
sshOptions += " -E " + @sshObj.server.ssh.logFile if @sshObj.server.ssh.logFile
sshOptions += " -F " + @sshObj.server.ssh.configFile if @sshObj.server.ssh.configFile
sshOptions += " -i " + @sshObj.server.ssh.identityFile if @sshObj.server.ssh.identityFile
sshOptions += " -l " + @sshObj.server.ssh.loginName if @sshObj.server.ssh.loginName
sshOptions += " -m " + @sshObj.server.ssh.macSpec if @sshObj.server.ssh.macSpec
sshOptions += ' -o "#{option}={#value}"' for option,value of @sshObj.server.ssh.Options
sshOptions += ' -o "StrictHostKeyChecking=no"'
sshOptions += " -p #{@sshObj.server.port}"
@sshObj.sshAuth = false
@command = "ssh #{sshFlags} #{sshOptions} #{@sshObj.server.userName}@#{@sshObj.server.host}"
@.emit 'msg', "#{@sshObj.server.host}: SSH command: connect" if @sshObj.debug
@_runCommand(@command)
_runExit: =>
@.emit 'msg', "#{@sshObj.server.host}: Process an exit" if @sshObj.debug
#run the exit commands loaded by ssh and sudo su commands
if @sshObj.exitCommands and @sshObj.exitCommands.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Queued exit commands: #{@sshObj.exitCommands.length}" if @sshObj.debug
@command = @sshObj.exitCommands.pop()
@_connections[0].sessionText += "\n#{@sshObj.server.host}: #{@sshObj.sessionText}"
@_runCommand(@command)
#more hosts to connect to so process the next one
else if @sshObj.hosts and @sshObj.hosts.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Next host from this host" if @sshObj.debug
@_nextHost()
#Leaving last host so load previous host
else if @_connections and @_connections.length > 0
@.emit 'msg', "#{@sshObj.server.host}: load previous host" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: #{@sshObj.closedMessage}"
@_previousHost()
#else if typeIsArray(@hosts) and @hosts.length > 0
#@connection.end()
#Nothing more to do so end the stream with last exit
else
@.emit 'msg', "#{@sshObj.server.host}: Exit command: Stream: close" if @sshObj.debug
#@.command = "stream.end()"
@_stream.close() #"exit#{@sshObj.enter}"
_removeEvents: =>
@.emit 'msg', "#{@sshObj.server.host}: Clearing host event handlers" if @sshObj.debug
@.removeAllListeners 'keyboard-interactive'
@.removeAllListeners "error"
@.removeListener "data", @sshObj.onData if typeof @sshObj.onData == 'function'
@.removeListener "stderrData", @sshObj.onStderrData if typeof @sshObj.onStderrData == 'function'
@.removeAllListeners 'end'
@.removeAllListeners 'commandProcessing'
@.removeAllListeners 'commandComplete'
@.removeAllListeners 'commandTimeout'
@.removeAllListeners 'msg'
clearTimeout @idleTimer if @idleTimer
clearTimeout @dataReceivedTimer if @dataReceivedTimer
constructor: (hosts) ->
if typeIsArray(hosts)
@hosts = hosts
else
@hosts = [hosts]
@ssh2Client = require('ssh2')
@.on "newPrimmaryHost", @_nextPrimaryHost
@.on "data", (data) =>
#@.emit 'msg', "#{@sshObj.server.host}: data event: #{data}" if @sshObj.verbose
@_onData( data )
@.on "stderrData", (data) =>
console.error data
@_allSessions = ""
_initiate: (callback)=>
@_removeEvents()
if typeof @sshObj.msg == 'function'
@.on "msg", @sshObj.msg.send
else
@.on "msg", ( message ) =>
console.log message
@_loadDefaults()
@.emit 'msg', "#{@sshObj.server.host}: initiate" if @sshObj.debug
#event handlers
@.on "keyboard-interactive", ( name, instructions, instructionsLang, prompts, finish ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.keyboard-interactive" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Keyboard-interactive: finish([response, array]) not called in class event handler." if @sshObj.debug
if @sshObj.verbose
@.emit 'msg', "name: " + name
@.emit 'msg', "instructions: " + instructions
str = JSON.stringify(prompts, null, 4)
@.emit 'msg', "Prompts object: " + str
@.on "error", (err, type, close = false, callback) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.error" if @sshObj.debug
if ( err instanceof Error )
@.emit 'msg', "Error: " + err.message + ", Level: " + err.level
else
@.emit 'msg', "#{type} error: " + err
callback(err, type) if typeof callback == 'function'
@connection.end() if close
@.on "end", ( sessionText, sshObj ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.end" if @sshObj.debug
if typeof callback == 'function'
callback()
_loadDefaults: (callback) =>
@.emit 'msg', "#{@sshObj.server.host}: Load Defaults" if @sshObj.debug
@command = ""
@_buffer = ""
@sshObj.connectedMessage = "Connected" unless @sshObj.connectedMessage
@sshObj.readyMessage = "Ready" unless @sshObj.readyMessage
@sshObj.closedMessage = "Closed" unless @sshObj.closedMessage
@sshObj.showBanner = false unless @sshObj.showBanner
@sshObj.verbose = false unless @sshObj.verbose
@sshObj.debug = false unless @sshObj.debug
@sshObj.hosts = [] unless @sshObj.hosts
@sshObj.commands = [] unless @sshObj.commands
@sshObj.standardPrompt = ">$%#" unless @sshObj.standardPrompt
@sshObj.passwordPromt = ":" unless @sshObj.passwordPromt
@sshObj.passphrasePromt = ":" unless @sshObj.passphrasePromt
@sshObj.passPromptText = "Password" unless @sshObj.passPromptText
@sshObj.enter = "\n" unless @sshObj.enter #windows = "\r\n", Linux = "\n", Mac = "\r"
@sshObj.asciiFilter = "[^\r\n\x20-\x7e]" unless @sshObj.asciiFilter
@sshObj.disableColorFilter = false unless @sshObj.disableColorFilter is true
@sshObj.disableASCIIFilter = false unless @sshObj.disableASCIIFilter is true
@sshObj.textColorFilter = "(\[{1}[0-9;]+m{1})" unless @sshObj.textColorFilter
@sshObj.exitCommands = [] unless @sshObj.exitCommands
@sshObj.pwSent = false
@sshObj.sshAuth = false
@sshObj.server.hashKey = @sshObj.server.hashKey ? ""
@sshObj.sessionText = "" unless @sshObj.sessionText
@sshObj.streamEncoding = @sshObj.streamEncoding ? "utf8"
@sshObj.window = true unless @sshObj.window
@sshObj.pty = true unless @sshObj.pty
@idleTime = @sshObj.idleTimeOut ? 5000
@dataIdleTime = @sshObj.dataIdleTime ? 500
@asciiFilter = new RegExp(@sshObj.asciiFilter,"g") unless @asciiFilter
@textColorFilter = new RegExp(@sshObj.textColorFilter,"g") unless @textColorFilter
@passwordPromt = new RegExp(@sshObj.passPromptText+".*" + @sshObj.passwordPromt + "\\s?$","i") unless @passwordPromt
@passphrasePromt = new RegExp(@sshObj.passPromptText+".*" + @sshObj.passphrasePromt + "\\s?$","i") unless @passphrasePromt
@standardPrompt = new RegExp("[" + @sshObj.standardPrompt + "]\\s?$") unless @standardPrompt
#@_callback = @sshObj.callback if @sshObj.callback
@sshObj.onCommandProcessing = @sshObj.onCommandProcessing ? ( command, response, sshObj, stream ) =>
@sshObj.onCommandComplete = @sshObj.onCommandComplete ? ( command, response, sshObj ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.commandComplete" if @sshObj.debug
@sshObj.onCommandTimeout = @sshObj.onCommandTimeout ? ( command, response, stream, connection ) =>
response = response.replace(@command, "")
@.emit 'msg', "#{@sshObj.server.host}: Class.commandTimeout" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Timeout command: #{command} response: #{response}" if @sshObj.verbose
@_runExit()
@.emit "error", "#{@sshObj.server.host}: Command timed out after #{@.idleTime/1000} seconds", "Timeout", true, (err, type)=>
@sshObj.sessionText += @_buffer
@.on "keyboard-interactive", @sshObj.onKeyboardInteractive if typeof @sshObj.onKeyboardInteractive == 'function'
@.on "error", @sshObj.onError if typeof @sshObj.onError == 'function'
@.on "data", @sshObj.onData if typeof @sshObj.onData == 'function'
@.on "stderrData", @sshObj.onStderrData if typeof @sshObj.onStderrData == 'function'
@.on "commandProcessing", @sshObj.onCommandProcessing
@.on "commandComplete", @sshObj.onCommandComplete
@.on "commandTimeout", @sshObj.onCommandTimeout
@.on "end", @sshObj.onEnd if typeof @sshObj.onEnd == 'function'
@.emit 'msg', "#{@sshObj.server.host}: Host loaded" if @sshObj.verbose
@.emit 'msg', @sshObj if @sshObj.verbose
if typeof callback == 'function'
callback()
connect: (callback)=>
@_callback = callback if typeof callback == 'function'
@.emit "newPrimaryHost", @_nextPrimaryHost(@_connect)
_connect: =>
@connection = new @ssh2Client()
@connection.on "keyboard-interactive", (name, instructions, instructionsLang, prompts, finish) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.keyboard-interactive" if @sshObj.debug
@.emit "keyboard-interactive", name, instructions, instructionsLang, prompts, finish
@connection.on "connect", =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.connect" if @sshObj.debug
@.emit 'msg', @sshObj.connectedMessage
@connection.on "ready", =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.ready" if @sshObj.debug
@.emit 'msg', @sshObj.readyMessage
#open a shell
@connection.shell @sshObj.window, { pty: @sshObj.pty }, (err, @_stream) =>
if err instanceof Error
@.emit 'error', err, "Shell", true
return
@.emit 'msg', "#{@sshObj.server.host}: Connection.shell" if @sshObj.debug
@_stream.setEncoding(@sshObj.streamEncoding);
@_stream.on "error", (err) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.error" if @sshObj.debug
@.emit 'error', err, "Stream"
@_stream.stderr.on 'data', (data) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.stderr.data" if @sshObj.debug
@.emit 'stderrData', data
@_stream.on "data", (data)=>
try
@.emit 'data', data
catch e
err = new Error("#{e} #{e.stack}")
err.level = "Data handling"
@.emit 'error', err, "Stream.read", true
@_stream.on "finish", =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.finish" if @sshObj.debug
@_primaryhostSessionText += @sshObj.sessionText+"\n"
@_allSessions += @_primaryhostSessionText
if typeIsArray(@hosts) and @hosts.length == 0
@.emit 'end', @_allSessions, @sshObj
@_removeEvents()
@_stream.on "close", (code, signal) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.close" if @sshObj.debug
@connection.end()
@connection.on "error", (err) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.error" if @sshObj.debug
@.emit "error", err, "Connection"
@connection.on "close", (had_error) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.close" if @sshObj.debug
if had_error
@.emit "error", had_error, "Connection close"
else
@.emit 'msg', @sshObj.closedMessage
if typeIsArray(@hosts) and @hosts.length == 0
if typeof @_callback == 'function'
@_callback @_allSessions
else
@.emit "newPrimaryHost", @_nextPrimaryHost(@_connect)
if @sshObj.server and @sshObj.commands
try
@connection.connect
host: @sshObj.server.host
port: @sshObj.server.port
forceIPv4: @sshObj.server.forceIPv4
forceIPv6: @sshObj.server.forceIPv6
hostHash: @sshObj.server.hashMethod
hostVerifier: @sshObj.server.hostVerifier
username: @sshObj.server.userName
password: <PASSWORD>Obj.server.password
agent: @sshObj.server.agent
agentForward: @sshObj.server.agentForward
privateKey: @sshObj.server.privateKey
passphrase: <PASSWORD>Obj<PASSWORD>.server.passPhrase
localHostname: @sshObj.server.localHostname
localUsername: @sshObj.server.localUsername
tryKeyboard: @sshObj.server.tryKeyboard
keepaliveInterval:@sshObj.server.keepaliveInterval
keepaliveCountMax:@sshObj.server.keepaliveCountMax
readyTimeout: @sshObj.server.readyTimeout
sock: @sshObj.server.sock
strictVendor: @sshObj.server.strictVendor
algorithms: @sshObj.server.algorithms
compress: @sshObj.server.compress
debug: @sshObj.server.debug
catch e
@.emit 'error', "#{e} #{e.stack}", "Connection.connect", true
else
@.emit 'error', "Missing connection parameters", "Parameters", false, ( err, type, close ) ->
@.emit 'msg', @sshObj.server
@.emit 'msg', @sshObj.commands
return @_stream
module.exports = SSH2Shell
| true | #================================
# SSH2Shel
#================================
# Description
# SSH2 wrapper for creating a SSH shell connection and running multiple commands sequentially.
typeIsArray = Array.isArray || ( value ) -> return {}.toString.call( value ) is '[object Array]'
Stream = require('stream');
class SSH2Shell extends Stream
sshObj: {}
command: ""
hosts: []
_primaryhostSessionText: ""
_allSessions: ""
_connections: []
_stream: {}
_buffer: ""
idleTime: 5000
asciiFilter: ""
textColorFilter: ""
passwordPromt: ""
passphrasePromt: ""
standardPrompt: ""
_callback: =>
onCommandProcessing:=>
onCommandComplete: =>
onCommandTimeout: =>
onEnd: =>
_onData: ( data )=>
#add host response data to buffer
@_buffer += data
if @command.length > 0 and not @standardPrompt.test(@_sanitizeResponse())
#continue loading the buffer and set/reset a timeout
@.emit 'commandProcessing' , @command, @_buffer, @sshObj, @_stream
clearTimeout @idleTimer if @idleTimer
@idleTimer = setTimeout( =>
@.emit 'commandTimeout', @.command, @._buffer, @._stream, @._connection
, @idleTime)
else if @command.length < 1 and not @standardPrompt.test(@_buffer)
@.emit 'commandProcessing' , @command, @_buffer, @sshObj, @_stream
#Set a timer to fire when no more data events are received
#and then process the buffer based on command and prompt combinations
clearTimeout @dataReceivedTimer if @dataReceivedTimer
@dataReceivedTimer = setTimeout( =>
#clear the command and SSH timeout timer
clearTimeout @idleTimer if @idleTimer
#remove test coloring from responses like [32m[31m
unless @.sshObj.disableColorFilter
@emit 'msg', "#{@sshObj.server.host}: text formatting filter: "+@sshObj.textColorFilter+", filtered: "+@textColorFilter.test(@_buffer) if @sshObj.verbose and @sshObj.debug
@_buffer = @_buffer.replace(@textColorFilter, "")
#remove non-standard ascii from terminal responses
unless @.sshObj.disableASCIIFilter
@emit 'msg', "#{@sshObj.server.host}: Non-standard ASCII filtered: "+@asciiFilter.test(@_buffer) if @sshObj.verbose and @sshObj.debug
@_buffer = @_buffer.replace(@asciiFilter, "")
switch (true)
#check if sudo password is needed
when @command.length > 0 and @command.indexOf("sudo ") isnt -1
@emit 'msg', "#{@sshObj.server.host}: Sudo command data" if @sshObj.debug
@_processPasswordPrompt()
#check if ssh authentication needs to be handled
when @command.length > 0 and @command.indexOf("ssh ") isnt -1
@emit 'msg', "#{@sshObj.server.host}: SSH command data" if @sshObj.debug
@_processSSHPrompt()
#check for standard prompt from a command
when @command.length > 0 and @standardPrompt.test(@_sanitizeResponse())
@emit 'msg', "#{@sshObj.server.host}: Normal prompt detected" if @sshObj.debug
@sshObj.pwSent = false #reset sudo prompt checkable
@_commandComplete()
#check for no command but first prompt detected
when @command.length < 1 and @standardPrompt.test(@_buffer)
@emit 'msg', "#{@sshObj.server.host}: First prompt detected" if @sshObj.debug
@sshObj.sessionText += @_buffer if @sshObj.showBanner
@_nextCommand()
else
@emit 'msg', "Data processing: data received timeout" if @sshObj.debug
@idleTimer = setTimeout( =>
@.emit 'commandTimeout', @.command, @._buffer, @._stream, @._connection
, @idleTime)
, @dataIdleTime)
_sanitizeResponse: =>
return @_buffer.replace(@command.substr(0, @_buffer.length), "")
_processPasswordPrompt: =>
#First test for password prompt
response = @_sanitizeResponse().trim()
passwordPrompt = @passwordPromt.test(response)
passphrase = @passphrasePromt.test(response)
standardPrompt = @standardPrompt.test(response)
@.emit 'msg', "#{@sshObj.server.host}: Password previously sent: #{@sshObj.pwSent}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Password previously sent: #{@sshObj.pwSent}" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Response: #{response}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Sudo Password Prompt: #{passwordPrompt}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Sudo Password: #{@sshObj.server.password}" if @sshObj.verbose
#normal prompt so continue with next command
if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Standard prompt detected" if @sshObj.debug
@_commandComplete()
@sshObj.pwSent = true
#Password prompt detection
else unless @sshObj.pwSent
if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Buffer: #{response}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: Send password " if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Sent password: #{@sshObj.server.password}" if @sshObj.verbose
#send password
@sshObj.pwSent = true
@_runCommand("#{@sshObj.server.password}")
else
@.emit 'msg', "#{@sshObj.server.host}: Password prompt: not detected first test" if @sshObj.debug
#password sent so either check for failure or run next command
else if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: Sudo password faied: response: #{response}" if @sshObj.verbose
@.emit 'error', "#{@sshObj.server.host}: Sudo password was incorrect for #{@sshObj.server.userName}", "Sudo authentication" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Failed password prompt: Password: [#{@sshObj.server.password}]" if @sshObj.debug
#add buffer to sessionText so the sudo response can be seen
@sshObj.sessionText += "#{@_buffer}"
@_buffer = ""
#@sshObj.commands = []
@command = ""
@_stream.write '\x03'
_processSSHPrompt: =>
#not authenticated yet so detect prompts
response = @_sanitizeResponse().trim()
clearTimeout @idleTimer if @idleTimer
passwordPrompt = @passwordPromt.test(response) and not @sshObj.server.hasOwnProperty("passPhrase")
passphrasePrompt = @passphrasePromt.test(response) and @sshObj.server.hasOwnProperty("passPhrase")
standardPrompt = @standardPrompt.test(response)
@.emit 'msg', "#{@sshObj.server.host}: SSH: Password previously sent: #{@sshObj.sshAuth}" if @sshObj.verbose
unless @sshObj.sshAuth
@.emit 'msg', "#{@sshObj.server.host}: First SSH prompt detection" if @sshObj.debug
#provide password
if passwordPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH send password" if @sshObj.debug
@sshObj.sshAuth = true
@_buffer = ""
@_runCommand("#{@sshObj.server.password}")
#provide passphrase
else if passphrasePrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH send passphrase" if @sshObj.debug
@sshObj.sshAuth = true
@_buffer = ""
@_runCommand("#{@sshObj.server.passPhrase}")
#normal prompt so continue with next command
else if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH: standard prompt: connection failed" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: SSH connection failed"
@.emit 'msg', "#{@sshObj.server.host}: SSH failed response: #{response}"
@sshObj.sessionText += "#{@sshObj.server.host}: SSH failed: response: #{response}"
@_runExit()
else
@.emit 'msg', "#{@sshObj.server.host}: SSH post authentication prompt detection" if @sshObj.debug
#normal prompt after authentication, start running commands.
if standardPrompt
@.emit 'msg', "#{@sshObj.server.host}: SSH complete: normal prompt" if @sshObj.debug
@sshObj.exitCommands.push "exit"
@.emit 'msg', "#{@sshObj.connectedMessage}"
@.emit 'msg', "#{@sshObj.readyMessage}"
@_nextCommand()
#Password or passphase detected a second time after authentication indicating failure.
else if (passwordPrompt or passphrasePrompt)
@.emit 'msg', "#{@sshObj.server.host}: SSH authentication failed"
@.emit 'msg', "#{@sshObj.server.host}: SSH auth failed" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: SSH: failed response: #{response}" if @sshObj.verbose
@sshObj.sshAuth = false
using = switch
when passwordPrompt then "password:PI:PASSWORD:<PASSWORD>END_PI #{@sshObjPI:PASSWORD:<PASSWORD>END_PI.server.password}"
when passphrasePrompt then "passphrase: #{@sshObj.server.passPhrase}"
@.emit 'error', "#{@sshObj.server.host}: SSH authentication failed for #{@sshObj.server.userName}@#{@sshObj.server.host}", "Nested host authentication"
@.emit 'msg', "#{@sshObj.server.host}: SSH auth failed: Using " + using if @sshObj.debug
#no connection so drop back to first host settings if there was one
#@sshObj.sessionText += "#{@_buffer}"
@.emit 'msg', "#{@sshObj.server.host}: SSH resonse: #{response}" if @sshObj.verbose and @sshObj.debug
if @_connections.length > 0
return @_previousHost()
@_runExit()
_processNotifications: =>
#check for notifications in commands
if @command
#this is a message for the sessionText like an echo command in bash
if (sessionNote = @command.match(/^`(.*)`$/))
@.emit 'msg', "#{@sshObj.server.host}: Notifications: sessionText output" if @sshObj.debug
if @_connections.length > 0
@sshObj.sessionText += "#{@sshObj.server.host}: Note: #{sessionNote[1]}#{@sshObj.enter}"
else
@sshObj.sessionText += "Note: #{sessionNote[1]}#{@sshObj.enter}"
@.emit 'msg', sessionNote[1] if @sshObj.verbose
@_nextCommand()
#this is a message to output in process
else if (msgNote = @command.match(/^msg:(.*)$/))
@.emit 'msg', "#{@sshObj.server.host}: Notifications: msg to output" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Note: #{msgNote[1]}"
@_nextCommand()
else
@.emit 'msg', "#{@sshObj.server.host}: Notifications: Normal Command to run" if @sshObj.debug
@_checkCommand()
_commandComplete: =>
response = @_buffer.trim() #replace(@command, "")
#check sudo su has been authenticated and add an extra exit command
if @command.indexOf("sudo su") isnt -1
@.emit 'msg', "#{@sshObj.server.host}: Sudo su adding exit." if @sshObj.debug
@sshObj.exitCommands.push "exit"
if @command isnt "" and @command isnt "exit" and @command.indexOf("ssh ") is -1
@.emit 'msg', "#{@sshObj.server.host}: Command complete:\nCommand:\n #{@command}\nResponse: #{response}" if @sshObj.verbose
#Not running an exit command or first prompt detection after connection
#load the full buffer into sessionText and raise a commandComplete event
@sshObj.sessionText += response
@.emit 'msg', "#{@sshObj.server.host}: Raising commandComplete event" if @sshObj.debug
@.emit 'commandComplete', @command, @_buffer, @sshObj
if @command.indexOf("exit") != -1
@_runExit()
else
@_nextCommand()
_nextCommand: =>
@_buffer = ""
#process the next command if there are any
if @sshObj.commands.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Host.commands: #{@sshObj.commands}" if @sshObj.verbose
@command = @sshObj.commands.shift()
@.emit 'msg', "#{@sshObj.server.host}: Next command from host.commands: #{@command}" if @sshObj.verbose
@_processNotifications()
else
@.emit 'msg', "#{@sshObj.server.host}: No commands so exit" if @sshObj.debug
#no more commands so exit
@_runExit()
_checkCommand: =>
#if there is still a command to run then run it or exit
if @command != ""
@_runCommand(@command)
else
#no more commands so exit
@.emit 'msg', "#{@sshObj.server.host}: No command so exit" if @sshObj.debug
@_runExit()
_runCommand: (command) =>
@.emit 'msg', "#{@sshObj.server.host}: sending: #{command}" if @sshObj.verbose
@.emit 'msg', "#{@sshObj.server.host}: run command" if @sshObj.debug
@_stream.write "#{command}#{@sshObj.enter}"
_previousHost: =>
@.emit 'msg', "#{@sshObj.server.host}: Load previous host config" if @sshObj.debug
@.emit 'end', "#{@sshObj.server.host}: \n#{@sshObj.sessionText}", @sshObj
@.emit 'msg', "#{@sshObj.server.host}: Previous hosts: #{@_connections.length}" if @sshObj.debug
if @_connections.length > 0
@sshObj = @_connections.pop()
@.emit 'msg', "#{@sshObj.server.host}: Reload previous host" if @sshObj.debug
@_loadDefaults(@_runExit)
else
@_runExit()
_nextHost: =>
nextHost = @sshObj.hosts.shift()
@.emit 'msg', "#{@sshObj.server.host}: SSH to #{nextHost.server.host}" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Clearing previous event handlers" if @sshObj.debug
@_connections.push(@sshObj)
@sshObj = nextHost
@_initiate(@_sshConnect)
_nextPrimaryHost: ( callback )=>
if typeIsArray(@hosts) and @hosts.length > 0
if @sshObj.server
@.emit 'msg', "#{@sshObj.server.host}: Current primary host" if @sshObj.debug
@sshObj = @hosts.shift()
@_primaryhostSessionText = "#{@sshObj.server.host}: "
@.emit 'msg', "#{@sshObj.server.host}: Next primary host" if @sshObj.debug
@_initiate(callback)
else
@.emit 'msg', "#{@sshObj.server.host}: No more primary hosts" if @sshObj.debug
@_runExit
_sshConnect: =>
#add ssh commandline options from host.server.ssh
sshFlags = "-x"
sshOptions = ""
if @sshObj.server.ssh
sshFlags += @sshObj.server.ssh.forceProtocolVersion if @sshObj.server.ssh.forceProtocolVersion
sshFlags += @sshObj.server.ssh.forceAddressType if @sshObj.server.ssh.forceAddressType
sshFlags += "T" if @sshObj.server.ssh.disablePseudoTTY
sshFlags += "t" if @sshObj.server.ssh.forcePseudoTTY
sshFlags += "v" if @sshObj.server.ssh.verbose
sshOptions += " -c " + @sshObj.server.ssh.cipherSpec if @sshObj.server.ssh.cipherSpec
sshOptions += " -e " + @sshObj.server.ssh.escape if @sshObj.server.ssh.escape
sshOptions += " -E " + @sshObj.server.ssh.logFile if @sshObj.server.ssh.logFile
sshOptions += " -F " + @sshObj.server.ssh.configFile if @sshObj.server.ssh.configFile
sshOptions += " -i " + @sshObj.server.ssh.identityFile if @sshObj.server.ssh.identityFile
sshOptions += " -l " + @sshObj.server.ssh.loginName if @sshObj.server.ssh.loginName
sshOptions += " -m " + @sshObj.server.ssh.macSpec if @sshObj.server.ssh.macSpec
sshOptions += ' -o "#{option}={#value}"' for option,value of @sshObj.server.ssh.Options
sshOptions += ' -o "StrictHostKeyChecking=no"'
sshOptions += " -p #{@sshObj.server.port}"
@sshObj.sshAuth = false
@command = "ssh #{sshFlags} #{sshOptions} #{@sshObj.server.userName}@#{@sshObj.server.host}"
@.emit 'msg', "#{@sshObj.server.host}: SSH command: connect" if @sshObj.debug
@_runCommand(@command)
_runExit: =>
@.emit 'msg', "#{@sshObj.server.host}: Process an exit" if @sshObj.debug
#run the exit commands loaded by ssh and sudo su commands
if @sshObj.exitCommands and @sshObj.exitCommands.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Queued exit commands: #{@sshObj.exitCommands.length}" if @sshObj.debug
@command = @sshObj.exitCommands.pop()
@_connections[0].sessionText += "\n#{@sshObj.server.host}: #{@sshObj.sessionText}"
@_runCommand(@command)
#more hosts to connect to so process the next one
else if @sshObj.hosts and @sshObj.hosts.length > 0
@.emit 'msg', "#{@sshObj.server.host}: Next host from this host" if @sshObj.debug
@_nextHost()
#Leaving last host so load previous host
else if @_connections and @_connections.length > 0
@.emit 'msg', "#{@sshObj.server.host}: load previous host" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: #{@sshObj.closedMessage}"
@_previousHost()
#else if typeIsArray(@hosts) and @hosts.length > 0
#@connection.end()
#Nothing more to do so end the stream with last exit
else
@.emit 'msg', "#{@sshObj.server.host}: Exit command: Stream: close" if @sshObj.debug
#@.command = "stream.end()"
@_stream.close() #"exit#{@sshObj.enter}"
_removeEvents: =>
@.emit 'msg', "#{@sshObj.server.host}: Clearing host event handlers" if @sshObj.debug
@.removeAllListeners 'keyboard-interactive'
@.removeAllListeners "error"
@.removeListener "data", @sshObj.onData if typeof @sshObj.onData == 'function'
@.removeListener "stderrData", @sshObj.onStderrData if typeof @sshObj.onStderrData == 'function'
@.removeAllListeners 'end'
@.removeAllListeners 'commandProcessing'
@.removeAllListeners 'commandComplete'
@.removeAllListeners 'commandTimeout'
@.removeAllListeners 'msg'
clearTimeout @idleTimer if @idleTimer
clearTimeout @dataReceivedTimer if @dataReceivedTimer
constructor: (hosts) ->
if typeIsArray(hosts)
@hosts = hosts
else
@hosts = [hosts]
@ssh2Client = require('ssh2')
@.on "newPrimmaryHost", @_nextPrimaryHost
@.on "data", (data) =>
#@.emit 'msg', "#{@sshObj.server.host}: data event: #{data}" if @sshObj.verbose
@_onData( data )
@.on "stderrData", (data) =>
console.error data
@_allSessions = ""
_initiate: (callback)=>
@_removeEvents()
if typeof @sshObj.msg == 'function'
@.on "msg", @sshObj.msg.send
else
@.on "msg", ( message ) =>
console.log message
@_loadDefaults()
@.emit 'msg', "#{@sshObj.server.host}: initiate" if @sshObj.debug
#event handlers
@.on "keyboard-interactive", ( name, instructions, instructionsLang, prompts, finish ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.keyboard-interactive" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Keyboard-interactive: finish([response, array]) not called in class event handler." if @sshObj.debug
if @sshObj.verbose
@.emit 'msg', "name: " + name
@.emit 'msg', "instructions: " + instructions
str = JSON.stringify(prompts, null, 4)
@.emit 'msg', "Prompts object: " + str
@.on "error", (err, type, close = false, callback) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.error" if @sshObj.debug
if ( err instanceof Error )
@.emit 'msg', "Error: " + err.message + ", Level: " + err.level
else
@.emit 'msg', "#{type} error: " + err
callback(err, type) if typeof callback == 'function'
@connection.end() if close
@.on "end", ( sessionText, sshObj ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.end" if @sshObj.debug
if typeof callback == 'function'
callback()
_loadDefaults: (callback) =>
@.emit 'msg', "#{@sshObj.server.host}: Load Defaults" if @sshObj.debug
@command = ""
@_buffer = ""
@sshObj.connectedMessage = "Connected" unless @sshObj.connectedMessage
@sshObj.readyMessage = "Ready" unless @sshObj.readyMessage
@sshObj.closedMessage = "Closed" unless @sshObj.closedMessage
@sshObj.showBanner = false unless @sshObj.showBanner
@sshObj.verbose = false unless @sshObj.verbose
@sshObj.debug = false unless @sshObj.debug
@sshObj.hosts = [] unless @sshObj.hosts
@sshObj.commands = [] unless @sshObj.commands
@sshObj.standardPrompt = ">$%#" unless @sshObj.standardPrompt
@sshObj.passwordPromt = ":" unless @sshObj.passwordPromt
@sshObj.passphrasePromt = ":" unless @sshObj.passphrasePromt
@sshObj.passPromptText = "Password" unless @sshObj.passPromptText
@sshObj.enter = "\n" unless @sshObj.enter #windows = "\r\n", Linux = "\n", Mac = "\r"
@sshObj.asciiFilter = "[^\r\n\x20-\x7e]" unless @sshObj.asciiFilter
@sshObj.disableColorFilter = false unless @sshObj.disableColorFilter is true
@sshObj.disableASCIIFilter = false unless @sshObj.disableASCIIFilter is true
@sshObj.textColorFilter = "(\[{1}[0-9;]+m{1})" unless @sshObj.textColorFilter
@sshObj.exitCommands = [] unless @sshObj.exitCommands
@sshObj.pwSent = false
@sshObj.sshAuth = false
@sshObj.server.hashKey = @sshObj.server.hashKey ? ""
@sshObj.sessionText = "" unless @sshObj.sessionText
@sshObj.streamEncoding = @sshObj.streamEncoding ? "utf8"
@sshObj.window = true unless @sshObj.window
@sshObj.pty = true unless @sshObj.pty
@idleTime = @sshObj.idleTimeOut ? 5000
@dataIdleTime = @sshObj.dataIdleTime ? 500
@asciiFilter = new RegExp(@sshObj.asciiFilter,"g") unless @asciiFilter
@textColorFilter = new RegExp(@sshObj.textColorFilter,"g") unless @textColorFilter
@passwordPromt = new RegExp(@sshObj.passPromptText+".*" + @sshObj.passwordPromt + "\\s?$","i") unless @passwordPromt
@passphrasePromt = new RegExp(@sshObj.passPromptText+".*" + @sshObj.passphrasePromt + "\\s?$","i") unless @passphrasePromt
@standardPrompt = new RegExp("[" + @sshObj.standardPrompt + "]\\s?$") unless @standardPrompt
#@_callback = @sshObj.callback if @sshObj.callback
@sshObj.onCommandProcessing = @sshObj.onCommandProcessing ? ( command, response, sshObj, stream ) =>
@sshObj.onCommandComplete = @sshObj.onCommandComplete ? ( command, response, sshObj ) =>
@.emit 'msg', "#{@sshObj.server.host}: Class.commandComplete" if @sshObj.debug
@sshObj.onCommandTimeout = @sshObj.onCommandTimeout ? ( command, response, stream, connection ) =>
response = response.replace(@command, "")
@.emit 'msg', "#{@sshObj.server.host}: Class.commandTimeout" if @sshObj.debug
@.emit 'msg', "#{@sshObj.server.host}: Timeout command: #{command} response: #{response}" if @sshObj.verbose
@_runExit()
@.emit "error", "#{@sshObj.server.host}: Command timed out after #{@.idleTime/1000} seconds", "Timeout", true, (err, type)=>
@sshObj.sessionText += @_buffer
@.on "keyboard-interactive", @sshObj.onKeyboardInteractive if typeof @sshObj.onKeyboardInteractive == 'function'
@.on "error", @sshObj.onError if typeof @sshObj.onError == 'function'
@.on "data", @sshObj.onData if typeof @sshObj.onData == 'function'
@.on "stderrData", @sshObj.onStderrData if typeof @sshObj.onStderrData == 'function'
@.on "commandProcessing", @sshObj.onCommandProcessing
@.on "commandComplete", @sshObj.onCommandComplete
@.on "commandTimeout", @sshObj.onCommandTimeout
@.on "end", @sshObj.onEnd if typeof @sshObj.onEnd == 'function'
@.emit 'msg', "#{@sshObj.server.host}: Host loaded" if @sshObj.verbose
@.emit 'msg', @sshObj if @sshObj.verbose
if typeof callback == 'function'
callback()
connect: (callback)=>
@_callback = callback if typeof callback == 'function'
@.emit "newPrimaryHost", @_nextPrimaryHost(@_connect)
_connect: =>
@connection = new @ssh2Client()
@connection.on "keyboard-interactive", (name, instructions, instructionsLang, prompts, finish) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.keyboard-interactive" if @sshObj.debug
@.emit "keyboard-interactive", name, instructions, instructionsLang, prompts, finish
@connection.on "connect", =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.connect" if @sshObj.debug
@.emit 'msg', @sshObj.connectedMessage
@connection.on "ready", =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.ready" if @sshObj.debug
@.emit 'msg', @sshObj.readyMessage
#open a shell
@connection.shell @sshObj.window, { pty: @sshObj.pty }, (err, @_stream) =>
if err instanceof Error
@.emit 'error', err, "Shell", true
return
@.emit 'msg', "#{@sshObj.server.host}: Connection.shell" if @sshObj.debug
@_stream.setEncoding(@sshObj.streamEncoding);
@_stream.on "error", (err) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.error" if @sshObj.debug
@.emit 'error', err, "Stream"
@_stream.stderr.on 'data', (data) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.stderr.data" if @sshObj.debug
@.emit 'stderrData', data
@_stream.on "data", (data)=>
try
@.emit 'data', data
catch e
err = new Error("#{e} #{e.stack}")
err.level = "Data handling"
@.emit 'error', err, "Stream.read", true
@_stream.on "finish", =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.finish" if @sshObj.debug
@_primaryhostSessionText += @sshObj.sessionText+"\n"
@_allSessions += @_primaryhostSessionText
if typeIsArray(@hosts) and @hosts.length == 0
@.emit 'end', @_allSessions, @sshObj
@_removeEvents()
@_stream.on "close", (code, signal) =>
@.emit 'msg', "#{@sshObj.server.host}: Stream.close" if @sshObj.debug
@connection.end()
@connection.on "error", (err) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.error" if @sshObj.debug
@.emit "error", err, "Connection"
@connection.on "close", (had_error) =>
@.emit 'msg', "#{@sshObj.server.host}: Connection.close" if @sshObj.debug
if had_error
@.emit "error", had_error, "Connection close"
else
@.emit 'msg', @sshObj.closedMessage
if typeIsArray(@hosts) and @hosts.length == 0
if typeof @_callback == 'function'
@_callback @_allSessions
else
@.emit "newPrimaryHost", @_nextPrimaryHost(@_connect)
if @sshObj.server and @sshObj.commands
try
@connection.connect
host: @sshObj.server.host
port: @sshObj.server.port
forceIPv4: @sshObj.server.forceIPv4
forceIPv6: @sshObj.server.forceIPv6
hostHash: @sshObj.server.hashMethod
hostVerifier: @sshObj.server.hostVerifier
username: @sshObj.server.userName
password: PI:PASSWORD:<PASSWORD>END_PIObj.server.password
agent: @sshObj.server.agent
agentForward: @sshObj.server.agentForward
privateKey: @sshObj.server.privateKey
passphrase: PI:PASSWORD:<PASSWORD>END_PIObjPI:PASSWORD:<PASSWORD>END_PI.server.passPhrase
localHostname: @sshObj.server.localHostname
localUsername: @sshObj.server.localUsername
tryKeyboard: @sshObj.server.tryKeyboard
keepaliveInterval:@sshObj.server.keepaliveInterval
keepaliveCountMax:@sshObj.server.keepaliveCountMax
readyTimeout: @sshObj.server.readyTimeout
sock: @sshObj.server.sock
strictVendor: @sshObj.server.strictVendor
algorithms: @sshObj.server.algorithms
compress: @sshObj.server.compress
debug: @sshObj.server.debug
catch e
@.emit 'error', "#{e} #{e.stack}", "Connection.connect", true
else
@.emit 'error', "Missing connection parameters", "Parameters", false, ( err, type, close ) ->
@.emit 'msg', @sshObj.server
@.emit 'msg', @sshObj.commands
return @_stream
module.exports = SSH2Shell
|
[
{
"context": "\t\t\tnumber: \"数值\"\n\t\t\t\tcurrency: \"金额\"\n\t\t\t\tpassword: \"密码\"\n\t\t\t\tlookup: \"相关表\"\n\t\t\t\tmaster_detail: \"主表/子表\"\n\t\t\t",
"end": 1893,
"score": 0.9994643330574036,
"start": 1891,
"tag": "PASSWORD",
"value": "密码"
}
] | creator/packages/steedos-object-database/models/object_fields.coffee | steedos/object-server | 10 | _syncToObject = (doc) ->
object_fields = Creator.getCollection("object_fields").find({space: doc.space, object: doc.object}, {
fields: {
created: 0,
modified: 0,
owner: 0,
created_by: 0,
modified_by: 0
}
}).fetch()
fields = {}
table_fields = {}
_.forEach object_fields, (f)->
if /^[a-zA-Z_]\w*(\.\$\.\w+){1}[a-zA-Z0-9]*$/.test(f.name)
cf_arr = f.name.split(".$.")
child_fields = {}
child_fields[cf_arr[1]] = f
if !_.size(table_fields[cf_arr[0]])
table_fields[cf_arr[0]] = {}
_.extend(table_fields[cf_arr[0]], child_fields)
else
fields[f.name] = f
_.each table_fields, (f, k)->
if fields[k].type == "grid"
if !_.size(fields[k].fields)
fields[k].fields = {}
_.extend(fields[k].fields, f)
Creator.getCollection("objects").update({space: doc.space, name: doc.object}, {
$set:
fields: fields
})
isRepeatedName = (doc, name)->
other = Creator.getCollection("object_fields").find({object: doc.object, space: doc.space, _id: {$ne: doc._id}, name: name || doc.name}, {fields:{_id: 1}})
if other.count() > 0
return true
return false
Creator.Objects.object_fields =
name: "object_fields"
icon: "orders"
enable_api: true
label:"字段"
fields:
name:
type: "text"
searchable: true
index: true
required: true
regEx: SimpleSchema.RegEx.field
label:
type: "text"
is_name:
type: "boolean"
hidden: true
object:
type: "master_detail"
reference_to: "objects"
required: true
optionsFunction: ()->
_options = []
_.forEach Creator.objectsByName, (o, k)->
_options.push {label: o.label, value: k, icon: o.icon}
return _options
type:
type: "select"
# required: true
options:
text: "文本",
textarea: "长文本"
html: "Html文本",
select: "选择框",
boolean: "Checkbox"
date: "日期"
datetime: "日期时间"
number: "数值"
currency: "金额"
password: "密码"
lookup: "相关表"
master_detail: "主表/子表"
grid: "表格"
url: "网址"
email: "邮件地址"
sort_no:
label: "排序号"
type: "number"
defaultValue: 100
scale: 0
sortable: true
group:
type: "text"
defaultValue:
type: "text"
allowedValues:
type: "text"
multiple: true
multiple:
type: "boolean"
required:
type: "boolean"
is_wide:
type: "boolean"
readonly:
type: "boolean"
# disabled:
# type: "boolean"
hidden:
type: "boolean"
#TODO 将此功能开放给用户时,需要关闭此属性
omit:
type: "boolean"
index:
type: "boolean"
searchable:
type: "boolean"
sortable:
type: "boolean"
precision:
type: "currency"
defaultValue: 18
scale:
type: "currency"
defaultValue: 2
reference_to: #在服务端处理此字段值,如果小于2个,则存储为字符串,否则存储为数组
type: "lookup"
optionsFunction: ()->
_options = []
_.forEach Creator.Objects, (o, k)->
_options.push {label: o.label, value: k, icon: o.icon}
return _options
# multiple: true #先修改为单选
rows:
type: "currency"
options:
type: "textarea"
is_wide: true
description:
label: "Description"
type: "text"
is_wide: true
list_views:
all:
columns: ["name", "label", "type", "object", "sort_no", "modified"]
sort: [{field_name: "sort_no", order: "asc"}]
filter_scope: "space"
permission_set:
user:
allowCreate: false
allowDelete: false
allowEdit: false
allowRead: false
modifyAllRecords: false
viewAllRecords: false
admin:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
triggers:
"after.insert.server.object_fields":
on: "server"
when: "after.insert"
todo: (userId, doc)->
_syncToObject(doc)
"after.update.server.object_fields":
on: "server"
when: "after.update"
todo: (userId, doc)->
_syncToObject(doc)
"after.remove.server.object_fields":
on: "server"
when: "after.remove"
todo: (userId, doc)->
_syncToObject(doc)
"before.update.server.object_fields":
on: "server"
when: "before.update"
todo: (userId, doc, fieldNames, modifier, options)->
if doc.name == 'name' && modifier?.$set?.name && doc.name != modifier.$set.name
throw new Meteor.Error 500, "不能修改此记录的name属性"
if modifier?.$set?.name && isRepeatedName(doc, modifier.$set.name)
console.log("update fields对象名称不能重复#{doc.name}")
throw new Meteor.Error 500, "对象名称不能重复"
if modifier?.$set?.reference_to
if modifier.$set.reference_to.length == 1
_reference_to = modifier.$set.reference_to[0]
else
_reference_to = modifier.$set.reference_to
if modifier?.$set?.index and (modifier?.$set?.type == 'textarea' or modifier?.$set?.type == 'html')
throw new Meteor.Error 500, "多行文本不支持建立索引"
object = Creator.getCollection("objects").findOne({_id: doc.object}, {fields: {name: 1, label: 1}})
if object
object_documents = Creator.getCollection(object.name).find()
if modifier?.$set?.reference_to && doc.reference_to != _reference_to && object_documents.count() > 0
throw new Meteor.Error 500, "对象#{object.label}中已经有记录,不能修改reference_to字段"
if modifier?.$unset?.reference_to && doc.reference_to != _reference_to && object_documents.count() > 0
throw new Meteor.Error 500, "对象#{object.label}中已经有记录,不能修改reference_to字段"
# if modifier?.$set?.reference_to
# if modifier.$set.reference_to.length == 1
# modifier.$set.reference_to = modifier.$set.reference_to[0]
"before.insert.server.object_fields":
on: "server"
when: "before.insert"
todo: (userId, doc)->
# if doc.reference_to?.length == 1
# doc.reference_to = doc.reference_to[0]
if isRepeatedName(doc)
console.log("insert fields对象名称不能重复#{doc.name}")
throw new Meteor.Error 500, "对象名称不能重复"
if doc?.index and (doc?.type == 'textarea' or doc?.type == 'html')
throw new Meteor.Error 500,'多行文本不支持建立索引'
"before.remove.server.object_fields":
on: "server"
when: "before.remove"
todo: (userId, doc)->
if doc.name == "name"
throw new Meteor.Error 500, "不能删除此纪录"
| 183789 | _syncToObject = (doc) ->
object_fields = Creator.getCollection("object_fields").find({space: doc.space, object: doc.object}, {
fields: {
created: 0,
modified: 0,
owner: 0,
created_by: 0,
modified_by: 0
}
}).fetch()
fields = {}
table_fields = {}
_.forEach object_fields, (f)->
if /^[a-zA-Z_]\w*(\.\$\.\w+){1}[a-zA-Z0-9]*$/.test(f.name)
cf_arr = f.name.split(".$.")
child_fields = {}
child_fields[cf_arr[1]] = f
if !_.size(table_fields[cf_arr[0]])
table_fields[cf_arr[0]] = {}
_.extend(table_fields[cf_arr[0]], child_fields)
else
fields[f.name] = f
_.each table_fields, (f, k)->
if fields[k].type == "grid"
if !_.size(fields[k].fields)
fields[k].fields = {}
_.extend(fields[k].fields, f)
Creator.getCollection("objects").update({space: doc.space, name: doc.object}, {
$set:
fields: fields
})
isRepeatedName = (doc, name)->
other = Creator.getCollection("object_fields").find({object: doc.object, space: doc.space, _id: {$ne: doc._id}, name: name || doc.name}, {fields:{_id: 1}})
if other.count() > 0
return true
return false
Creator.Objects.object_fields =
name: "object_fields"
icon: "orders"
enable_api: true
label:"字段"
fields:
name:
type: "text"
searchable: true
index: true
required: true
regEx: SimpleSchema.RegEx.field
label:
type: "text"
is_name:
type: "boolean"
hidden: true
object:
type: "master_detail"
reference_to: "objects"
required: true
optionsFunction: ()->
_options = []
_.forEach Creator.objectsByName, (o, k)->
_options.push {label: o.label, value: k, icon: o.icon}
return _options
type:
type: "select"
# required: true
options:
text: "文本",
textarea: "长文本"
html: "Html文本",
select: "选择框",
boolean: "Checkbox"
date: "日期"
datetime: "日期时间"
number: "数值"
currency: "金额"
password: "<PASSWORD>"
lookup: "相关表"
master_detail: "主表/子表"
grid: "表格"
url: "网址"
email: "邮件地址"
sort_no:
label: "排序号"
type: "number"
defaultValue: 100
scale: 0
sortable: true
group:
type: "text"
defaultValue:
type: "text"
allowedValues:
type: "text"
multiple: true
multiple:
type: "boolean"
required:
type: "boolean"
is_wide:
type: "boolean"
readonly:
type: "boolean"
# disabled:
# type: "boolean"
hidden:
type: "boolean"
#TODO 将此功能开放给用户时,需要关闭此属性
omit:
type: "boolean"
index:
type: "boolean"
searchable:
type: "boolean"
sortable:
type: "boolean"
precision:
type: "currency"
defaultValue: 18
scale:
type: "currency"
defaultValue: 2
reference_to: #在服务端处理此字段值,如果小于2个,则存储为字符串,否则存储为数组
type: "lookup"
optionsFunction: ()->
_options = []
_.forEach Creator.Objects, (o, k)->
_options.push {label: o.label, value: k, icon: o.icon}
return _options
# multiple: true #先修改为单选
rows:
type: "currency"
options:
type: "textarea"
is_wide: true
description:
label: "Description"
type: "text"
is_wide: true
list_views:
all:
columns: ["name", "label", "type", "object", "sort_no", "modified"]
sort: [{field_name: "sort_no", order: "asc"}]
filter_scope: "space"
permission_set:
user:
allowCreate: false
allowDelete: false
allowEdit: false
allowRead: false
modifyAllRecords: false
viewAllRecords: false
admin:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
triggers:
"after.insert.server.object_fields":
on: "server"
when: "after.insert"
todo: (userId, doc)->
_syncToObject(doc)
"after.update.server.object_fields":
on: "server"
when: "after.update"
todo: (userId, doc)->
_syncToObject(doc)
"after.remove.server.object_fields":
on: "server"
when: "after.remove"
todo: (userId, doc)->
_syncToObject(doc)
"before.update.server.object_fields":
on: "server"
when: "before.update"
todo: (userId, doc, fieldNames, modifier, options)->
if doc.name == 'name' && modifier?.$set?.name && doc.name != modifier.$set.name
throw new Meteor.Error 500, "不能修改此记录的name属性"
if modifier?.$set?.name && isRepeatedName(doc, modifier.$set.name)
console.log("update fields对象名称不能重复#{doc.name}")
throw new Meteor.Error 500, "对象名称不能重复"
if modifier?.$set?.reference_to
if modifier.$set.reference_to.length == 1
_reference_to = modifier.$set.reference_to[0]
else
_reference_to = modifier.$set.reference_to
if modifier?.$set?.index and (modifier?.$set?.type == 'textarea' or modifier?.$set?.type == 'html')
throw new Meteor.Error 500, "多行文本不支持建立索引"
object = Creator.getCollection("objects").findOne({_id: doc.object}, {fields: {name: 1, label: 1}})
if object
object_documents = Creator.getCollection(object.name).find()
if modifier?.$set?.reference_to && doc.reference_to != _reference_to && object_documents.count() > 0
throw new Meteor.Error 500, "对象#{object.label}中已经有记录,不能修改reference_to字段"
if modifier?.$unset?.reference_to && doc.reference_to != _reference_to && object_documents.count() > 0
throw new Meteor.Error 500, "对象#{object.label}中已经有记录,不能修改reference_to字段"
# if modifier?.$set?.reference_to
# if modifier.$set.reference_to.length == 1
# modifier.$set.reference_to = modifier.$set.reference_to[0]
"before.insert.server.object_fields":
on: "server"
when: "before.insert"
todo: (userId, doc)->
# if doc.reference_to?.length == 1
# doc.reference_to = doc.reference_to[0]
if isRepeatedName(doc)
console.log("insert fields对象名称不能重复#{doc.name}")
throw new Meteor.Error 500, "对象名称不能重复"
if doc?.index and (doc?.type == 'textarea' or doc?.type == 'html')
throw new Meteor.Error 500,'多行文本不支持建立索引'
"before.remove.server.object_fields":
on: "server"
when: "before.remove"
todo: (userId, doc)->
if doc.name == "name"
throw new Meteor.Error 500, "不能删除此纪录"
| true | _syncToObject = (doc) ->
object_fields = Creator.getCollection("object_fields").find({space: doc.space, object: doc.object}, {
fields: {
created: 0,
modified: 0,
owner: 0,
created_by: 0,
modified_by: 0
}
}).fetch()
fields = {}
table_fields = {}
_.forEach object_fields, (f)->
if /^[a-zA-Z_]\w*(\.\$\.\w+){1}[a-zA-Z0-9]*$/.test(f.name)
cf_arr = f.name.split(".$.")
child_fields = {}
child_fields[cf_arr[1]] = f
if !_.size(table_fields[cf_arr[0]])
table_fields[cf_arr[0]] = {}
_.extend(table_fields[cf_arr[0]], child_fields)
else
fields[f.name] = f
_.each table_fields, (f, k)->
if fields[k].type == "grid"
if !_.size(fields[k].fields)
fields[k].fields = {}
_.extend(fields[k].fields, f)
Creator.getCollection("objects").update({space: doc.space, name: doc.object}, {
$set:
fields: fields
})
isRepeatedName = (doc, name)->
other = Creator.getCollection("object_fields").find({object: doc.object, space: doc.space, _id: {$ne: doc._id}, name: name || doc.name}, {fields:{_id: 1}})
if other.count() > 0
return true
return false
Creator.Objects.object_fields =
name: "object_fields"
icon: "orders"
enable_api: true
label:"字段"
fields:
name:
type: "text"
searchable: true
index: true
required: true
regEx: SimpleSchema.RegEx.field
label:
type: "text"
is_name:
type: "boolean"
hidden: true
object:
type: "master_detail"
reference_to: "objects"
required: true
optionsFunction: ()->
_options = []
_.forEach Creator.objectsByName, (o, k)->
_options.push {label: o.label, value: k, icon: o.icon}
return _options
type:
type: "select"
# required: true
options:
text: "文本",
textarea: "长文本"
html: "Html文本",
select: "选择框",
boolean: "Checkbox"
date: "日期"
datetime: "日期时间"
number: "数值"
currency: "金额"
password: "PI:PASSWORD:<PASSWORD>END_PI"
lookup: "相关表"
master_detail: "主表/子表"
grid: "表格"
url: "网址"
email: "邮件地址"
sort_no:
label: "排序号"
type: "number"
defaultValue: 100
scale: 0
sortable: true
group:
type: "text"
defaultValue:
type: "text"
allowedValues:
type: "text"
multiple: true
multiple:
type: "boolean"
required:
type: "boolean"
is_wide:
type: "boolean"
readonly:
type: "boolean"
# disabled:
# type: "boolean"
hidden:
type: "boolean"
#TODO 将此功能开放给用户时,需要关闭此属性
omit:
type: "boolean"
index:
type: "boolean"
searchable:
type: "boolean"
sortable:
type: "boolean"
precision:
type: "currency"
defaultValue: 18
scale:
type: "currency"
defaultValue: 2
reference_to: #在服务端处理此字段值,如果小于2个,则存储为字符串,否则存储为数组
type: "lookup"
optionsFunction: ()->
_options = []
_.forEach Creator.Objects, (o, k)->
_options.push {label: o.label, value: k, icon: o.icon}
return _options
# multiple: true #先修改为单选
rows:
type: "currency"
options:
type: "textarea"
is_wide: true
description:
label: "Description"
type: "text"
is_wide: true
list_views:
all:
columns: ["name", "label", "type", "object", "sort_no", "modified"]
sort: [{field_name: "sort_no", order: "asc"}]
filter_scope: "space"
permission_set:
user:
allowCreate: false
allowDelete: false
allowEdit: false
allowRead: false
modifyAllRecords: false
viewAllRecords: false
admin:
allowCreate: true
allowDelete: true
allowEdit: true
allowRead: true
modifyAllRecords: true
viewAllRecords: true
triggers:
"after.insert.server.object_fields":
on: "server"
when: "after.insert"
todo: (userId, doc)->
_syncToObject(doc)
"after.update.server.object_fields":
on: "server"
when: "after.update"
todo: (userId, doc)->
_syncToObject(doc)
"after.remove.server.object_fields":
on: "server"
when: "after.remove"
todo: (userId, doc)->
_syncToObject(doc)
"before.update.server.object_fields":
on: "server"
when: "before.update"
todo: (userId, doc, fieldNames, modifier, options)->
if doc.name == 'name' && modifier?.$set?.name && doc.name != modifier.$set.name
throw new Meteor.Error 500, "不能修改此记录的name属性"
if modifier?.$set?.name && isRepeatedName(doc, modifier.$set.name)
console.log("update fields对象名称不能重复#{doc.name}")
throw new Meteor.Error 500, "对象名称不能重复"
if modifier?.$set?.reference_to
if modifier.$set.reference_to.length == 1
_reference_to = modifier.$set.reference_to[0]
else
_reference_to = modifier.$set.reference_to
if modifier?.$set?.index and (modifier?.$set?.type == 'textarea' or modifier?.$set?.type == 'html')
throw new Meteor.Error 500, "多行文本不支持建立索引"
object = Creator.getCollection("objects").findOne({_id: doc.object}, {fields: {name: 1, label: 1}})
if object
object_documents = Creator.getCollection(object.name).find()
if modifier?.$set?.reference_to && doc.reference_to != _reference_to && object_documents.count() > 0
throw new Meteor.Error 500, "对象#{object.label}中已经有记录,不能修改reference_to字段"
if modifier?.$unset?.reference_to && doc.reference_to != _reference_to && object_documents.count() > 0
throw new Meteor.Error 500, "对象#{object.label}中已经有记录,不能修改reference_to字段"
# if modifier?.$set?.reference_to
# if modifier.$set.reference_to.length == 1
# modifier.$set.reference_to = modifier.$set.reference_to[0]
"before.insert.server.object_fields":
on: "server"
when: "before.insert"
todo: (userId, doc)->
# if doc.reference_to?.length == 1
# doc.reference_to = doc.reference_to[0]
if isRepeatedName(doc)
console.log("insert fields对象名称不能重复#{doc.name}")
throw new Meteor.Error 500, "对象名称不能重复"
if doc?.index and (doc?.type == 'textarea' or doc?.type == 'html')
throw new Meteor.Error 500,'多行文本不支持建立索引'
"before.remove.server.object_fields":
on: "server"
when: "before.remove"
todo: (userId, doc)->
if doc.name == "name"
throw new Meteor.Error 500, "不能删除此纪录"
|
[
{
"context": "kdevices.json').devices\n\nconfig = \n hostname: '192.168.105.222',\n port: 5222,\n# config2 =\n# hostname: '19",
"end": 431,
"score": 0.9996885061264038,
"start": 416,
"tag": "IP_ADDRESS",
"value": "192.168.105.222"
},
{
"context": "22',\n port: 5222,\n# config2 =\n# hostname: '192.168.105.221',\n# port: 5222,\n# token: \"14fc2e166841078",
"end": 494,
"score": 0.9996777176856995,
"start": 479,
"tag": "IP_ADDRESS",
"value": "192.168.105.221"
},
{
"context": "192.168.105.221',\n# port: 5222,\n# token: \"14fc2e1668410784f75ba8c946e4a4b6cac3989f\", \n# uuid: \"037dd8ef-19e7-4b44-8172-f2813f0c2",
"end": 569,
"score": 0.5735017657279968,
"start": 529,
"tag": "KEY",
"value": "14fc2e1668410784f75ba8c946e4a4b6cac3989f"
},
{
"context": "\n \"version\":0\n options =\n host: '192.168.105.222'\n port: 8080\n path: '/messaging/dev",
"end": 2309,
"score": 0.9997163414955139,
"start": 2294,
"tag": "IP_ADDRESS",
"value": "192.168.105.222"
}
] | command-xmpp-msg.coffee | ducxop/meshblu-benchmark | 0 | myMesh = require "./src/MyMeshblu.js"
Meshblu = require 'meshblu-xmpp'
Benchmark = require 'simple-benchmark'
Table = require 'cli-table'
async = require 'async'
_ = require 'lodash'
commander = require 'commander'
http = require('http')
now = require 'performance-now'
devices = require('./300kdevices.json').devices
config =
hostname: '192.168.105.222',
port: 5222,
# config2 =
# hostname: '192.168.105.221',
# port: 5222,
# token: "14fc2e1668410784f75ba8c946e4a4b6cac3989f",
# uuid: "037dd8ef-19e7-4b44-8172-f2813f0c245c"
benchmark = {}
conn = {}
nr = 0
n = 0
nS = 0
arr = []
bench = []
myParseInt = (string, defaultValue) ->
int = parseInt(string, 10)
if typeof int == 'number'
int
else
defaultValue
#@parseInt = (str) => parseInt str, 10
commander
.option '-t, --total-times [n]', 'create connection in total times (default to 1)', myParseInt, 1
.option '-i, --interval [n]', 'create connection with interval between each time(default 5s)', myParseInt, 5
.option '-n, --number-of-devices [n]', 'number of receiver devices to connect at a time (default to 1000)', myParseInt, 1000
.option '-s, --step [n]', 'display step (defaults to 500)', myParseInt, 500
.option '-m, --number-of-msg [n]', 'number of parallel messages (defaults to 1)', myParseInt, 1
.option '-o, --offset [n]','devices uuid offset value (default to 0)', myParseInt, 0
.option '-f, --offline'
.parse process.argv
{totalTimes,interval,numberOfDevices,step,numberOfMsg,offset,offline} = commander
totalTimes = totalTimes
interval = interval*1000
# if totalTimes = 1
# interval = 99999999
totalConnection = 0
dConnected = {}
dReceived = {}
dStartR = {}
conn = [] #new Meshblu(config2);
sendMessage = (callback) ->
console.log 'sending msg...'
arrDevices = []
date = new Date()
for i in [2...numberOfDevices*totalTimes+2]
arrDevices.push devices[i+offset].uuid
postData = JSON.stringify
"targetType":"device"
"pushProfile":"push profile 1"
"targets":arrDevices
"payload":"1"
"priority":0
"expirationDate":"2018-12-12 23:59:59"
"messageId": date.getTime()
"version":0
options =
host: '192.168.105.222'
port: 8080
path: '/messaging/devices/messages/send/'
method: 'POST'
headers: 'Content-Type': 'application/json'
req = http.request options,(res)=>
console.log 'STATUS:', res.statusCode
#console.log `HEADERS: ${JSON.stringify(res.headers)}`
res.setEncoding 'utf8'
rawData = ''
res.on 'data', (chunk) =>
rawData+=chunk
res.on 'end', () =>
#console.log JSON.parse rawData
typeof callback == 'function' && res.statusCode == 200 && callback()
req.on 'error', (e) =>
console.error 'problem with request:', e.message
req.write postData
req.end()
createConnections = () ->
totalMsgSend = 0
if nS>=totalTimes
return
else if nS==0
console.log "connecting "
for i in [numberOfDevices*nS...numberOfDevices*++nS]
config.uuid = devices[i+offset+2].uuid
config.token = devices[i+offset+2].token
conn[i] = new Meshblu(config)
conn_temp = conn[i]
conn_temp.on 'message', (message) =>
conn_temp.updateMessageStatus config.uuid, message.data.id, 1, (error) =>
if error
console.log error
if ++nr%(step*numberOfMsg)==0 then console.log 'receiving ', nr
id = parseInt(message.data.payload)
unless isNaN id
if arr[id]?
if ++arr[id]==totalConnection*numberOfMsg
printResults(id)
else
arr[id]=1
bench[id] = new Benchmark label:id
if nr==1
totalMsgSend = id
dStartR = new Date()
benchmark = new Benchmark label:'total benchmark'
if nr==(numberOfMsg*totalConnection*totalMsgSend)
dReceived = new Date()
console.log 'Start Connecting: ', dStartC.toString()
console.log 'Finish Connecting: ', dConnected.toString()
if totalMsgSend>1 then printResults()
console.log 'Received 1st msg: ', dStartR.toString()
console.log 'Received last msg: ', dReceived.toString()
process.exit 0
conn_temp.connect (i)=>
conn_temp.claimOfflineMessages config.uuid, (error) =>
if (error)
console.log(error);
if ++n%step==0 then console.log "connecting ", n
totalConnection=n
startConnect = () ->
createConnections()
runReceiver = () =>
if totalTimes==1
intervalObj = setImmediate startConnect
else
intervalObj = setInterval startConnect, interval
stopConnect = () ->
console.log totalConnection
if totalConnection==totalTimes*numberOfDevices
clearInterval intervalObj
dConnected = new Date()
if not offline
console.log 'start send message'
sendMessage()
else
setTimeout stopConnect, 1000
setTimeout stopConnect, totalTimes*interval
################# Run Benchmark ####################
dStartC = new Date()
console.time 'connect'
if totalTimes>0 && interval>0
if offline
sendMessage runReceiver
else
runReceiver()
################# End Benchmark ####################
printResults = (id) => #(error) =>
#return @die error if error?
if id?
elapsedTime = bench[id].elapsed()
totalmsg = arr[id]
console.log "Receiving Results - ", id
else
elapsedTime = benchmark.elapsed()
totalmsg = nr
console.log "Final Results: "
averagePerSecond = totalmsg / (elapsedTime / 1000)
#messageLoss = 1 - (_.size(@statusCodes) / (@cycles * @numberOfMessages))
generalTable = new Table
generalTable.push
'total msg receive' : "#{totalmsg}"
,
'took' : "#{elapsedTime}ms"
,
'average per second' : "#{averagePerSecond}/s"
percentileTable = new Table
head: ['10th', '25th', '50th', '75th', '90th']
percentileTable.push [
nthPercentile(10, @elapsedTimes2)
nthPercentile(25, @elapsedTimes2)
nthPercentile(50, @elapsedTimes2)
nthPercentile(75, @elapsedTimes2)
nthPercentile(90, @elapsedTimes2)
]
console.log generalTable.toString()
#console.log percentileTable.toString()
nthPercentile = (percentile, array) =>
array = _.sortBy array
index = (percentile / 100) * _.size(array)
if Math.floor(index) == index
return (array[index-1] + array[index]) / 2
return array[Math.floor index]
if process.platform == "win32"
inf =
input: process.stdin
output: process.stdout
rl = require "readline"
.createInterface inf
rl.on "SIGINT", () => process.emit "SIGINT"
onSigint = () =>
console.log "Exit on SIGINT"
process.exit 0
process.on "SIGINT", onSigint
| 196878 | myMesh = require "./src/MyMeshblu.js"
Meshblu = require 'meshblu-xmpp'
Benchmark = require 'simple-benchmark'
Table = require 'cli-table'
async = require 'async'
_ = require 'lodash'
commander = require 'commander'
http = require('http')
now = require 'performance-now'
devices = require('./300kdevices.json').devices
config =
hostname: '192.168.105.222',
port: 5222,
# config2 =
# hostname: '192.168.105.221',
# port: 5222,
# token: "<KEY>",
# uuid: "037dd8ef-19e7-4b44-8172-f2813f0c245c"
benchmark = {}
conn = {}
nr = 0
n = 0
nS = 0
arr = []
bench = []
myParseInt = (string, defaultValue) ->
int = parseInt(string, 10)
if typeof int == 'number'
int
else
defaultValue
#@parseInt = (str) => parseInt str, 10
commander
.option '-t, --total-times [n]', 'create connection in total times (default to 1)', myParseInt, 1
.option '-i, --interval [n]', 'create connection with interval between each time(default 5s)', myParseInt, 5
.option '-n, --number-of-devices [n]', 'number of receiver devices to connect at a time (default to 1000)', myParseInt, 1000
.option '-s, --step [n]', 'display step (defaults to 500)', myParseInt, 500
.option '-m, --number-of-msg [n]', 'number of parallel messages (defaults to 1)', myParseInt, 1
.option '-o, --offset [n]','devices uuid offset value (default to 0)', myParseInt, 0
.option '-f, --offline'
.parse process.argv
{totalTimes,interval,numberOfDevices,step,numberOfMsg,offset,offline} = commander
totalTimes = totalTimes
interval = interval*1000
# if totalTimes = 1
# interval = 99999999
totalConnection = 0
dConnected = {}
dReceived = {}
dStartR = {}
conn = [] #new Meshblu(config2);
sendMessage = (callback) ->
console.log 'sending msg...'
arrDevices = []
date = new Date()
for i in [2...numberOfDevices*totalTimes+2]
arrDevices.push devices[i+offset].uuid
postData = JSON.stringify
"targetType":"device"
"pushProfile":"push profile 1"
"targets":arrDevices
"payload":"1"
"priority":0
"expirationDate":"2018-12-12 23:59:59"
"messageId": date.getTime()
"version":0
options =
host: '192.168.105.222'
port: 8080
path: '/messaging/devices/messages/send/'
method: 'POST'
headers: 'Content-Type': 'application/json'
req = http.request options,(res)=>
console.log 'STATUS:', res.statusCode
#console.log `HEADERS: ${JSON.stringify(res.headers)}`
res.setEncoding 'utf8'
rawData = ''
res.on 'data', (chunk) =>
rawData+=chunk
res.on 'end', () =>
#console.log JSON.parse rawData
typeof callback == 'function' && res.statusCode == 200 && callback()
req.on 'error', (e) =>
console.error 'problem with request:', e.message
req.write postData
req.end()
createConnections = () ->
totalMsgSend = 0
if nS>=totalTimes
return
else if nS==0
console.log "connecting "
for i in [numberOfDevices*nS...numberOfDevices*++nS]
config.uuid = devices[i+offset+2].uuid
config.token = devices[i+offset+2].token
conn[i] = new Meshblu(config)
conn_temp = conn[i]
conn_temp.on 'message', (message) =>
conn_temp.updateMessageStatus config.uuid, message.data.id, 1, (error) =>
if error
console.log error
if ++nr%(step*numberOfMsg)==0 then console.log 'receiving ', nr
id = parseInt(message.data.payload)
unless isNaN id
if arr[id]?
if ++arr[id]==totalConnection*numberOfMsg
printResults(id)
else
arr[id]=1
bench[id] = new Benchmark label:id
if nr==1
totalMsgSend = id
dStartR = new Date()
benchmark = new Benchmark label:'total benchmark'
if nr==(numberOfMsg*totalConnection*totalMsgSend)
dReceived = new Date()
console.log 'Start Connecting: ', dStartC.toString()
console.log 'Finish Connecting: ', dConnected.toString()
if totalMsgSend>1 then printResults()
console.log 'Received 1st msg: ', dStartR.toString()
console.log 'Received last msg: ', dReceived.toString()
process.exit 0
conn_temp.connect (i)=>
conn_temp.claimOfflineMessages config.uuid, (error) =>
if (error)
console.log(error);
if ++n%step==0 then console.log "connecting ", n
totalConnection=n
startConnect = () ->
createConnections()
runReceiver = () =>
if totalTimes==1
intervalObj = setImmediate startConnect
else
intervalObj = setInterval startConnect, interval
stopConnect = () ->
console.log totalConnection
if totalConnection==totalTimes*numberOfDevices
clearInterval intervalObj
dConnected = new Date()
if not offline
console.log 'start send message'
sendMessage()
else
setTimeout stopConnect, 1000
setTimeout stopConnect, totalTimes*interval
################# Run Benchmark ####################
dStartC = new Date()
console.time 'connect'
if totalTimes>0 && interval>0
if offline
sendMessage runReceiver
else
runReceiver()
################# End Benchmark ####################
printResults = (id) => #(error) =>
#return @die error if error?
if id?
elapsedTime = bench[id].elapsed()
totalmsg = arr[id]
console.log "Receiving Results - ", id
else
elapsedTime = benchmark.elapsed()
totalmsg = nr
console.log "Final Results: "
averagePerSecond = totalmsg / (elapsedTime / 1000)
#messageLoss = 1 - (_.size(@statusCodes) / (@cycles * @numberOfMessages))
generalTable = new Table
generalTable.push
'total msg receive' : "#{totalmsg}"
,
'took' : "#{elapsedTime}ms"
,
'average per second' : "#{averagePerSecond}/s"
percentileTable = new Table
head: ['10th', '25th', '50th', '75th', '90th']
percentileTable.push [
nthPercentile(10, @elapsedTimes2)
nthPercentile(25, @elapsedTimes2)
nthPercentile(50, @elapsedTimes2)
nthPercentile(75, @elapsedTimes2)
nthPercentile(90, @elapsedTimes2)
]
console.log generalTable.toString()
#console.log percentileTable.toString()
nthPercentile = (percentile, array) =>
array = _.sortBy array
index = (percentile / 100) * _.size(array)
if Math.floor(index) == index
return (array[index-1] + array[index]) / 2
return array[Math.floor index]
if process.platform == "win32"
inf =
input: process.stdin
output: process.stdout
rl = require "readline"
.createInterface inf
rl.on "SIGINT", () => process.emit "SIGINT"
onSigint = () =>
console.log "Exit on SIGINT"
process.exit 0
process.on "SIGINT", onSigint
| true | myMesh = require "./src/MyMeshblu.js"
Meshblu = require 'meshblu-xmpp'
Benchmark = require 'simple-benchmark'
Table = require 'cli-table'
async = require 'async'
_ = require 'lodash'
commander = require 'commander'
http = require('http')
now = require 'performance-now'
devices = require('./300kdevices.json').devices
config =
hostname: '192.168.105.222',
port: 5222,
# config2 =
# hostname: '192.168.105.221',
# port: 5222,
# token: "PI:KEY:<KEY>END_PI",
# uuid: "037dd8ef-19e7-4b44-8172-f2813f0c245c"
benchmark = {}
conn = {}
nr = 0
n = 0
nS = 0
arr = []
bench = []
myParseInt = (string, defaultValue) ->
int = parseInt(string, 10)
if typeof int == 'number'
int
else
defaultValue
#@parseInt = (str) => parseInt str, 10
commander
.option '-t, --total-times [n]', 'create connection in total times (default to 1)', myParseInt, 1
.option '-i, --interval [n]', 'create connection with interval between each time(default 5s)', myParseInt, 5
.option '-n, --number-of-devices [n]', 'number of receiver devices to connect at a time (default to 1000)', myParseInt, 1000
.option '-s, --step [n]', 'display step (defaults to 500)', myParseInt, 500
.option '-m, --number-of-msg [n]', 'number of parallel messages (defaults to 1)', myParseInt, 1
.option '-o, --offset [n]','devices uuid offset value (default to 0)', myParseInt, 0
.option '-f, --offline'
.parse process.argv
{totalTimes,interval,numberOfDevices,step,numberOfMsg,offset,offline} = commander
totalTimes = totalTimes
interval = interval*1000
# if totalTimes = 1
# interval = 99999999
totalConnection = 0
dConnected = {}
dReceived = {}
dStartR = {}
conn = [] #new Meshblu(config2);
sendMessage = (callback) ->
console.log 'sending msg...'
arrDevices = []
date = new Date()
for i in [2...numberOfDevices*totalTimes+2]
arrDevices.push devices[i+offset].uuid
postData = JSON.stringify
"targetType":"device"
"pushProfile":"push profile 1"
"targets":arrDevices
"payload":"1"
"priority":0
"expirationDate":"2018-12-12 23:59:59"
"messageId": date.getTime()
"version":0
options =
host: '192.168.105.222'
port: 8080
path: '/messaging/devices/messages/send/'
method: 'POST'
headers: 'Content-Type': 'application/json'
req = http.request options,(res)=>
console.log 'STATUS:', res.statusCode
#console.log `HEADERS: ${JSON.stringify(res.headers)}`
res.setEncoding 'utf8'
rawData = ''
res.on 'data', (chunk) =>
rawData+=chunk
res.on 'end', () =>
#console.log JSON.parse rawData
typeof callback == 'function' && res.statusCode == 200 && callback()
req.on 'error', (e) =>
console.error 'problem with request:', e.message
req.write postData
req.end()
createConnections = () ->
totalMsgSend = 0
if nS>=totalTimes
return
else if nS==0
console.log "connecting "
for i in [numberOfDevices*nS...numberOfDevices*++nS]
config.uuid = devices[i+offset+2].uuid
config.token = devices[i+offset+2].token
conn[i] = new Meshblu(config)
conn_temp = conn[i]
conn_temp.on 'message', (message) =>
conn_temp.updateMessageStatus config.uuid, message.data.id, 1, (error) =>
if error
console.log error
if ++nr%(step*numberOfMsg)==0 then console.log 'receiving ', nr
id = parseInt(message.data.payload)
unless isNaN id
if arr[id]?
if ++arr[id]==totalConnection*numberOfMsg
printResults(id)
else
arr[id]=1
bench[id] = new Benchmark label:id
if nr==1
totalMsgSend = id
dStartR = new Date()
benchmark = new Benchmark label:'total benchmark'
if nr==(numberOfMsg*totalConnection*totalMsgSend)
dReceived = new Date()
console.log 'Start Connecting: ', dStartC.toString()
console.log 'Finish Connecting: ', dConnected.toString()
if totalMsgSend>1 then printResults()
console.log 'Received 1st msg: ', dStartR.toString()
console.log 'Received last msg: ', dReceived.toString()
process.exit 0
conn_temp.connect (i)=>
conn_temp.claimOfflineMessages config.uuid, (error) =>
if (error)
console.log(error);
if ++n%step==0 then console.log "connecting ", n
totalConnection=n
startConnect = () ->
createConnections()
runReceiver = () =>
if totalTimes==1
intervalObj = setImmediate startConnect
else
intervalObj = setInterval startConnect, interval
stopConnect = () ->
console.log totalConnection
if totalConnection==totalTimes*numberOfDevices
clearInterval intervalObj
dConnected = new Date()
if not offline
console.log 'start send message'
sendMessage()
else
setTimeout stopConnect, 1000
setTimeout stopConnect, totalTimes*interval
################# Run Benchmark ####################
dStartC = new Date()
console.time 'connect'
if totalTimes>0 && interval>0
if offline
sendMessage runReceiver
else
runReceiver()
################# End Benchmark ####################
printResults = (id) => #(error) =>
#return @die error if error?
if id?
elapsedTime = bench[id].elapsed()
totalmsg = arr[id]
console.log "Receiving Results - ", id
else
elapsedTime = benchmark.elapsed()
totalmsg = nr
console.log "Final Results: "
averagePerSecond = totalmsg / (elapsedTime / 1000)
#messageLoss = 1 - (_.size(@statusCodes) / (@cycles * @numberOfMessages))
generalTable = new Table
generalTable.push
'total msg receive' : "#{totalmsg}"
,
'took' : "#{elapsedTime}ms"
,
'average per second' : "#{averagePerSecond}/s"
percentileTable = new Table
head: ['10th', '25th', '50th', '75th', '90th']
percentileTable.push [
nthPercentile(10, @elapsedTimes2)
nthPercentile(25, @elapsedTimes2)
nthPercentile(50, @elapsedTimes2)
nthPercentile(75, @elapsedTimes2)
nthPercentile(90, @elapsedTimes2)
]
console.log generalTable.toString()
#console.log percentileTable.toString()
nthPercentile = (percentile, array) =>
array = _.sortBy array
index = (percentile / 100) * _.size(array)
if Math.floor(index) == index
return (array[index-1] + array[index]) / 2
return array[Math.floor index]
if process.platform == "win32"
inf =
input: process.stdin
output: process.stdout
rl = require "readline"
.createInterface inf
rl.on "SIGINT", () => process.emit "SIGINT"
onSigint = () =>
console.log "Exit on SIGINT"
process.exit 0
process.on "SIGINT", onSigint
|
[
{
"context": "# Author: Josh Bass\n\nReact = require(\"react\");\nCustomerEdit = require",
"end": 19,
"score": 0.9998644590377808,
"start": 10,
"tag": "NAME",
"value": "Josh Bass"
}
] | src/client/components/customers/CustomerTable.coffee | jbass86/Aroma | 0 | # Author: Josh Bass
React = require("react");
CustomerEdit = require("./CustomerEdit.coffee");
Moment = require("moment");
DateUtils = require("utilities/DateUtils.coffee");
module.exports = React.createClass
getInitialState: ->
{expanded_rows: {}, editing_item: undefined, confirming_delete: {}, order_mode: false};
componentDidMount: ->
@props.order_model.on("change:order_mode", (model, data) =>
@setState({order_mode: data})
);
render: ->
if (@state.order_mode)
<div style={{"margin": "auto"}} className="common-table">
{@props.items.map((item, index) =>
<div className="common-table-entry" key={item._id}>
<div className="row">
<div className="col-md-1">
<button className="btn btn-primary" onClick={@updateOrder.bind(@, item)}>
<span className="glyphicon glyphicon-pushpin"></span>
</button>
</div>
<div className="col-md-11">
{@renderCustomerRow(item)}
</div>
</div>
{@renderInfoSection(item)}
</div>
)}
</div>
else
<div style={{"margin": "auto"}} className="common-table">
{@props.items.map((item, index) =>
<div className="common-table-entry" key={item._id}>
{@renderCustomerRow(item)}
{@renderInfoSection(item)}
</div>
)}
</div>
renderCustomerRow: (item) ->
<div className="row common-row" onClick={@expandRow.bind(@, item)}>
<div className="col-md-3">{item.first_name}</div>
<div className="col-md-3">{item.last_name}</div>
<div className="col-md-3">{item.email}</div>
<div className="col-md-3">{item.social_media}</div>
</div>
renderInfoSection: (item) ->
info_classes = "collapsible";
if (@state.expanded_rows[item._id])
#make sure expanded row state has the most up to date item.
@state.expanded_rows[item._id] = item;
info_classes += " full-height-large";
else
info_classes += " no-height";
delete_alert_classes = "collapsible"
if (@state.confirming_delete[item._id])
delete_alert_classes += " full-height-small";
else
delete_alert_classes += " no-height";
<div className={info_classes}>
<div className="row item-edit-buttons">
<button className="col-xs-6 btn btn-primary" onClick={@editItem.bind(@, item)}>
<span className="glyphicon glyphicon-edit"></span>
</button>
<button className="col-xs-6 btn btn-danger" onClick={@confirmDelete.bind(@, item)}>
<span className="glyphicon glyphicon-trash"></span>
</button>
</div>
<div className={delete_alert_classes}>
<div className="delete-item-alert alert common-alert" role="alert">
<span>Are you Sure?</span>
<div className="row alert-panel">
<button className="col-xs-6 btn button-ok" onClick={@deleteItem.bind(@, item)}>Yes</button>
<button className="col-xs-6 btn button-cancel" onClick={@confirmDelete.bind(@, item)}>No</button>
</div>
</div>
</div>
{@renderDetailedInfo(item)}
</div>
renderDetailedInfo: (item) ->
if (@state.editing_item == item._id)
initial_state = {_id: item._id, first_name: item.first_name, middle_name: item.middle_name, last_name: item.last_name, \
address: item.address, email: item.email, phone_number: item.phone_number, social_media: item.social_media, \
birthday: item.birthday};
<CustomerEdit initialState={initial_state} updateCustomer={@finishEdit} handleFinish={@cancelEdit}/>
else
<div className="common-info-section">
<div className="row">
<div className="col-md-3 customer-label">
First Name:
</div>
<div className="col-md-3 customer-info">
{if item.first_name then item.first_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Middle Name:
</div>
<div className="col-md-3 customer-info">
{if item.middle_name then item.middle_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Last Name:
</div>
<div className="col-md-3 customer-info">
{if item.last_name then item.last_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Address:
</div>
<div className="col-md-3 customer-info">
{if item.address then item.address else "N/A"}
</div>
<div className="col-md-3 customer-label">
Email:
</div>
<div className="col-md-3 customer-info">
{if item.email then item.email else "N/A"}
</div>
<div className="col-md-3 customer-label">
Phone Number:
</div>
<div className="col-md-3 customer-info">
{if item.phone_number then item.phone_number else "N/A"}
</div>
<div className="col-md-3 customer-label">
Social Media:
</div>
<div className="col-md-3 customer-info">
{if item.social_media then item.social_media else "N/A"}
</div>
<div className="col-md-3 customer-label">
Birthday:
</div>
<div className="col-md-3 customer-info">
{if item.birthday then DateUtils.getPrettyDate(item.birthday) else "N/A"}
</div>
</div>
</div>
expandRow: (item) ->
if(@state.expanded_rows[item._id])
delete @state.expanded_rows[item._id]
else
@state.expanded_rows[item._id] = item;
@setState({expanded_rows: @state.expanded_rows});
confirmDelete: (item) ->
if(@state.confirming_delete[item._id])
delete @state.confirming_delete[item._id]
else
@state.confirming_delete[item._id] = item;
@setState({confirming_delete: @state.confirming_delete})
deleteItem: (item) ->
$.post("aroma/secure/delete_customers", {token: window.sessionStorage.token, items_to_delete: [item]}, (response) =>
if (response.success)
@props.customerUpdate();
)
@confirmDelete(item);
editItem: (item) ->
@setState({editing_item: item._id});
finishEdit: (id) ->
@props.customerUpdate();
cancelEdit: () ->
@setState({editing_item: undefined});
updateOrder: (item) ->
console.log("add customer to order");
console.log(item);
@props.order_model.set("customer", item);
| 25026 | # Author: <NAME>
React = require("react");
CustomerEdit = require("./CustomerEdit.coffee");
Moment = require("moment");
DateUtils = require("utilities/DateUtils.coffee");
module.exports = React.createClass
getInitialState: ->
{expanded_rows: {}, editing_item: undefined, confirming_delete: {}, order_mode: false};
componentDidMount: ->
@props.order_model.on("change:order_mode", (model, data) =>
@setState({order_mode: data})
);
render: ->
if (@state.order_mode)
<div style={{"margin": "auto"}} className="common-table">
{@props.items.map((item, index) =>
<div className="common-table-entry" key={item._id}>
<div className="row">
<div className="col-md-1">
<button className="btn btn-primary" onClick={@updateOrder.bind(@, item)}>
<span className="glyphicon glyphicon-pushpin"></span>
</button>
</div>
<div className="col-md-11">
{@renderCustomerRow(item)}
</div>
</div>
{@renderInfoSection(item)}
</div>
)}
</div>
else
<div style={{"margin": "auto"}} className="common-table">
{@props.items.map((item, index) =>
<div className="common-table-entry" key={item._id}>
{@renderCustomerRow(item)}
{@renderInfoSection(item)}
</div>
)}
</div>
renderCustomerRow: (item) ->
<div className="row common-row" onClick={@expandRow.bind(@, item)}>
<div className="col-md-3">{item.first_name}</div>
<div className="col-md-3">{item.last_name}</div>
<div className="col-md-3">{item.email}</div>
<div className="col-md-3">{item.social_media}</div>
</div>
renderInfoSection: (item) ->
info_classes = "collapsible";
if (@state.expanded_rows[item._id])
#make sure expanded row state has the most up to date item.
@state.expanded_rows[item._id] = item;
info_classes += " full-height-large";
else
info_classes += " no-height";
delete_alert_classes = "collapsible"
if (@state.confirming_delete[item._id])
delete_alert_classes += " full-height-small";
else
delete_alert_classes += " no-height";
<div className={info_classes}>
<div className="row item-edit-buttons">
<button className="col-xs-6 btn btn-primary" onClick={@editItem.bind(@, item)}>
<span className="glyphicon glyphicon-edit"></span>
</button>
<button className="col-xs-6 btn btn-danger" onClick={@confirmDelete.bind(@, item)}>
<span className="glyphicon glyphicon-trash"></span>
</button>
</div>
<div className={delete_alert_classes}>
<div className="delete-item-alert alert common-alert" role="alert">
<span>Are you Sure?</span>
<div className="row alert-panel">
<button className="col-xs-6 btn button-ok" onClick={@deleteItem.bind(@, item)}>Yes</button>
<button className="col-xs-6 btn button-cancel" onClick={@confirmDelete.bind(@, item)}>No</button>
</div>
</div>
</div>
{@renderDetailedInfo(item)}
</div>
renderDetailedInfo: (item) ->
if (@state.editing_item == item._id)
initial_state = {_id: item._id, first_name: item.first_name, middle_name: item.middle_name, last_name: item.last_name, \
address: item.address, email: item.email, phone_number: item.phone_number, social_media: item.social_media, \
birthday: item.birthday};
<CustomerEdit initialState={initial_state} updateCustomer={@finishEdit} handleFinish={@cancelEdit}/>
else
<div className="common-info-section">
<div className="row">
<div className="col-md-3 customer-label">
First Name:
</div>
<div className="col-md-3 customer-info">
{if item.first_name then item.first_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Middle Name:
</div>
<div className="col-md-3 customer-info">
{if item.middle_name then item.middle_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Last Name:
</div>
<div className="col-md-3 customer-info">
{if item.last_name then item.last_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Address:
</div>
<div className="col-md-3 customer-info">
{if item.address then item.address else "N/A"}
</div>
<div className="col-md-3 customer-label">
Email:
</div>
<div className="col-md-3 customer-info">
{if item.email then item.email else "N/A"}
</div>
<div className="col-md-3 customer-label">
Phone Number:
</div>
<div className="col-md-3 customer-info">
{if item.phone_number then item.phone_number else "N/A"}
</div>
<div className="col-md-3 customer-label">
Social Media:
</div>
<div className="col-md-3 customer-info">
{if item.social_media then item.social_media else "N/A"}
</div>
<div className="col-md-3 customer-label">
Birthday:
</div>
<div className="col-md-3 customer-info">
{if item.birthday then DateUtils.getPrettyDate(item.birthday) else "N/A"}
</div>
</div>
</div>
expandRow: (item) ->
if(@state.expanded_rows[item._id])
delete @state.expanded_rows[item._id]
else
@state.expanded_rows[item._id] = item;
@setState({expanded_rows: @state.expanded_rows});
confirmDelete: (item) ->
if(@state.confirming_delete[item._id])
delete @state.confirming_delete[item._id]
else
@state.confirming_delete[item._id] = item;
@setState({confirming_delete: @state.confirming_delete})
deleteItem: (item) ->
$.post("aroma/secure/delete_customers", {token: window.sessionStorage.token, items_to_delete: [item]}, (response) =>
if (response.success)
@props.customerUpdate();
)
@confirmDelete(item);
editItem: (item) ->
@setState({editing_item: item._id});
finishEdit: (id) ->
@props.customerUpdate();
cancelEdit: () ->
@setState({editing_item: undefined});
updateOrder: (item) ->
console.log("add customer to order");
console.log(item);
@props.order_model.set("customer", item);
| true | # Author: PI:NAME:<NAME>END_PI
React = require("react");
CustomerEdit = require("./CustomerEdit.coffee");
Moment = require("moment");
DateUtils = require("utilities/DateUtils.coffee");
module.exports = React.createClass
getInitialState: ->
{expanded_rows: {}, editing_item: undefined, confirming_delete: {}, order_mode: false};
componentDidMount: ->
@props.order_model.on("change:order_mode", (model, data) =>
@setState({order_mode: data})
);
render: ->
if (@state.order_mode)
<div style={{"margin": "auto"}} className="common-table">
{@props.items.map((item, index) =>
<div className="common-table-entry" key={item._id}>
<div className="row">
<div className="col-md-1">
<button className="btn btn-primary" onClick={@updateOrder.bind(@, item)}>
<span className="glyphicon glyphicon-pushpin"></span>
</button>
</div>
<div className="col-md-11">
{@renderCustomerRow(item)}
</div>
</div>
{@renderInfoSection(item)}
</div>
)}
</div>
else
<div style={{"margin": "auto"}} className="common-table">
{@props.items.map((item, index) =>
<div className="common-table-entry" key={item._id}>
{@renderCustomerRow(item)}
{@renderInfoSection(item)}
</div>
)}
</div>
renderCustomerRow: (item) ->
<div className="row common-row" onClick={@expandRow.bind(@, item)}>
<div className="col-md-3">{item.first_name}</div>
<div className="col-md-3">{item.last_name}</div>
<div className="col-md-3">{item.email}</div>
<div className="col-md-3">{item.social_media}</div>
</div>
renderInfoSection: (item) ->
info_classes = "collapsible";
if (@state.expanded_rows[item._id])
#make sure expanded row state has the most up to date item.
@state.expanded_rows[item._id] = item;
info_classes += " full-height-large";
else
info_classes += " no-height";
delete_alert_classes = "collapsible"
if (@state.confirming_delete[item._id])
delete_alert_classes += " full-height-small";
else
delete_alert_classes += " no-height";
<div className={info_classes}>
<div className="row item-edit-buttons">
<button className="col-xs-6 btn btn-primary" onClick={@editItem.bind(@, item)}>
<span className="glyphicon glyphicon-edit"></span>
</button>
<button className="col-xs-6 btn btn-danger" onClick={@confirmDelete.bind(@, item)}>
<span className="glyphicon glyphicon-trash"></span>
</button>
</div>
<div className={delete_alert_classes}>
<div className="delete-item-alert alert common-alert" role="alert">
<span>Are you Sure?</span>
<div className="row alert-panel">
<button className="col-xs-6 btn button-ok" onClick={@deleteItem.bind(@, item)}>Yes</button>
<button className="col-xs-6 btn button-cancel" onClick={@confirmDelete.bind(@, item)}>No</button>
</div>
</div>
</div>
{@renderDetailedInfo(item)}
</div>
renderDetailedInfo: (item) ->
if (@state.editing_item == item._id)
initial_state = {_id: item._id, first_name: item.first_name, middle_name: item.middle_name, last_name: item.last_name, \
address: item.address, email: item.email, phone_number: item.phone_number, social_media: item.social_media, \
birthday: item.birthday};
<CustomerEdit initialState={initial_state} updateCustomer={@finishEdit} handleFinish={@cancelEdit}/>
else
<div className="common-info-section">
<div className="row">
<div className="col-md-3 customer-label">
First Name:
</div>
<div className="col-md-3 customer-info">
{if item.first_name then item.first_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Middle Name:
</div>
<div className="col-md-3 customer-info">
{if item.middle_name then item.middle_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Last Name:
</div>
<div className="col-md-3 customer-info">
{if item.last_name then item.last_name else "N/A"}
</div>
<div className="col-md-3 customer-label">
Address:
</div>
<div className="col-md-3 customer-info">
{if item.address then item.address else "N/A"}
</div>
<div className="col-md-3 customer-label">
Email:
</div>
<div className="col-md-3 customer-info">
{if item.email then item.email else "N/A"}
</div>
<div className="col-md-3 customer-label">
Phone Number:
</div>
<div className="col-md-3 customer-info">
{if item.phone_number then item.phone_number else "N/A"}
</div>
<div className="col-md-3 customer-label">
Social Media:
</div>
<div className="col-md-3 customer-info">
{if item.social_media then item.social_media else "N/A"}
</div>
<div className="col-md-3 customer-label">
Birthday:
</div>
<div className="col-md-3 customer-info">
{if item.birthday then DateUtils.getPrettyDate(item.birthday) else "N/A"}
</div>
</div>
</div>
expandRow: (item) ->
if(@state.expanded_rows[item._id])
delete @state.expanded_rows[item._id]
else
@state.expanded_rows[item._id] = item;
@setState({expanded_rows: @state.expanded_rows});
confirmDelete: (item) ->
if(@state.confirming_delete[item._id])
delete @state.confirming_delete[item._id]
else
@state.confirming_delete[item._id] = item;
@setState({confirming_delete: @state.confirming_delete})
deleteItem: (item) ->
$.post("aroma/secure/delete_customers", {token: window.sessionStorage.token, items_to_delete: [item]}, (response) =>
if (response.success)
@props.customerUpdate();
)
@confirmDelete(item);
editItem: (item) ->
@setState({editing_item: item._id});
finishEdit: (id) ->
@props.customerUpdate();
cancelEdit: () ->
@setState({editing_item: undefined});
updateOrder: (item) ->
console.log("add customer to order");
console.log(item);
@props.order_model.set("customer", item);
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999109506607056,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/react/beatmaps/search-filter.coffee | osu-katakuna/osu-katakuna-web | 5 | # Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import core from 'osu-core-singleton'
import * as React from 'react'
import { div, a, span } from 'react-dom-factories'
el = React.createElement
controller = core.beatmapsetSearchController
export class SearchFilter extends React.PureComponent
constructor: (props) ->
super props
@cache = {}
componentWillReceiveProps: (nextProps) =>
@cache = {}
render: =>
div className: 'beatmapsets-search-filter',
if @props.title?
span className: 'beatmapsets-search-filter__header', @props.title
div className: 'beatmapsets-search-filter__items',
for option, i in @props.options
cssClasses = 'beatmapsets-search-filter__item'
cssClasses += ' beatmapsets-search-filter__item--active' if @selected(option.id)
text = option.name
if @props.name == 'general' && option.id == 'recommended' && @props.recommendedDifficulty?
text += " (#{osu.formatNumber(@props.recommendedDifficulty, 2)})"
a
key: i
href: @href(option)
className: cssClasses
'data-filter-value': option.id
onClick: @select
text
cast: (value) =>
BeatmapsetFilter.castFromString[@props.name]?(value) ? value ? null
href: ({ id }) =>
updatedFilter = {}
updatedFilter[@props.name] = @newSelection(id)
filters = _.assign {}, @props.filters.values, updatedFilter
osu.updateQueryString null, BeatmapsetFilter.queryParamsFromFilters(filters)
select: (e) =>
e.preventDefault()
controller.updateFilters "#{@props.name}": @newSelection(e.target.dataset.filterValue) ? null
# TODO: rename
newSelection: (id) =>
i = @cast(id)
if @props.multiselect
_(@currentSelection())[if @selected(i) then 'without' else 'concat'](i).sort().join('.')
else
if @selected(i) then BeatmapsetFilter.defaults[id] else i
selected: (i) =>
i in @currentSelection()
currentSelection: =>
@cache.currentSelection ?=
if @props.multiselect
_(@props.selected ? '')
.split('.')
.filter (s) =>
s in _.map(@props.options, 'id')
.value()
else
[@props.selected]
| 118189 | # Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import core from 'osu-core-singleton'
import * as React from 'react'
import { div, a, span } from 'react-dom-factories'
el = React.createElement
controller = core.beatmapsetSearchController
export class SearchFilter extends React.PureComponent
constructor: (props) ->
super props
@cache = {}
componentWillReceiveProps: (nextProps) =>
@cache = {}
render: =>
div className: 'beatmapsets-search-filter',
if @props.title?
span className: 'beatmapsets-search-filter__header', @props.title
div className: 'beatmapsets-search-filter__items',
for option, i in @props.options
cssClasses = 'beatmapsets-search-filter__item'
cssClasses += ' beatmapsets-search-filter__item--active' if @selected(option.id)
text = option.name
if @props.name == 'general' && option.id == 'recommended' && @props.recommendedDifficulty?
text += " (#{osu.formatNumber(@props.recommendedDifficulty, 2)})"
a
key: i
href: @href(option)
className: cssClasses
'data-filter-value': option.id
onClick: @select
text
cast: (value) =>
BeatmapsetFilter.castFromString[@props.name]?(value) ? value ? null
href: ({ id }) =>
updatedFilter = {}
updatedFilter[@props.name] = @newSelection(id)
filters = _.assign {}, @props.filters.values, updatedFilter
osu.updateQueryString null, BeatmapsetFilter.queryParamsFromFilters(filters)
select: (e) =>
e.preventDefault()
controller.updateFilters "#{@props.name}": @newSelection(e.target.dataset.filterValue) ? null
# TODO: rename
newSelection: (id) =>
i = @cast(id)
if @props.multiselect
_(@currentSelection())[if @selected(i) then 'without' else 'concat'](i).sort().join('.')
else
if @selected(i) then BeatmapsetFilter.defaults[id] else i
selected: (i) =>
i in @currentSelection()
currentSelection: =>
@cache.currentSelection ?=
if @props.multiselect
_(@props.selected ? '')
.split('.')
.filter (s) =>
s in _.map(@props.options, 'id')
.value()
else
[@props.selected]
| true | # Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0.
# See the LICENCE file in the repository root for full licence text.
import core from 'osu-core-singleton'
import * as React from 'react'
import { div, a, span } from 'react-dom-factories'
el = React.createElement
controller = core.beatmapsetSearchController
export class SearchFilter extends React.PureComponent
constructor: (props) ->
super props
@cache = {}
componentWillReceiveProps: (nextProps) =>
@cache = {}
render: =>
div className: 'beatmapsets-search-filter',
if @props.title?
span className: 'beatmapsets-search-filter__header', @props.title
div className: 'beatmapsets-search-filter__items',
for option, i in @props.options
cssClasses = 'beatmapsets-search-filter__item'
cssClasses += ' beatmapsets-search-filter__item--active' if @selected(option.id)
text = option.name
if @props.name == 'general' && option.id == 'recommended' && @props.recommendedDifficulty?
text += " (#{osu.formatNumber(@props.recommendedDifficulty, 2)})"
a
key: i
href: @href(option)
className: cssClasses
'data-filter-value': option.id
onClick: @select
text
cast: (value) =>
BeatmapsetFilter.castFromString[@props.name]?(value) ? value ? null
href: ({ id }) =>
updatedFilter = {}
updatedFilter[@props.name] = @newSelection(id)
filters = _.assign {}, @props.filters.values, updatedFilter
osu.updateQueryString null, BeatmapsetFilter.queryParamsFromFilters(filters)
select: (e) =>
e.preventDefault()
controller.updateFilters "#{@props.name}": @newSelection(e.target.dataset.filterValue) ? null
# TODO: rename
newSelection: (id) =>
i = @cast(id)
if @props.multiselect
_(@currentSelection())[if @selected(i) then 'without' else 'concat'](i).sort().join('.')
else
if @selected(i) then BeatmapsetFilter.defaults[id] else i
selected: (i) =>
i in @currentSelection()
currentSelection: =>
@cache.currentSelection ?=
if @props.multiselect
_(@props.selected ? '')
.split('.')
.filter (s) =>
s in _.map(@props.options, 'id')
.value()
else
[@props.selected]
|
[
{
"context": "hr.setRequestHeader('Authorization', ('Token ' + 'fccb3a073f9e7e53e01838d4693d1302e5857cf3'))\n\n Backbone.sync.call(this, method, collec",
"end": 689,
"score": 0.9664257168769836,
"start": 649,
"tag": "PASSWORD",
"value": "fccb3a073f9e7e53e01838d4693d1302e5857cf3"
}
] | coffee/models/base/collection.coffee | zedam/backbone_chaplin_api | 0 | define [
'chaplin'
'config'
'backbone'
'models/base/model'
], (Chaplin, Config, Backbone, Model) ->
class Collection extends Chaplin.Collection
# Mixin a synchronization state machine.
# _(@prototype).extend Chaplin.SyncMachine
# initialize: ->
# super
# @on 'request', @beginSync
# @on 'sync', @finishSync
# @on 'error', @unsync
model: Model
parse: (response) ->
response.results
sync: (method, collection, options) ->
options = options || {}
options.beforeSend = (xhr) ->
@url = API_ROOT_URL + @url;
xhr.setRequestHeader('Authorization', ('Token ' + 'fccb3a073f9e7e53e01838d4693d1302e5857cf3'))
Backbone.sync.call(this, method, collection, options)
| 91414 | define [
'chaplin'
'config'
'backbone'
'models/base/model'
], (Chaplin, Config, Backbone, Model) ->
class Collection extends Chaplin.Collection
# Mixin a synchronization state machine.
# _(@prototype).extend Chaplin.SyncMachine
# initialize: ->
# super
# @on 'request', @beginSync
# @on 'sync', @finishSync
# @on 'error', @unsync
model: Model
parse: (response) ->
response.results
sync: (method, collection, options) ->
options = options || {}
options.beforeSend = (xhr) ->
@url = API_ROOT_URL + @url;
xhr.setRequestHeader('Authorization', ('Token ' + '<PASSWORD>'))
Backbone.sync.call(this, method, collection, options)
| true | define [
'chaplin'
'config'
'backbone'
'models/base/model'
], (Chaplin, Config, Backbone, Model) ->
class Collection extends Chaplin.Collection
# Mixin a synchronization state machine.
# _(@prototype).extend Chaplin.SyncMachine
# initialize: ->
# super
# @on 'request', @beginSync
# @on 'sync', @finishSync
# @on 'error', @unsync
model: Model
parse: (response) ->
response.results
sync: (method, collection, options) ->
options = options || {}
options.beforeSend = (xhr) ->
@url = API_ROOT_URL + @url;
xhr.setRequestHeader('Authorization', ('Token ' + 'PI:PASSWORD:<PASSWORD>END_PI'))
Backbone.sync.call(this, method, collection, options)
|
[
{
"context": "b) ->\n await KeyManager.generate_ecc { userid : \"tester@test.cc\" }, T.esc(defer(tmp), cb)\n km = tmp\n cb()\n\nexpo",
"end": 483,
"score": 0.9998769760131836,
"start": 469,
"tag": "EMAIL",
"value": "tester@test.cc"
},
{
"context": "----\n\nbcrypt_sig = \"\"\"-----BEGIN PGP MESSAGE-----\n\nowJ4nJvAy8zAxXhhd4KZ89+bbxhPH1iZxBBsyb62WikpP6VSyapaKTsVTKVl5qWn\nFhUUZeaVKFkpJaWkmqeYGlgYJyUZm6amJJsnmpklpViaG1tYJKcaGVmmJSabWySn\nmSvpKGXkF4N0AI1JSixO1cvMB4oBOfGZKUBRoHpnV6B6N0dncwtnN5D6UrCERYq5\nkVmikalhcqqlQaqlRZppcpplsqmJsXGymYGFgQFIYXFqUV5ibirIOclFlQUlSrU6\nSkCxsszkVJCLoXIl5ZklJalFuDSUVBaABMpTk+KheuOTMvNSgL4F6ihLLSrOzM9T\nsjIEqkwuyQTpNTS2NDMyMTMxMdVRSq0oyCxKjc8EqTA1NwO6y8BAR6mgKLVMySqv\nNCcH5J7CvHygLNCixHSgPcWZ6XmJJaVFqUq1nYwyLAyMXAxsrEygEGfg4hSAxcPj\nLg6GVdJc+ev6hFZIWG/OSv7Jxsy+4mm/uL1O9PePJhan7Y2DOZ0ccu4qM35/uzLd\n6EdfxHLucsZFYnc03yd++fYh5vqsPV9KhNtmTfzZd4RRYPqP1K3R995tX7BIm//p\nQbkEbdFMLuFujp7YhXWX/1QeORfRniTPd/7z6/SaI49OmjOe2mI4U7FdbvbFw//N\nzs92+tQVq8LcHTm5be/kmJKKFnXx9J1/OTc/jHxxOrvleHbOt/4vyRF31qxs8Tl0\n5mZj7jOez9e3/q+9OXNq+dPclxF3tLpNHhzatTintPu+rbbYl5j9i099OyDg+fHm\nrf+MJwz/S3Syv7Pze3/795qjpaJT3yxIuaYtP+2m5pzIeAA1rQep\n=h3a4\n-----END PGP MESSAGE-----\"\"\"\n\nexports.pgp_unbox_b",
"end": 2772,
"score": 0.9940549731254578,
"start": 1934,
"tag": "KEY",
"value": "owJ4nJvAy8zAxXhhd4KZ89+bbxhPH1iZxBBsyb62WikpP6VSyapaKTsVTKVl5qWn\nFhUUZeaVKFkpJaWkmqeYGlgYJyUZm6amJJsnmpklpViaG1tYJKcaGVmmJSabWySn\nmSvpKGXkF4N0AI1JSixO1cvMB4oBOfGZKUBRoHpnV6B6N0dncwtnN5D6UrCERYq5\nkVmikalhcqqlQaqlRZppcpplsqmJsXGymYGFgQFIYXFqUV5ibirIOclFlQUlSrU6\nSkCxsszkVJCLoXIl5ZklJalFuDSUVBaABMpTk+KheuOTMvNSgL4F6ihLLSrOzM9T\nsjIEqkwuyQTpNTS2NDMyMTMxMdVRSq0oyCxKjc8EqTA1NwO6y8BAR6mgKLVMySqv\nNCcH5J7CvHygLNCixHSgPcWZ6XmJJaVFqUq1nYwyLAyMXAxsrEygEGfg4hSAxcPj\nLg6GVdJc+ev6hFZIWG/OSv7Jxsy+4mm/uL1O9PePJhan7Y2DOZ0ccu4qM35/uzLd\n6EdfxHLucsZFYnc03yd++fYh5vqsPV9KhNtmTfzZd4RRYPqP1K3R995tX7BIm//p\nQbkEbdFMLuFujp7YhXWX/1QeORfRniTPd/7z6/SaI49OmjOe2mI4U7FdbvbFw//N\nzs92+tQVq8LcHTm5be/kmJKKFnXx9J1/OTc/jHxxOrvleHbOt/4vyRF31qxs8Tl0\n5mZj7jOez9e3/q+9OXNq+dPclxF3tLpNHhzatTintPu+rbbYl5j9i099OyDg+fHm\nrf+MJwz/S3Syv7Pze3/795qjpaJT3yxIuaYtP+2m5pzIeAA1rQep\n=h3a4"
},
{
"context": "ck\"\n exp = 1407614008\n rxx = new RegExp \"PGP key bde7d5083bb35edc7a66bd97388ce229fac78cf7 expired at #{exp} but we checked for time (\\\\d+)\"",
"end": 3688,
"score": 0.9994455575942993,
"start": 3648,
"tag": "KEY",
"value": "bde7d5083bb35edc7a66bd97388ce229fac78cf7"
},
{
"context": "armored = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmI0EWT7YPwEEAMpf5t3pNShLAEy1zSnhS9uTZwna5aVFcox5FPHkBHMKCpd7RjJp\nR0TfVM+kfvCjJlwpcn/uznVLU9TSsfiikDGo6Rltrj0lTqhz0zRBkwID1D76KhSG\nIYtoGO8JvA6OjRFZ31YUzOkdv7EioNHj0wNGhzyojmKtEFiKq7qP8/wNABEBAAG0\nKkZvb3IgODgzICh0ZXN0KSA8dGhlbWF4K2Zvb3I4ODNAZ21haWwuY29tPoi4BBMB\nAgAiBQJZPtg/AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAyPbtU2NuF\nvPf5A/4hfMgB2FKbiQTES8Ic4Qmr4FlNh64z+N0rDpmVNGPHUKcg2UbRJx54jV0o\nJJ6kWbTW2N5QVVoUZMv5RK1FGYMAhmT8xIJayobDj60ZkP/iiLFkwior8RxBd1Qu\nuZ+JeT2xMjOs1z6sVkwV7tBmyw6hAaVxTN8Wv3/6ciZ4ZYGN57iNBFk+2D8BBACf\ntcEN+wW06lWieM+CM9DOwr8DE7heQm/BfQgPSTIwYj/TqWLkpCFWOVM1CY2Qm2VP\nC22txzqctKmMvRhKVjsl5k/k8/TIOo/3mIOkgnS5O9t/CWLuXyM7IF3mNSeOfbIX\ne497NdXK/viEeemb02d5aa3b6uf28lJa2eN2adhbawARAQABiJ8EGAECAAkFAlk+\n2D8CGwwACgkQMj27VNjbhbz76QP/fLSo1QvegCPweqgVgn7FDN13ea9Fbid6qTKJ\nZSu083+zJnG3WYQClrLjuZ9gapN3MplRuAzIZANQ9zqlGXzwqbJXs+ifZez5vorH\n9fz+WhakUkUPfBG8xAsc7Nqm+Q5RyPEyklJuekk3U+Mw4R3LS1RDO06DVV/mqZ+/\njr19hIg=\n=05rq\n-----END PGP PUBLIC KEY BLOCK-----\"\"\"\n msg = \"\"\"",
"end": 4978,
"score": 0.9991254806518555,
"start": 4054,
"tag": "KEY",
"value": "mI0EWT7YPwEEAMpf5t3pNShLAEy1zSnhS9uTZwna5aVFcox5FPHkBHMKCpd7RjJp\nR0TfVM+kfvCjJlwpcn/uznVLU9TSsfiikDGo6Rltrj0lTqhz0zRBkwID1D76KhSG\nIYtoGO8JvA6OjRFZ31YUzOkdv7EioNHj0wNGhzyojmKtEFiKq7qP8/wNABEBAAG0\nKkZvb3IgODgzICh0ZXN0KSA8dGhlbWF4K2Zvb3I4ODNAZ21haWwuY29tPoi4BBMB\nAgAiBQJZPtg/AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAyPbtU2NuF\nvPf5A/4hfMgB2FKbiQTES8Ic4Qmr4FlNh64z+N0rDpmVNGPHUKcg2UbRJx54jV0o\nJJ6kWbTW2N5QVVoUZMv5RK1FGYMAhmT8xIJayobDj60ZkP/iiLFkwior8RxBd1Qu\nuZ+JeT2xMjOs1z6sVkwV7tBmyw6hAaVxTN8Wv3/6ciZ4ZYGN57iNBFk+2D8BBACf\ntcEN+wW06lWieM+CM9DOwr8DE7heQm/BfQgPSTIwYj/TqWLkpCFWOVM1CY2Qm2VP\nC22txzqctKmMvRhKVjsl5k/k8/TIOo/3mIOkgnS5O9t/CWLuXyM7IF3mNSeOfbIX\ne497NdXK/viEeemb02d5aa3b6uf28lJa2eN2adhbawARAQABiJ8EGAECAAkFAlk+\n2D8CGwwACgkQMj27VNjbhbz76QP/fLSo1QvegCPweqgVgn7FDN13ea9Fbid6qTKJ\nZSu083+zJnG3WYQClrLjuZ9gapN3MplRuAzIZANQ9zqlGXzwqbJXs+ifZez5vorH\n9fz+WhakUkUPfBG8xAsc7Nqm+Q5RyPEyklJuekk3U+Mw4R3LS1RDO06DVV/mqZ+/\njr19hIg=\n=05rq"
},
{
"context": "K-----\"\"\"\n msg = \"\"\"-----BEGIN PGP MESSAGE-----\n\nhIwDnASvG86Bd98BBACQ7QjQNuyQJ+gjHEydJ2gNFbGwtFvs5W2aNw8GMv2WY2gV\nmPa4BN9mShG++DnMxvaINV4WHb5GK87YgDc4nB1tva4OUPqt11xVzlLPfD643hGL\n3lkXk62j2LyLwFa4v8lk2UtRlg9X9L7hzMRljpwR8OkFuvtr4/zP0/JPI7LHpdLp\nAV+f1Uuw/9CZHw0nMDUDzW4W4Mr++B441RnjQjuIgSgD8croGDGJZkXHSwmrx6Ry\n852gPKVNSv4sQnAhRU9/n9Tk5vO1TK9QpM5eDVz6cTMUkFrvvEv5w7dC6hdgwRiE\nuiGkIyFRsW8GTZYQh1E7ygHUb83Du8bipi9LG0s+A0upqR4nxetAc3ZdghRwU3Zx\nVKstH2wTgdNPcUzzssRZP2N8AdfLKfouvzwBftbDUOK2OPtwSXP3fi507HfRwpau\ndjNjwGF6o+vS5VLnuE0Bd+Un59aJpFB3hf1EJJe7nNFqoV+rKAYXQzfhrcjbJR2Q\nImEb+DTF/QTLWdJHzDYtZtcaR5+OjySAoprWwBgFd/5jO7QxFAYsK0KB+qYORhPS\nmA8E2krlh4qhVzolYazAin4Q4qkbfatHS2UrWH21RlqL4RbbmxFmczCI9nR1BIuG\n8vYdAy54Dprka6JavrrBGBlJcf/19REwEoXrid7fJta3fXYQzGVm6cJXlsYAdXUP\n5txUdrUsv95jOM2VQxJn1CBlAVtwXRQ41UR476QAO52ShDMrzy1dCSewQIk2nrbZ\nrT3tA/jpRZBEamYqXQ67JqNsEqe9nfIn7PszKOoz3PaoLUOAIfIc0/XU6WzfldSS\nvog49ozvkIgTtkG+Yu1eHOKc1b1qEBz+9Gn2U6Dxh0F3uLyC30gPNaApCDX+4n1p\nbxLxH8ynQ0tN65Nog67RE8zzwhlifWLi4C6nO4ma02rqy/VaBT2BhnTZC6SZfmvQ\nKVz0tO9vcnWOkH1nA6iTJPxduAzCxDmVx3XaoVj9LPjajlROyWyMogdnZ5u0vP+l\nKn2YXxcsF30=\n=iWKX\n---",
"end": 6069,
"score": 0.9989243149757385,
"start": 5057,
"tag": "KEY",
"value": "hIwDnASvG86Bd98BBACQ7QjQNuyQJ+gjHEydJ2gNFbGwtFvs5W2aNw8GMv2WY2gV\nmPa4BN9mShG++DnMxvaINV4WHb5GK87YgDc4nB1tva4OUPqt11xVzlLPfD643hGL\n3lkXk62j2LyLwFa4v8lk2UtRlg9X9L7hzMRljpwR8OkFuvtr4/zP0/JPI7LHpdLp\nAV+f1Uuw/9CZHw0nMDUDzW4W4Mr++B441RnjQjuIgSgD8croGDGJZkXHSwmrx6Ry\n852gPKVNSv4sQnAhRU9/n9Tk5vO1TK9QpM5eDVz6cTMUkFrvvEv5w7dC6hdgwRiE\nuiGkIyFRsW8GTZYQh1E7ygHUb83Du8bipi9LG0s+A0upqR4nxetAc3ZdghRwU3Zx\nVKstH2wTgdNPcUzzssRZP2N8AdfLKfouvzwBftbDUOK2OPtwSXP3fi507HfRwpau\ndjNjwGF6o+vS5VLnuE0Bd+Un59aJpFB3hf1EJJe7nNFqoV+rKAYXQzfhrcjbJR2Q\nImEb+DTF/QTLWdJHzDYtZtcaR5+OjySAoprWwBgFd/5jO7QxFAYsK0KB+qYORhPS\nmA8E2krlh4qhVzolYazAin4Q4qkbfatHS2UrWH21RlqL4RbbmxFmczCI9nR1BIuG\n8vYdAy54Dprka6JavrrBGBlJcf/19REwEoXrid7fJta3fXYQzGVm6cJXlsYAdXUP\n5txUdrUsv95jOM2VQxJn1CBlAVtwXRQ41UR476QAO52ShDMrzy1dCSewQIk2nrbZ\nrT3tA/jpRZBEamYqXQ67JqNsEqe9nfIn7PszKOoz3PaoLUOAIfIc0/XU6WzfldSS\nvog49ozvkIgTtkG+Yu1eHOKc1b1qEBz+9Gn2U6Dxh0F3uLyC30gPNaApCDX+4n1p\nbxLxH8ynQ0tN65Nog67RE8zzwhlifWLi4C6nO4ma02rqy/VaBT2BhnTZC6SZfmvQ\nKVz0tO9vcnWOkH1nA6iTJPxduAzCxDmVx3Xao"
},
{
"context": "armored = \"\"\"-----BEGIN PGP PUBLIC KEY BLOCK-----\n\nmDMEXhzOfhYJKwYBBAHaRw8BAQdALvMNWLpZDyObyMZ3NhDU9xtJWaiN7CceDYZu\ns3GckS20C3Rlc3QgMzQxNzkziIsEExYIADMCGwMCHgECF4AWIQQh1dGN6/OQKfEe\nZRVVstYtBnUBsAUCXhzPQwQLCQgHAhUCBBYCAwAACgkQVbLWLQZ1AbBo1QD/avI6\npLxP7MAlIKCIaxkfIfEfk6zpXMZIthTtI7nq40AA/2hOX1zpVECY1QjleFV5/LH9\nRRouH+iAF7zFlXwhcAgKuDgEXhzOfhIKKwYBBAGXVQEFAQEHQEsigQS7wsbom9W3\nEjf7DpFRWRuX7XaKVGOmWS0FihkjAwEIB4h4BBgWCAAgFiEEIdXRjevzkCnxHmUV\nVbLWLQZ1AbAFAl4czn4CGwwACgkQVbLWLQZ1AbCKVAD8CFGlE6hdBxByaysXRPQI\nSXq9Tr+SFYXSESyuk1JXbSoBAILGzw56uJL2kXHGJDCJPXLnPH",
"end": 8817,
"score": 0.9893229603767395,
"start": 8363,
"tag": "KEY",
"value": "mDMEXhzOfhYJKwYBBAHaRw8BAQdALvMNWLpZDyObyMZ3NhDU9xtJWaiN7CceDYZu\ns3GckS20C3Rlc3QgMzQxNzkziIsEExYIADMCGwMCHgECF4AWIQQh1dGN6/OQKfEe\nZRVVstYtBnUBsAUCXhzPQwQLCQgHAhUCBBYCAwAACgkQVbLWLQZ1AbBo1QD/avI6\npLxP7MAlIKCIaxkfIfEfk6zpXMZIthTtI7nq40AA/2hOX1zpVECY1QjleFV5/LH9\nRRouH+iAF7zFlXwhcAgKuDgEXhzOfhIKKwYBBAGXVQEFAQEHQEsigQS7wsbom9W3\nEjf7DpFRWRuX7XaKVGOmWS0FihkjAwEIB4h4BBgWCAAgFiEEIdXRjevzkCnxHmUV\nVbLWLQZ1AbAFAl4czn4CGwwACgkQVbLWLQZ1AbCKVAD8CFGlE6hdBxByaysXRPQI"
},
{
"context": "n4CGwwACgkQVbLWLQZ1AbCKVAD8CFGlE6hdBxByaysXRPQI\nSXq9Tr+SFYXSESyuk1JXbSoBAILGzw56uJL2kXHGJDCJPXLnPHvTjqHvD8Uhe0l2\n5uEI\n=v83o\n-----END PGP PUBLIC KEY BLOCK-----\n \"\"",
"end": 8882,
"score": 0.6197854280471802,
"start": 8820,
"tag": "KEY",
"value": "q9Tr+SFYXSESyuk1JXbSoBAILGzw56uJL2kXHGJDCJPXLnPHvTjqHvD8Uhe0l2"
},
{
"context": "\"\"\n msg = \"\"\"-----BEGIN PGP MESSAGE-----\n\nowGbwMvMwCQWuumaLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZ",
"end": 8986,
"score": 0.5326123833656311,
"start": 8982,
"tag": "KEY",
"value": "MwCQ"
},
{
"context": "BEGIN PGP MESSAGE-----\n\nowGbwMvMwCQWuumaLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZMUU\nWRSvXux9/XmC5",
"end": 9003,
"score": 0.5439672470092773,
"start": 9001,
"tag": "KEY",
"value": "JJ"
},
{
"context": "IN PGP MESSAGE-----\n\nowGbwMvMwCQWuumaLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZMUU\nWRSvXux9/XmC5ke5",
"end": 9006,
"score": 0.5064435601234436,
"start": 9004,
"tag": "KEY",
"value": "HE"
},
{
"context": "PGP MESSAGE-----\n\nowGbwMvMwCQWuumaLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZMUU\nWRSvXux9/XmC5ke5VFG",
"end": 9009,
"score": 0.532308042049408,
"start": 9007,
"tag": "KEY",
"value": "52"
},
{
"context": "MESSAGE-----\n\nowGbwMvMwCQWuumaLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZMUU\nWRSvXux9/XmC5ke5VFGYHlYmkAYGLk4BmMhGc4Y/3LLGnwS",
"end": 9037,
"score": 0.5521820187568665,
"start": 9011,
"tag": "KEY",
"value": "UnNy8hXK84tyUrg6SlkYxJgYZM"
},
{
"context": "maLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZMUU\nWRSvXux9/XmC5ke5VFGYHlYmkAYGLk4BmMhGc4Y/3LLGnwSytTN6tUzzZ3P1/blw\nXmvNgZ5DfMo97yesefTiEiPDrMuu5fxvromt00zea3bahC2S46",
"end": 9104,
"score": 0.6380695700645447,
"start": 9040,
"tag": "KEY",
"value": "WRSvXux9/XmC5ke5VFGYHlYmkAYGLk4BmMhGc4Y/3LLGnwSytTN6tUzzZ3P1/blw"
},
{
"context": "VFGYHlYmkAYGLk4BmMhGc4Y/3LLGnwSytTN6tUzzZ3P1/blw\nXmvNgZ5DfMo97yesefTiEiPDrMuu5fxvromt00zea3bahC2S46bLbOW9CYpMZVrl\nn6ZzAAA=\n=+xbq\n-----END PGP MESSAGE-----\n \"\"\"\n a",
"end": 9169,
"score": 0.605934202671051,
"start": 9106,
"tag": "KEY",
"value": "mvNgZ5DfMo97yesefTiEiPDrMuu5fxvromt00zea3bahC2S46bLbOW9CYpMZVrl"
},
{
"context": "fTiEiPDrMuu5fxvromt00zea3bahC2S46bLbOW9CYpMZVrl\nn6ZzAAA=\n=+xbq\n-----END PGP MESSAGE-----\n \"\"\"\n await Ke",
"end": 9177,
"score": 0.5580390691757202,
"start": 9172,
"tag": "KEY",
"value": "ZzAAA"
}
] | test/files/sigeng.iced | samkenxstream/kbpgp | 464 | kbpgp = require '../../'
{armor,KeyManager,kb,util} = kbpgp
{keys} = require('../data/keys.iced')
{make_esc} = require 'iced-error'
{asyncify} = util
{unbox_decode,encode} = kb
hash = kbpgp.hash
km = null
msg = """
The night attendant, a B.U. sophomore,
rouses from the mare's-nest of his drowsy head
propped on The Meaning of Meaning.
He catwalks down our corridor.
"""
sig = null
se = null
exports.generate = (T,cb) ->
await KeyManager.generate_ecc { userid : "tester@test.cc" }, T.esc(defer(tmp), cb)
km = tmp
cb()
exports.box = (T,cb) ->
se = km.make_sig_eng()
await se.box msg, T.esc(defer(tmp), cb)
sig = tmp
await se.box msg, defer(err), { prefix : "foo" }
T.assert err?, "an error when using prefixes with PGP"
T.equal err.message, "prefixes cannot be used with PGP", "right error message"
cb()
exports.unbox = (T,cb) ->
[ err, raw ] = armor.decode sig.pgp
T.no_error err
await se.unbox raw, T.esc(defer(tmp), cb)
T.equal tmp.toString('utf8'), msg, "the right message came back out"
cb()
exports.pgp_get_unverified_payload = (T,cb) ->
await se.get_body_and_unverified_payload { armored : sig.pgp }, T.esc(defer(_, payload), cb)
T.equal payload.toString('utf8'), msg, "the right message came back out"
cb()
exports.kb_generate = (T,cb) ->
await kb.KeyManager.generate {}, T.esc(defer(tmp), cb)
km = tmp
cb()
exports.kb_box = (T,cb) ->
se = km.make_sig_eng()
await se.box msg, T.esc(defer(tmp), cb)
sig = tmp
cb()
exports.kb_unbox = (T,cb) ->
await se.unbox sig.armored, T.esc(defer(tmp), cb)
T.equal tmp.toString('utf8'), msg, "the right message came back out"
cb()
exports.kb_get_unverified_payload = (T,cb) ->
await se.get_body_and_unverified_payload { armored : sig.armored }, T.esc(defer(_, payload), cb)
T.equal payload.toString('utf8'), msg, "the right message came back out"
cb()
#------------------
bcrypt_sig = """-----BEGIN PGP MESSAGE-----
owJ4nJvAy8zAxXhhd4KZ89+bbxhPH1iZxBBsyb62WikpP6VSyapaKTsVTKVl5qWn
FhUUZeaVKFkpJaWkmqeYGlgYJyUZm6amJJsnmpklpViaG1tYJKcaGVmmJSabWySn
mSvpKGXkF4N0AI1JSixO1cvMB4oBOfGZKUBRoHpnV6B6N0dncwtnN5D6UrCERYq5
kVmikalhcqqlQaqlRZppcpplsqmJsXGymYGFgQFIYXFqUV5ibirIOclFlQUlSrU6
SkCxsszkVJCLoXIl5ZklJalFuDSUVBaABMpTk+KheuOTMvNSgL4F6ihLLSrOzM9T
sjIEqkwuyQTpNTS2NDMyMTMxMdVRSq0oyCxKjc8EqTA1NwO6y8BAR6mgKLVMySqv
NCcH5J7CvHygLNCixHSgPcWZ6XmJJaVFqUq1nYwyLAyMXAxsrEygEGfg4hSAxcPj
Lg6GVdJc+ev6hFZIWG/OSv7Jxsy+4mm/uL1O9PePJhan7Y2DOZ0ccu4qM35/uzLd
6EdfxHLucsZFYnc03yd++fYh5vqsPV9KhNtmTfzZd4RRYPqP1K3R995tX7BIm//p
QbkEbdFMLuFujp7YhXWX/1QeORfRniTPd/7z6/SaI49OmjOe2mI4U7FdbvbFw//N
zs92+tQVq8LcHTm5be/kmJKKFnXx9J1/OTc/jHxxOrvleHbOt/4vyRF31qxs8Tl0
5mZj7jOez9e3/q+9OXNq+dPclxF3tLpNHhzatTintPu+rbbYl5j9i099OyDg+fHm
rf+MJwz/S3Syv7Pze3/795qjpaJT3yxIuaYtP+2m5pzIeAA1rQep
=h3a4
-----END PGP MESSAGE-----"""
exports.pgp_unbox_bcrypt = (T,cb) ->
opts = { time_travel : true }
# First attempt to import bcrypt's key should warn about the expired subkeys
await KeyManager.import_from_armored_pgp { armored : keys.bcrypt }, T.esc(defer(km, warnings), cb)
w = (w for w in warnings.warnings() when not w.match /Skipping signature by another issuer/)
T.assert (w.length is 15), "15 expired signatures at time now"
await KeyManager.import_from_armored_pgp { armored : keys.bcrypt, opts }, T.esc(defer(km, warnings), cb)
w = (w for w in warnings.warnings() when not w.match /Skipping signature by another issuer/)
T.assert (w.length is 0), "no warnings aside from lots of cross-sigs"
sig_eng = km.make_sig_eng()
await sig_eng.unbox bcrypt_sig, defer err
T.assert err?, "an error came back"
exp = 1407614008
rxx = new RegExp "PGP key bde7d5083bb35edc7a66bd97388ce229fac78cf7 expired at #{exp} but we checked for time (\\d+)"
T.assert err.toString().match(rxx), "right error message (got: #{err.toString()}"
await sig_eng.unbox bcrypt_sig, T.esc(defer(), cb), { now : exp - 100 }
cb()
exports.sigeng_verify_encrypt_msg = (T,cb) ->
esc = make_esc cb, "sigeng_verify_encrypt_msg"
armored = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mI0EWT7YPwEEAMpf5t3pNShLAEy1zSnhS9uTZwna5aVFcox5FPHkBHMKCpd7RjJp
R0TfVM+kfvCjJlwpcn/uznVLU9TSsfiikDGo6Rltrj0lTqhz0zRBkwID1D76KhSG
IYtoGO8JvA6OjRFZ31YUzOkdv7EioNHj0wNGhzyojmKtEFiKq7qP8/wNABEBAAG0
KkZvb3IgODgzICh0ZXN0KSA8dGhlbWF4K2Zvb3I4ODNAZ21haWwuY29tPoi4BBMB
AgAiBQJZPtg/AhsDBgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRAyPbtU2NuF
vPf5A/4hfMgB2FKbiQTES8Ic4Qmr4FlNh64z+N0rDpmVNGPHUKcg2UbRJx54jV0o
JJ6kWbTW2N5QVVoUZMv5RK1FGYMAhmT8xIJayobDj60ZkP/iiLFkwior8RxBd1Qu
uZ+JeT2xMjOs1z6sVkwV7tBmyw6hAaVxTN8Wv3/6ciZ4ZYGN57iNBFk+2D8BBACf
tcEN+wW06lWieM+CM9DOwr8DE7heQm/BfQgPSTIwYj/TqWLkpCFWOVM1CY2Qm2VP
C22txzqctKmMvRhKVjsl5k/k8/TIOo/3mIOkgnS5O9t/CWLuXyM7IF3mNSeOfbIX
e497NdXK/viEeemb02d5aa3b6uf28lJa2eN2adhbawARAQABiJ8EGAECAAkFAlk+
2D8CGwwACgkQMj27VNjbhbz76QP/fLSo1QvegCPweqgVgn7FDN13ea9Fbid6qTKJ
ZSu083+zJnG3WYQClrLjuZ9gapN3MplRuAzIZANQ9zqlGXzwqbJXs+ifZez5vorH
9fz+WhakUkUPfBG8xAsc7Nqm+Q5RyPEyklJuekk3U+Mw4R3LS1RDO06DVV/mqZ+/
jr19hIg=
=05rq
-----END PGP PUBLIC KEY BLOCK-----"""
msg = """-----BEGIN PGP MESSAGE-----
hIwDnASvG86Bd98BBACQ7QjQNuyQJ+gjHEydJ2gNFbGwtFvs5W2aNw8GMv2WY2gV
mPa4BN9mShG++DnMxvaINV4WHb5GK87YgDc4nB1tva4OUPqt11xVzlLPfD643hGL
3lkXk62j2LyLwFa4v8lk2UtRlg9X9L7hzMRljpwR8OkFuvtr4/zP0/JPI7LHpdLp
AV+f1Uuw/9CZHw0nMDUDzW4W4Mr++B441RnjQjuIgSgD8croGDGJZkXHSwmrx6Ry
852gPKVNSv4sQnAhRU9/n9Tk5vO1TK9QpM5eDVz6cTMUkFrvvEv5w7dC6hdgwRiE
uiGkIyFRsW8GTZYQh1E7ygHUb83Du8bipi9LG0s+A0upqR4nxetAc3ZdghRwU3Zx
VKstH2wTgdNPcUzzssRZP2N8AdfLKfouvzwBftbDUOK2OPtwSXP3fi507HfRwpau
djNjwGF6o+vS5VLnuE0Bd+Un59aJpFB3hf1EJJe7nNFqoV+rKAYXQzfhrcjbJR2Q
ImEb+DTF/QTLWdJHzDYtZtcaR5+OjySAoprWwBgFd/5jO7QxFAYsK0KB+qYORhPS
mA8E2krlh4qhVzolYazAin4Q4qkbfatHS2UrWH21RlqL4RbbmxFmczCI9nR1BIuG
8vYdAy54Dprka6JavrrBGBlJcf/19REwEoXrid7fJta3fXYQzGVm6cJXlsYAdXUP
5txUdrUsv95jOM2VQxJn1CBlAVtwXRQ41UR476QAO52ShDMrzy1dCSewQIk2nrbZ
rT3tA/jpRZBEamYqXQ67JqNsEqe9nfIn7PszKOoz3PaoLUOAIfIc0/XU6WzfldSS
vog49ozvkIgTtkG+Yu1eHOKc1b1qEBz+9Gn2U6Dxh0F3uLyC30gPNaApCDX+4n1p
bxLxH8ynQ0tN65Nog67RE8zzwhlifWLi4C6nO4ma02rqy/VaBT2BhnTZC6SZfmvQ
KVz0tO9vcnWOkH1nA6iTJPxduAzCxDmVx3XaoVj9LPjajlROyWyMogdnZ5u0vP+l
Kn2YXxcsF30=
=iWKX
-----END PGP MESSAGE-----"""
await KeyManager.import_from_armored_pgp { armored }, esc defer km
sig_eng = km.make_sig_eng()
await sig_eng.unbox msg, defer err
T.assert err?, "should fail"
T.assert err.toString().indexOf("can't peform the operation -- maybe no secret key material (op_mask=2)") >= 0, "find right msg"
cb()
exports.kb_generate_with_prefix = (T,cb) ->
esc = make_esc cb
await kb.KeyManager.generate {}, esc defer pkm
psig_eng = pkm.make_sig_eng()
pmsg = Buffer.from("Of Man's First Disobedience, and the Fruit Of that Forbidden Tree, whose mortal taste", "utf8")
prefix = Buffer.from("milton-x-1", "utf8")
await psig_eng.box(pmsg, esc(defer(psig)), { prefix })
await psig_eng.unbox(psig.kb, esc(defer()))
await psig_eng.unbox(psig.kb, defer(err), { prefix : Buffer.from("should-fail") })
T.assert err?, "should get an error that we failed to verify with the wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
await asyncify unbox_decode({armored : psig.kb}), esc defer packet
delete packet.prefix
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
await psig_eng.unbox(armored, defer(err))
T.assert err?, "should fail since wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
packet.prefix = prefix
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
# should work
await psig_eng.unbox(armored, esc(defer()))
packet.prefix = Buffer.from("sidney-for-life-1")
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
await psig_eng.unbox(armored, defer(err))
T.assert err?, "should fail since wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
cb()
exports.assert_pgp_hash = (T, cb) ->
esc = make_esc cb
###
Keys and signature created using GnuPG with the following config:
personal-digest-preferences SHA1
cert-digest-algo SHA1
default-preference-list SHA1 AES256 AES192 AES ZLIB BZIP2 Uncompressed
###
armored = """-----BEGIN PGP PUBLIC KEY BLOCK-----
mDMEXhzOfhYJKwYBBAHaRw8BAQdALvMNWLpZDyObyMZ3NhDU9xtJWaiN7CceDYZu
s3GckS20C3Rlc3QgMzQxNzkziIsEExYIADMCGwMCHgECF4AWIQQh1dGN6/OQKfEe
ZRVVstYtBnUBsAUCXhzPQwQLCQgHAhUCBBYCAwAACgkQVbLWLQZ1AbBo1QD/avI6
pLxP7MAlIKCIaxkfIfEfk6zpXMZIthTtI7nq40AA/2hOX1zpVECY1QjleFV5/LH9
RRouH+iAF7zFlXwhcAgKuDgEXhzOfhIKKwYBBAGXVQEFAQEHQEsigQS7wsbom9W3
Ejf7DpFRWRuX7XaKVGOmWS0FihkjAwEIB4h4BBgWCAAgFiEEIdXRjevzkCnxHmUV
VbLWLQZ1AbAFAl4czn4CGwwACgkQVbLWLQZ1AbCKVAD8CFGlE6hdBxByaysXRPQI
SXq9Tr+SFYXSESyuk1JXbSoBAILGzw56uJL2kXHGJDCJPXLnPHvTjqHvD8Uhe0l2
5uEI
=v83o
-----END PGP PUBLIC KEY BLOCK-----
"""
msg = """-----BEGIN PGP MESSAGE-----
owGbwMvMwCQWuumaLlsp4wbG00JJDHEy52szUnNy8hXK84tyUrg6SlkYxJgYZMUU
WRSvXux9/XmC5ke5VFGYHlYmkAYGLk4BmMhGc4Y/3LLGnwSytTN6tUzzZ3P1/blw
XmvNgZ5DfMo97yesefTiEiPDrMuu5fxvromt00zea3bahC2S46bLbOW9CYpMZVrl
n6ZzAAA=
=+xbq
-----END PGP MESSAGE-----
"""
await KeyManager.import_from_armored_pgp { armored }, esc defer km
sig_eng = km.make_sig_eng()
await sig_eng.unbox msg, defer err, payload
T.no_error err, "should not fail without `assert_pgp_hash` callback"
T.equal payload.toString(), "hello world\n"
assert_pgp_hash = (hasher) ->
if hasher.algname is 'SHA1'
T.assert hasher.klass is hash.SHA1.klass
T.equal hasher.type, 2
new Error("signatures using SHA1 are not allowed")
await sig_eng.unbox msg, defer(err, payload), { assert_pgp_hash }
T.equal err?.message, "signatures using SHA1 are not allowed"
T.assert not payload?
cb null
| 90833 | kbpgp = require '../../'
{armor,KeyManager,kb,util} = kbpgp
{keys} = require('../data/keys.iced')
{make_esc} = require 'iced-error'
{asyncify} = util
{unbox_decode,encode} = kb
hash = kbpgp.hash
km = null
msg = """
The night attendant, a B.U. sophomore,
rouses from the mare's-nest of his drowsy head
propped on The Meaning of Meaning.
He catwalks down our corridor.
"""
sig = null
se = null
exports.generate = (T,cb) ->
await KeyManager.generate_ecc { userid : "<EMAIL>" }, T.esc(defer(tmp), cb)
km = tmp
cb()
exports.box = (T,cb) ->
se = km.make_sig_eng()
await se.box msg, T.esc(defer(tmp), cb)
sig = tmp
await se.box msg, defer(err), { prefix : "foo" }
T.assert err?, "an error when using prefixes with PGP"
T.equal err.message, "prefixes cannot be used with PGP", "right error message"
cb()
exports.unbox = (T,cb) ->
[ err, raw ] = armor.decode sig.pgp
T.no_error err
await se.unbox raw, T.esc(defer(tmp), cb)
T.equal tmp.toString('utf8'), msg, "the right message came back out"
cb()
exports.pgp_get_unverified_payload = (T,cb) ->
await se.get_body_and_unverified_payload { armored : sig.pgp }, T.esc(defer(_, payload), cb)
T.equal payload.toString('utf8'), msg, "the right message came back out"
cb()
exports.kb_generate = (T,cb) ->
await kb.KeyManager.generate {}, T.esc(defer(tmp), cb)
km = tmp
cb()
exports.kb_box = (T,cb) ->
se = km.make_sig_eng()
await se.box msg, T.esc(defer(tmp), cb)
sig = tmp
cb()
exports.kb_unbox = (T,cb) ->
await se.unbox sig.armored, T.esc(defer(tmp), cb)
T.equal tmp.toString('utf8'), msg, "the right message came back out"
cb()
exports.kb_get_unverified_payload = (T,cb) ->
await se.get_body_and_unverified_payload { armored : sig.armored }, T.esc(defer(_, payload), cb)
T.equal payload.toString('utf8'), msg, "the right message came back out"
cb()
#------------------
bcrypt_sig = """-----BEGIN PGP MESSAGE-----
<KEY>
-----END PGP MESSAGE-----"""
exports.pgp_unbox_bcrypt = (T,cb) ->
opts = { time_travel : true }
# First attempt to import bcrypt's key should warn about the expired subkeys
await KeyManager.import_from_armored_pgp { armored : keys.bcrypt }, T.esc(defer(km, warnings), cb)
w = (w for w in warnings.warnings() when not w.match /Skipping signature by another issuer/)
T.assert (w.length is 15), "15 expired signatures at time now"
await KeyManager.import_from_armored_pgp { armored : keys.bcrypt, opts }, T.esc(defer(km, warnings), cb)
w = (w for w in warnings.warnings() when not w.match /Skipping signature by another issuer/)
T.assert (w.length is 0), "no warnings aside from lots of cross-sigs"
sig_eng = km.make_sig_eng()
await sig_eng.unbox bcrypt_sig, defer err
T.assert err?, "an error came back"
exp = 1407614008
rxx = new RegExp "PGP key <KEY> expired at #{exp} but we checked for time (\\d+)"
T.assert err.toString().match(rxx), "right error message (got: #{err.toString()}"
await sig_eng.unbox bcrypt_sig, T.esc(defer(), cb), { now : exp - 100 }
cb()
exports.sigeng_verify_encrypt_msg = (T,cb) ->
esc = make_esc cb, "sigeng_verify_encrypt_msg"
armored = """-----BEGIN PGP PUBLIC KEY BLOCK-----
<KEY>
-----END PGP PUBLIC KEY BLOCK-----"""
msg = """-----BEGIN PGP MESSAGE-----
<KEY>Vj9LPjajlROyWyMogdnZ5u0vP+l
Kn2YXxcsF30=
=iWKX
-----END PGP MESSAGE-----"""
await KeyManager.import_from_armored_pgp { armored }, esc defer km
sig_eng = km.make_sig_eng()
await sig_eng.unbox msg, defer err
T.assert err?, "should fail"
T.assert err.toString().indexOf("can't peform the operation -- maybe no secret key material (op_mask=2)") >= 0, "find right msg"
cb()
exports.kb_generate_with_prefix = (T,cb) ->
esc = make_esc cb
await kb.KeyManager.generate {}, esc defer pkm
psig_eng = pkm.make_sig_eng()
pmsg = Buffer.from("Of Man's First Disobedience, and the Fruit Of that Forbidden Tree, whose mortal taste", "utf8")
prefix = Buffer.from("milton-x-1", "utf8")
await psig_eng.box(pmsg, esc(defer(psig)), { prefix })
await psig_eng.unbox(psig.kb, esc(defer()))
await psig_eng.unbox(psig.kb, defer(err), { prefix : Buffer.from("should-fail") })
T.assert err?, "should get an error that we failed to verify with the wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
await asyncify unbox_decode({armored : psig.kb}), esc defer packet
delete packet.prefix
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
await psig_eng.unbox(armored, defer(err))
T.assert err?, "should fail since wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
packet.prefix = prefix
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
# should work
await psig_eng.unbox(armored, esc(defer()))
packet.prefix = Buffer.from("sidney-for-life-1")
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
await psig_eng.unbox(armored, defer(err))
T.assert err?, "should fail since wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
cb()
exports.assert_pgp_hash = (T, cb) ->
esc = make_esc cb
###
Keys and signature created using GnuPG with the following config:
personal-digest-preferences SHA1
cert-digest-algo SHA1
default-preference-list SHA1 AES256 AES192 AES ZLIB BZIP2 Uncompressed
###
armored = """-----BEGIN PGP PUBLIC KEY BLOCK-----
<KEY>
SX<KEY>
5uEI
=v83o
-----END PGP PUBLIC KEY BLOCK-----
"""
msg = """-----BEGIN PGP MESSAGE-----
owGbwMv<KEY>WuumaLlsp4wbG00<KEY>D<KEY>y<KEY>sz<KEY>UU
<KEY>
X<KEY>
n6<KEY>=
=+xbq
-----END PGP MESSAGE-----
"""
await KeyManager.import_from_armored_pgp { armored }, esc defer km
sig_eng = km.make_sig_eng()
await sig_eng.unbox msg, defer err, payload
T.no_error err, "should not fail without `assert_pgp_hash` callback"
T.equal payload.toString(), "hello world\n"
assert_pgp_hash = (hasher) ->
if hasher.algname is 'SHA1'
T.assert hasher.klass is hash.SHA1.klass
T.equal hasher.type, 2
new Error("signatures using SHA1 are not allowed")
await sig_eng.unbox msg, defer(err, payload), { assert_pgp_hash }
T.equal err?.message, "signatures using SHA1 are not allowed"
T.assert not payload?
cb null
| true | kbpgp = require '../../'
{armor,KeyManager,kb,util} = kbpgp
{keys} = require('../data/keys.iced')
{make_esc} = require 'iced-error'
{asyncify} = util
{unbox_decode,encode} = kb
hash = kbpgp.hash
km = null
msg = """
The night attendant, a B.U. sophomore,
rouses from the mare's-nest of his drowsy head
propped on The Meaning of Meaning.
He catwalks down our corridor.
"""
sig = null
se = null
exports.generate = (T,cb) ->
await KeyManager.generate_ecc { userid : "PI:EMAIL:<EMAIL>END_PI" }, T.esc(defer(tmp), cb)
km = tmp
cb()
exports.box = (T,cb) ->
se = km.make_sig_eng()
await se.box msg, T.esc(defer(tmp), cb)
sig = tmp
await se.box msg, defer(err), { prefix : "foo" }
T.assert err?, "an error when using prefixes with PGP"
T.equal err.message, "prefixes cannot be used with PGP", "right error message"
cb()
exports.unbox = (T,cb) ->
[ err, raw ] = armor.decode sig.pgp
T.no_error err
await se.unbox raw, T.esc(defer(tmp), cb)
T.equal tmp.toString('utf8'), msg, "the right message came back out"
cb()
exports.pgp_get_unverified_payload = (T,cb) ->
await se.get_body_and_unverified_payload { armored : sig.pgp }, T.esc(defer(_, payload), cb)
T.equal payload.toString('utf8'), msg, "the right message came back out"
cb()
exports.kb_generate = (T,cb) ->
await kb.KeyManager.generate {}, T.esc(defer(tmp), cb)
km = tmp
cb()
exports.kb_box = (T,cb) ->
se = km.make_sig_eng()
await se.box msg, T.esc(defer(tmp), cb)
sig = tmp
cb()
exports.kb_unbox = (T,cb) ->
await se.unbox sig.armored, T.esc(defer(tmp), cb)
T.equal tmp.toString('utf8'), msg, "the right message came back out"
cb()
exports.kb_get_unverified_payload = (T,cb) ->
await se.get_body_and_unverified_payload { armored : sig.armored }, T.esc(defer(_, payload), cb)
T.equal payload.toString('utf8'), msg, "the right message came back out"
cb()
#------------------
bcrypt_sig = """-----BEGIN PGP MESSAGE-----
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----"""
exports.pgp_unbox_bcrypt = (T,cb) ->
opts = { time_travel : true }
# First attempt to import bcrypt's key should warn about the expired subkeys
await KeyManager.import_from_armored_pgp { armored : keys.bcrypt }, T.esc(defer(km, warnings), cb)
w = (w for w in warnings.warnings() when not w.match /Skipping signature by another issuer/)
T.assert (w.length is 15), "15 expired signatures at time now"
await KeyManager.import_from_armored_pgp { armored : keys.bcrypt, opts }, T.esc(defer(km, warnings), cb)
w = (w for w in warnings.warnings() when not w.match /Skipping signature by another issuer/)
T.assert (w.length is 0), "no warnings aside from lots of cross-sigs"
sig_eng = km.make_sig_eng()
await sig_eng.unbox bcrypt_sig, defer err
T.assert err?, "an error came back"
exp = 1407614008
rxx = new RegExp "PGP key PI:KEY:<KEY>END_PI expired at #{exp} but we checked for time (\\d+)"
T.assert err.toString().match(rxx), "right error message (got: #{err.toString()}"
await sig_eng.unbox bcrypt_sig, T.esc(defer(), cb), { now : exp - 100 }
cb()
exports.sigeng_verify_encrypt_msg = (T,cb) ->
esc = make_esc cb, "sigeng_verify_encrypt_msg"
armored = """-----BEGIN PGP PUBLIC KEY BLOCK-----
PI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----"""
msg = """-----BEGIN PGP MESSAGE-----
PI:KEY:<KEY>END_PIVj9LPjajlROyWyMogdnZ5u0vP+l
Kn2YXxcsF30=
=iWKX
-----END PGP MESSAGE-----"""
await KeyManager.import_from_armored_pgp { armored }, esc defer km
sig_eng = km.make_sig_eng()
await sig_eng.unbox msg, defer err
T.assert err?, "should fail"
T.assert err.toString().indexOf("can't peform the operation -- maybe no secret key material (op_mask=2)") >= 0, "find right msg"
cb()
exports.kb_generate_with_prefix = (T,cb) ->
esc = make_esc cb
await kb.KeyManager.generate {}, esc defer pkm
psig_eng = pkm.make_sig_eng()
pmsg = Buffer.from("Of Man's First Disobedience, and the Fruit Of that Forbidden Tree, whose mortal taste", "utf8")
prefix = Buffer.from("milton-x-1", "utf8")
await psig_eng.box(pmsg, esc(defer(psig)), { prefix })
await psig_eng.unbox(psig.kb, esc(defer()))
await psig_eng.unbox(psig.kb, defer(err), { prefix : Buffer.from("should-fail") })
T.assert err?, "should get an error that we failed to verify with the wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
await asyncify unbox_decode({armored : psig.kb}), esc defer packet
delete packet.prefix
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
await psig_eng.unbox(armored, defer(err))
T.assert err?, "should fail since wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
packet.prefix = prefix
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
# should work
await psig_eng.unbox(armored, esc(defer()))
packet.prefix = Buffer.from("sidney-for-life-1")
packed = packet.frame_packet()
sealed = encode.seal { obj : packed, dohash : false }
armored = sealed.toString('base64')
await psig_eng.unbox(armored, defer(err))
T.assert err?, "should fail since wrong prefix"
T.equal err.message, "Signature failed to verify", "right error"
cb()
exports.assert_pgp_hash = (T, cb) ->
esc = make_esc cb
###
Keys and signature created using GnuPG with the following config:
personal-digest-preferences SHA1
cert-digest-algo SHA1
default-preference-list SHA1 AES256 AES192 AES ZLIB BZIP2 Uncompressed
###
armored = """-----BEGIN PGP PUBLIC KEY BLOCK-----
PI:KEY:<KEY>END_PI
SXPI:KEY:<KEY>END_PI
5uEI
=v83o
-----END PGP PUBLIC KEY BLOCK-----
"""
msg = """-----BEGIN PGP MESSAGE-----
owGbwMvPI:KEY:<KEY>END_PIWuumaLlsp4wbG00PI:KEY:<KEY>END_PIDPI:KEY:<KEY>END_PIyPI:KEY:<KEY>END_PIszPI:KEY:<KEY>END_PIUU
PI:KEY:<KEY>END_PI
XPI:KEY:<KEY>END_PI
n6PI:KEY:<KEY>END_PI=
=+xbq
-----END PGP MESSAGE-----
"""
await KeyManager.import_from_armored_pgp { armored }, esc defer km
sig_eng = km.make_sig_eng()
await sig_eng.unbox msg, defer err, payload
T.no_error err, "should not fail without `assert_pgp_hash` callback"
T.equal payload.toString(), "hello world\n"
assert_pgp_hash = (hasher) ->
if hasher.algname is 'SHA1'
T.assert hasher.klass is hash.SHA1.klass
T.equal hasher.type, 2
new Error("signatures using SHA1 are not allowed")
await sig_eng.unbox msg, defer(err, payload), { assert_pgp_hash }
T.equal err?.message, "signatures using SHA1 are not allowed"
T.assert not payload?
cb null
|
[
{
"context": " conf.user = @_conf.user\n conf.pass = @_conf.pass\n\n @_transport = nodemailer.createTransport",
"end": 825,
"score": 0.9982308745384216,
"start": 814,
"tag": "PASSWORD",
"value": "@_conf.pass"
},
{
"context": " tasks =\n subject: async.apply(@_renderMessage, subjectTemplateName, context)\n body: ",
"end": 3044,
"score": 0.8312942385673523,
"start": 3031,
"tag": "USERNAME",
"value": "renderMessage"
},
{
"context": "lateName, context)\n body: async.apply(@_renderMessage, bodyTemplateName, context)\n html: asy",
"end": 3121,
"score": 0.8023359179496765,
"start": 3108,
"tag": "USERNAME",
"value": "renderMessage"
},
{
"context": "lateName, context)\n html: async.apply(@_renderMessage, htmlTemplateName, context)\n async.series(",
"end": 3195,
"score": 0.7701699137687683,
"start": 3182,
"tag": "USERNAME",
"value": "renderMessage"
}
] | src/server/notification/transport/smtp/index.coffee | LaPingvino/rizzoma | 88 | _ = require('underscore')
nodemailer = require('nodemailer')
util = require('util')
async = require('async')
Conf = require('../../../conf').Conf
NotificationTransport = require('../').NotificationTransport
NOTIFICATOR_TRANSPORT_SMTP = require('../../constants').NOTIFICATOR_TRANSPORT_SMTP
class SmtpTransport extends NotificationTransport
###
Уведомитель через Smtp
###
constructor: (smtpConf) ->
super(smtpConf)
getName: () -> NOTIFICATOR_TRANSPORT_SMTP
@getCommunicationType: () ->
return "email"
init: () ->
super()
conf = {}
conf.host = @_conf.host
conf.port = @_conf.port
conf.secureConnection = @_conf.ssl
conf.use_authentication = @_conf.use_authentication
conf.user = @_conf.user
conf.pass = @_conf.pass
@_transport = nodemailer.createTransport("SMTP", conf)
_getTemplatePath: (templateName) ->
return "#{super()}smtp/#{templateName}"
_escapeFromName: (fromName) ->
###
Удаляет плохие символы из имени отправителя
###
fromName = fromName.replace(/[<\\"]/g, '')
return fromName.replace(" ", "\xa0")
_getFromHeader: (context) ->
###
Возвращает заголовок from
###
return "" if not @_conf.from
fromName = if context.from and context.from.name then context.from.name else @_conf.fromName
if fromName
return "\"#{@_escapeFromName(fromName)}\xa0(Rizzoma)\" <#{@_conf.from}>"
else
return @_conf.from
_getReplyToHeader: (context) ->
###
Возвращает заголовок replyTo если подобное поле есть в контексте
context.replyTo может быть строкой или объектом типа UserModel
###
return null if not context.replyTo
return context.replyTo if _.isString(context.replyTo)
return context.replyTo.email if context.replyTo and context.replyTo.email
return null
_fillMailData: (user, res, context, type) ->
mailData =
to: user.email
html: res.html
body: res.body
from = @_getFromHeader(context)
mailData.from = from if from
replyTo = @_getReplyToHeader(context)
mailData.replyTo = replyTo if replyTo
mailData.attachments = context.attachments if context.attachments
mailData.headers = {} if not mailData.headers
mailData.headers['Subject'] = "=?utf-8?b?" + new Buffer(res.subject, "utf-8").toString("base64") + "?="
return mailData
notificateUser: (user, type, context, callback) ->
super(user, type, context, callback)
return callback(new Error('No user email'), null) if not user.email
subjectTemplateName = @_getTemplate(type, user.firstVisit, '_subject.txt')
htmlTemplateName = @_getTemplate(type, user.firstVisit, '_body.html')
bodyTemplateName = @_getTemplate(type, user.firstVisit, '_body.txt')
tasks =
subject: async.apply(@_renderMessage, subjectTemplateName, context)
body: async.apply(@_renderMessage, bodyTemplateName, context)
html: async.apply(@_renderMessage, htmlTemplateName, context)
async.series(tasks, (err, res) =>
return callback(err, null) if err
mailData = @_fillMailData(user, res, context, type)
@_transport.sendMail(mailData, (error, success) =>
isNewUser = if user.firstVisit then "existing user" else "new user"
from = if context.from then context.from.email else @_getFromHeader(context)
meta =
transport: @getName()
type: type
from: from
to: mailData.to
subject: res.subject
replyTo: mailData.replyTo
isNewUser: isNewUser
success: !!success
callback(error, meta)
)
)
close: () ->
module.exports.SmtpTransport = SmtpTransport
| 14005 | _ = require('underscore')
nodemailer = require('nodemailer')
util = require('util')
async = require('async')
Conf = require('../../../conf').Conf
NotificationTransport = require('../').NotificationTransport
NOTIFICATOR_TRANSPORT_SMTP = require('../../constants').NOTIFICATOR_TRANSPORT_SMTP
class SmtpTransport extends NotificationTransport
###
Уведомитель через Smtp
###
constructor: (smtpConf) ->
super(smtpConf)
getName: () -> NOTIFICATOR_TRANSPORT_SMTP
@getCommunicationType: () ->
return "email"
init: () ->
super()
conf = {}
conf.host = @_conf.host
conf.port = @_conf.port
conf.secureConnection = @_conf.ssl
conf.use_authentication = @_conf.use_authentication
conf.user = @_conf.user
conf.pass = <PASSWORD>
@_transport = nodemailer.createTransport("SMTP", conf)
_getTemplatePath: (templateName) ->
return "#{super()}smtp/#{templateName}"
_escapeFromName: (fromName) ->
###
Удаляет плохие символы из имени отправителя
###
fromName = fromName.replace(/[<\\"]/g, '')
return fromName.replace(" ", "\xa0")
_getFromHeader: (context) ->
###
Возвращает заголовок from
###
return "" if not @_conf.from
fromName = if context.from and context.from.name then context.from.name else @_conf.fromName
if fromName
return "\"#{@_escapeFromName(fromName)}\xa0(Rizzoma)\" <#{@_conf.from}>"
else
return @_conf.from
_getReplyToHeader: (context) ->
###
Возвращает заголовок replyTo если подобное поле есть в контексте
context.replyTo может быть строкой или объектом типа UserModel
###
return null if not context.replyTo
return context.replyTo if _.isString(context.replyTo)
return context.replyTo.email if context.replyTo and context.replyTo.email
return null
_fillMailData: (user, res, context, type) ->
mailData =
to: user.email
html: res.html
body: res.body
from = @_getFromHeader(context)
mailData.from = from if from
replyTo = @_getReplyToHeader(context)
mailData.replyTo = replyTo if replyTo
mailData.attachments = context.attachments if context.attachments
mailData.headers = {} if not mailData.headers
mailData.headers['Subject'] = "=?utf-8?b?" + new Buffer(res.subject, "utf-8").toString("base64") + "?="
return mailData
notificateUser: (user, type, context, callback) ->
super(user, type, context, callback)
return callback(new Error('No user email'), null) if not user.email
subjectTemplateName = @_getTemplate(type, user.firstVisit, '_subject.txt')
htmlTemplateName = @_getTemplate(type, user.firstVisit, '_body.html')
bodyTemplateName = @_getTemplate(type, user.firstVisit, '_body.txt')
tasks =
subject: async.apply(@_renderMessage, subjectTemplateName, context)
body: async.apply(@_renderMessage, bodyTemplateName, context)
html: async.apply(@_renderMessage, htmlTemplateName, context)
async.series(tasks, (err, res) =>
return callback(err, null) if err
mailData = @_fillMailData(user, res, context, type)
@_transport.sendMail(mailData, (error, success) =>
isNewUser = if user.firstVisit then "existing user" else "new user"
from = if context.from then context.from.email else @_getFromHeader(context)
meta =
transport: @getName()
type: type
from: from
to: mailData.to
subject: res.subject
replyTo: mailData.replyTo
isNewUser: isNewUser
success: !!success
callback(error, meta)
)
)
close: () ->
module.exports.SmtpTransport = SmtpTransport
| true | _ = require('underscore')
nodemailer = require('nodemailer')
util = require('util')
async = require('async')
Conf = require('../../../conf').Conf
NotificationTransport = require('../').NotificationTransport
NOTIFICATOR_TRANSPORT_SMTP = require('../../constants').NOTIFICATOR_TRANSPORT_SMTP
class SmtpTransport extends NotificationTransport
###
Уведомитель через Smtp
###
constructor: (smtpConf) ->
super(smtpConf)
getName: () -> NOTIFICATOR_TRANSPORT_SMTP
@getCommunicationType: () ->
return "email"
init: () ->
super()
conf = {}
conf.host = @_conf.host
conf.port = @_conf.port
conf.secureConnection = @_conf.ssl
conf.use_authentication = @_conf.use_authentication
conf.user = @_conf.user
conf.pass = PI:PASSWORD:<PASSWORD>END_PI
@_transport = nodemailer.createTransport("SMTP", conf)
_getTemplatePath: (templateName) ->
return "#{super()}smtp/#{templateName}"
_escapeFromName: (fromName) ->
###
Удаляет плохие символы из имени отправителя
###
fromName = fromName.replace(/[<\\"]/g, '')
return fromName.replace(" ", "\xa0")
_getFromHeader: (context) ->
###
Возвращает заголовок from
###
return "" if not @_conf.from
fromName = if context.from and context.from.name then context.from.name else @_conf.fromName
if fromName
return "\"#{@_escapeFromName(fromName)}\xa0(Rizzoma)\" <#{@_conf.from}>"
else
return @_conf.from
_getReplyToHeader: (context) ->
###
Возвращает заголовок replyTo если подобное поле есть в контексте
context.replyTo может быть строкой или объектом типа UserModel
###
return null if not context.replyTo
return context.replyTo if _.isString(context.replyTo)
return context.replyTo.email if context.replyTo and context.replyTo.email
return null
_fillMailData: (user, res, context, type) ->
mailData =
to: user.email
html: res.html
body: res.body
from = @_getFromHeader(context)
mailData.from = from if from
replyTo = @_getReplyToHeader(context)
mailData.replyTo = replyTo if replyTo
mailData.attachments = context.attachments if context.attachments
mailData.headers = {} if not mailData.headers
mailData.headers['Subject'] = "=?utf-8?b?" + new Buffer(res.subject, "utf-8").toString("base64") + "?="
return mailData
notificateUser: (user, type, context, callback) ->
super(user, type, context, callback)
return callback(new Error('No user email'), null) if not user.email
subjectTemplateName = @_getTemplate(type, user.firstVisit, '_subject.txt')
htmlTemplateName = @_getTemplate(type, user.firstVisit, '_body.html')
bodyTemplateName = @_getTemplate(type, user.firstVisit, '_body.txt')
tasks =
subject: async.apply(@_renderMessage, subjectTemplateName, context)
body: async.apply(@_renderMessage, bodyTemplateName, context)
html: async.apply(@_renderMessage, htmlTemplateName, context)
async.series(tasks, (err, res) =>
return callback(err, null) if err
mailData = @_fillMailData(user, res, context, type)
@_transport.sendMail(mailData, (error, success) =>
isNewUser = if user.firstVisit then "existing user" else "new user"
from = if context.from then context.from.email else @_getFromHeader(context)
meta =
transport: @getName()
type: type
from: from
to: mailData.to
subject: res.subject
replyTo: mailData.replyTo
isNewUser: isNewUser
success: !!success
callback(error, meta)
)
)
close: () ->
module.exports.SmtpTransport = SmtpTransport
|
[
{
"context": "\n xml = render('artists')\n models: [{id: 'andy-warhol'}, {id: 'roy-lichtenstein'}]\n sd: APP",
"end": 1001,
"score": 0.6637818813323975,
"start": 997,
"tag": "NAME",
"value": "andy"
},
{
"context": "xml = render('artists')\n models: [{id: 'andy-warhol'}, {id: 'roy-lichtenstein'}]\n sd: APP_URL: '",
"end": 1008,
"score": 0.4784482717514038,
"start": 1002,
"tag": "NAME",
"value": "warhol"
},
{
"context": "tists')\n models: [{id: 'andy-warhol'}, {id: 'roy-lichtenstein'}]\n sd: APP_URL: 'www.artsy.net'\n _: _\n",
"end": 1034,
"score": 0.8755232691764832,
"start": 1018,
"tag": "NAME",
"value": "roy-lichtenstein"
},
{
"context": "'\n xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein'\n xml.should.containEql 'www.arts",
"end": 1417,
"score": 0.724104106426239,
"start": 1414,
"tag": "NAME",
"value": "roy"
},
{
"context": " xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein'\n xml.should.containEql 'www.artsy.net/",
"end": 1423,
"score": 0.4256032109260559,
"start": 1418,
"tag": "USERNAME",
"value": "licht"
},
{
"context": ".should.containEql 'www.artsy.net/artist/roy-lichtenstein'\n xml.should.containEql 'www.artsy.net/artist/",
"end": 1430,
"score": 0.4219411611557007,
"start": 1423,
"tag": "NAME",
"value": "enstein"
},
{
"context": "'\n xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/shows'\n xml.should.containEql 'ww",
"end": 1483,
"score": 0.7259411811828613,
"start": 1480,
"tag": "NAME",
"value": "roy"
},
{
"context": "'\n xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/related-artists'\n xml.should.cont",
"end": 1555,
"score": 0.6532490849494934,
"start": 1552,
"tag": "NAME",
"value": "roy"
},
{
"context": "tsy.net'\n xml.should.containEql 'www.artsy.net/alessandra'\n\ndescribe 'shows sitemap template', ->\n\n it 're",
"end": 5119,
"score": 0.9993417859077454,
"start": 5109,
"tag": "USERNAME",
"value": "alessandra"
}
] | desktop/apps/sitemaps/test/templates.coffee | dblock/force | 0 | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
moment = require 'moment'
{ fabricate } = require 'antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
Artwork = require '../../../models/artwork'
Section = require '../../../models/section'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'articles template', ->
it 'renders article urls', ->
xml = render('articles')
slugs: ['artsy-editorial-1', 'artsy-editorial-2']
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/article/artsy-editorial-1'
xml.should.containEql 'www.artsy.net/article/artsy-editorial-2'
describe 'artists template', ->
it 'renders artist pages and related links', ->
xml = render('artists')
models: [{id: 'andy-warhol'}, {id: 'roy-lichtenstein'}]
sd: APP_URL: 'www.artsy.net'
_: _
xml.should.containEql 'www.artsy.net/artist/andy-warhol'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/shows'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/related-artists'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/auction-results'
xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein'
xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/shows'
xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/related-artists'
xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/auction-results'
describe 'cities sitemap template', ->
it 'renders the correct city show URLs', ->
xml = render('cities')
citySlugs: ['new-york', 'tokyo']
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/shows/new-york'
xml.should.containEql 'www.artsy.net/shows/tokyo'
describe 'fairs sitemap template', ->
it 'renders the correct fair URLs', ->
xml = render('fairs')
models: [fabricate 'fair', has_full_feature: true]
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/the-armory-show'
xml.should.containEql 'www.artsy.net/the-armory-show/browse/booths'
xml.should.containEql 'www.artsy.net/the-armory-show/articles'
xml.should.containEql 'www.artsy.net/the-armory-show/info'
describe 'features sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('features')
models: [fabricate 'feature']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/feature/bitty-the-cat'
describe 'gene sitemap template', ->
it 'renders the correct gene URLs', ->
xml = render('genes')
models: [fabricate 'gene']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/gene/pop-art'
describe 'feature sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('features')
models: [fabricate 'feature']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/feature/bitty-the-cat'
describe 'misc sitemap template', ->
it 'renders the correct misc URLs', ->
xml = render('misc')
sd: APP_URL: 'www.artsy.net'
xml.should.containEql '<loc>www.artsy.net</loc><priority>1</priority>'
xml.should.containEql 'www.artsy.net/about'
xml.should.containEql '/press/in-the-media'
xml.should.containEql '/press/press-releases'
xml.should.containEql '/collect'
xml.should.containEql '/log_in'
xml.should.containEql '/security'
xml.should.containEql '/privacy'
xml.should.containEql '/shows'
xml.should.containEql '/artists'
xml.should.containEql '/categories'
xml.should.containEql '/sign_up'
xml.should.containEql '/terms'
describe 'news sitemap template', ->
it 'renders article info', ->
xml = render('news_sitemap')
articles: [new Article fabricate 'article']
xml.should.containEql 'https://www.artsy.net/article/editorial-on-the-heels-of-a-stellar-year'
xml.should.containEql '<news:name>Artsy</news:name>'
xml.should.containEql '2014-09-24T23:24:54.000Z'
xml.should.containEql 'On The Heels of A Stellar Year in the West, Sterling Ruby Makes His Vivid Mark on Asia'
describe 'partners sitemap template', ->
it 'renders the correct partner URLs', ->
xml = render('partners')
models: [fabricate 'partner']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql '<loc>www.artsy.net/gagosian'
xml.should.containEql '/shows'
xml.should.containEql '/artists'
xml.should.containEql '/articles'
xml.should.containEql '/contact'
xml.should.containEql '/shop'
xml.should.containEql '/collection'
xml.should.containEql '/about'
describe 'profiles sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('profiles')
models: [fabricate 'profile']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/alessandra'
describe 'shows sitemap template', ->
it 'renders the correct show URLs', ->
xml = render('shows')
models: [fabricate 'show']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/show/gagosian-gallery-inez-and-vinoodh'
describe 'video sitemap template', ->
it 'renders the correct video info', ->
xml = render('video')
articles: new Articles fabricate 'article', published_at: '2014-09-02', sections: [
type: 'video'
url: 'http://youtube.com/video'
]
sd: APP_URL: 'www.artsy.net'
moment: moment
xml.should.containEql 'www.artsy.net/article/editorial-on-the-heels-of-a-stellar-year'
xml.should.containEql '<video:player_loc>http://youtube.com/video</video:player_loc>'
xml.should.containEql '2014-09-02'
| 140708 | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
moment = require 'moment'
{ fabricate } = require 'antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
Artwork = require '../../../models/artwork'
Section = require '../../../models/section'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'articles template', ->
it 'renders article urls', ->
xml = render('articles')
slugs: ['artsy-editorial-1', 'artsy-editorial-2']
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/article/artsy-editorial-1'
xml.should.containEql 'www.artsy.net/article/artsy-editorial-2'
describe 'artists template', ->
it 'renders artist pages and related links', ->
xml = render('artists')
models: [{id: '<NAME>-<NAME>'}, {id: '<NAME>'}]
sd: APP_URL: 'www.artsy.net'
_: _
xml.should.containEql 'www.artsy.net/artist/andy-warhol'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/shows'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/related-artists'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/auction-results'
xml.should.containEql 'www.artsy.net/artist/<NAME>-licht<NAME>'
xml.should.containEql 'www.artsy.net/artist/<NAME>-lichtenstein/shows'
xml.should.containEql 'www.artsy.net/artist/<NAME>-lichtenstein/related-artists'
xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/auction-results'
describe 'cities sitemap template', ->
it 'renders the correct city show URLs', ->
xml = render('cities')
citySlugs: ['new-york', 'tokyo']
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/shows/new-york'
xml.should.containEql 'www.artsy.net/shows/tokyo'
describe 'fairs sitemap template', ->
it 'renders the correct fair URLs', ->
xml = render('fairs')
models: [fabricate 'fair', has_full_feature: true]
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/the-armory-show'
xml.should.containEql 'www.artsy.net/the-armory-show/browse/booths'
xml.should.containEql 'www.artsy.net/the-armory-show/articles'
xml.should.containEql 'www.artsy.net/the-armory-show/info'
describe 'features sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('features')
models: [fabricate 'feature']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/feature/bitty-the-cat'
describe 'gene sitemap template', ->
it 'renders the correct gene URLs', ->
xml = render('genes')
models: [fabricate 'gene']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/gene/pop-art'
describe 'feature sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('features')
models: [fabricate 'feature']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/feature/bitty-the-cat'
describe 'misc sitemap template', ->
it 'renders the correct misc URLs', ->
xml = render('misc')
sd: APP_URL: 'www.artsy.net'
xml.should.containEql '<loc>www.artsy.net</loc><priority>1</priority>'
xml.should.containEql 'www.artsy.net/about'
xml.should.containEql '/press/in-the-media'
xml.should.containEql '/press/press-releases'
xml.should.containEql '/collect'
xml.should.containEql '/log_in'
xml.should.containEql '/security'
xml.should.containEql '/privacy'
xml.should.containEql '/shows'
xml.should.containEql '/artists'
xml.should.containEql '/categories'
xml.should.containEql '/sign_up'
xml.should.containEql '/terms'
describe 'news sitemap template', ->
it 'renders article info', ->
xml = render('news_sitemap')
articles: [new Article fabricate 'article']
xml.should.containEql 'https://www.artsy.net/article/editorial-on-the-heels-of-a-stellar-year'
xml.should.containEql '<news:name>Artsy</news:name>'
xml.should.containEql '2014-09-24T23:24:54.000Z'
xml.should.containEql 'On The Heels of A Stellar Year in the West, Sterling Ruby Makes His Vivid Mark on Asia'
describe 'partners sitemap template', ->
it 'renders the correct partner URLs', ->
xml = render('partners')
models: [fabricate 'partner']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql '<loc>www.artsy.net/gagosian'
xml.should.containEql '/shows'
xml.should.containEql '/artists'
xml.should.containEql '/articles'
xml.should.containEql '/contact'
xml.should.containEql '/shop'
xml.should.containEql '/collection'
xml.should.containEql '/about'
describe 'profiles sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('profiles')
models: [fabricate 'profile']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/alessandra'
describe 'shows sitemap template', ->
it 'renders the correct show URLs', ->
xml = render('shows')
models: [fabricate 'show']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/show/gagosian-gallery-inez-and-vinoodh'
describe 'video sitemap template', ->
it 'renders the correct video info', ->
xml = render('video')
articles: new Articles fabricate 'article', published_at: '2014-09-02', sections: [
type: 'video'
url: 'http://youtube.com/video'
]
sd: APP_URL: 'www.artsy.net'
moment: moment
xml.should.containEql 'www.artsy.net/article/editorial-on-the-heels-of-a-stellar-year'
xml.should.containEql '<video:player_loc>http://youtube.com/video</video:player_loc>'
xml.should.containEql '2014-09-02'
| true | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
moment = require 'moment'
{ fabricate } = require 'antigravity'
Article = require '../../../models/article'
Articles = require '../../../collections/articles'
Artwork = require '../../../models/artwork'
Section = require '../../../models/section'
render = (templateName) ->
filename = path.resolve __dirname, "../templates/#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'articles template', ->
it 'renders article urls', ->
xml = render('articles')
slugs: ['artsy-editorial-1', 'artsy-editorial-2']
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/article/artsy-editorial-1'
xml.should.containEql 'www.artsy.net/article/artsy-editorial-2'
describe 'artists template', ->
it 'renders artist pages and related links', ->
xml = render('artists')
models: [{id: 'PI:NAME:<NAME>END_PI-PI:NAME:<NAME>END_PI'}, {id: 'PI:NAME:<NAME>END_PI'}]
sd: APP_URL: 'www.artsy.net'
_: _
xml.should.containEql 'www.artsy.net/artist/andy-warhol'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/shows'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/related-artists'
xml.should.containEql 'www.artsy.net/artist/andy-warhol/auction-results'
xml.should.containEql 'www.artsy.net/artist/PI:NAME:<NAME>END_PI-lichtPI:NAME:<NAME>END_PI'
xml.should.containEql 'www.artsy.net/artist/PI:NAME:<NAME>END_PI-lichtenstein/shows'
xml.should.containEql 'www.artsy.net/artist/PI:NAME:<NAME>END_PI-lichtenstein/related-artists'
xml.should.containEql 'www.artsy.net/artist/roy-lichtenstein/auction-results'
describe 'cities sitemap template', ->
it 'renders the correct city show URLs', ->
xml = render('cities')
citySlugs: ['new-york', 'tokyo']
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/shows/new-york'
xml.should.containEql 'www.artsy.net/shows/tokyo'
describe 'fairs sitemap template', ->
it 'renders the correct fair URLs', ->
xml = render('fairs')
models: [fabricate 'fair', has_full_feature: true]
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/the-armory-show'
xml.should.containEql 'www.artsy.net/the-armory-show/browse/booths'
xml.should.containEql 'www.artsy.net/the-armory-show/articles'
xml.should.containEql 'www.artsy.net/the-armory-show/info'
describe 'features sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('features')
models: [fabricate 'feature']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/feature/bitty-the-cat'
describe 'gene sitemap template', ->
it 'renders the correct gene URLs', ->
xml = render('genes')
models: [fabricate 'gene']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/gene/pop-art'
describe 'feature sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('features')
models: [fabricate 'feature']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/feature/bitty-the-cat'
describe 'misc sitemap template', ->
it 'renders the correct misc URLs', ->
xml = render('misc')
sd: APP_URL: 'www.artsy.net'
xml.should.containEql '<loc>www.artsy.net</loc><priority>1</priority>'
xml.should.containEql 'www.artsy.net/about'
xml.should.containEql '/press/in-the-media'
xml.should.containEql '/press/press-releases'
xml.should.containEql '/collect'
xml.should.containEql '/log_in'
xml.should.containEql '/security'
xml.should.containEql '/privacy'
xml.should.containEql '/shows'
xml.should.containEql '/artists'
xml.should.containEql '/categories'
xml.should.containEql '/sign_up'
xml.should.containEql '/terms'
describe 'news sitemap template', ->
it 'renders article info', ->
xml = render('news_sitemap')
articles: [new Article fabricate 'article']
xml.should.containEql 'https://www.artsy.net/article/editorial-on-the-heels-of-a-stellar-year'
xml.should.containEql '<news:name>Artsy</news:name>'
xml.should.containEql '2014-09-24T23:24:54.000Z'
xml.should.containEql 'On The Heels of A Stellar Year in the West, Sterling Ruby Makes His Vivid Mark on Asia'
describe 'partners sitemap template', ->
it 'renders the correct partner URLs', ->
xml = render('partners')
models: [fabricate 'partner']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql '<loc>www.artsy.net/gagosian'
xml.should.containEql '/shows'
xml.should.containEql '/artists'
xml.should.containEql '/articles'
xml.should.containEql '/contact'
xml.should.containEql '/shop'
xml.should.containEql '/collection'
xml.should.containEql '/about'
describe 'profiles sitemap template', ->
it 'renders the correct feature URLs', ->
xml = render('profiles')
models: [fabricate 'profile']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/alessandra'
describe 'shows sitemap template', ->
it 'renders the correct show URLs', ->
xml = render('shows')
models: [fabricate 'show']
_: _
sd: APP_URL: 'www.artsy.net'
xml.should.containEql 'www.artsy.net/show/gagosian-gallery-inez-and-vinoodh'
describe 'video sitemap template', ->
it 'renders the correct video info', ->
xml = render('video')
articles: new Articles fabricate 'article', published_at: '2014-09-02', sections: [
type: 'video'
url: 'http://youtube.com/video'
]
sd: APP_URL: 'www.artsy.net'
moment: moment
xml.should.containEql 'www.artsy.net/article/editorial-on-the-heels-of-a-stellar-year'
xml.should.containEql '<video:player_loc>http://youtube.com/video</video:player_loc>'
xml.should.containEql '2014-09-02'
|
[
{
"context": "ck for ambiguous div operator in regexes\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n#-",
"end": 94,
"score": 0.9998031854629517,
"start": 83,
"tag": "NAME",
"value": "Matt DuVall"
}
] | src/rules/no-div-regex.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to check for ambiguous div operator in regexes
# @author Matt DuVall <http://www.mattduvall.com>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'disallow division operators explicitly at the beginning of regular expressions'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-div-regex'
fixable: 'code'
schema: []
messages:
unexpected: "A regular expression literal can be confused with '/='."
create: (context) ->
sourceCode = context.getSourceCode()
Literal: (node) ->
token = sourceCode.getFirstToken node
if (
token.type is 'RegularExpression' and
token.value[1] is '=' and
node.delimiter isnt '///'
)
context.report {
node
messageId: 'unexpected'
fix: (fixer) ->
fixer.replaceTextRange(
[token.range[0] + 1, token.range[0] + 2]
'[=]'
)
}
| 191204 | ###*
# @fileoverview Rule to check for ambiguous div operator in regexes
# @author <NAME> <http://www.mattduvall.com>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'disallow division operators explicitly at the beginning of regular expressions'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-div-regex'
fixable: 'code'
schema: []
messages:
unexpected: "A regular expression literal can be confused with '/='."
create: (context) ->
sourceCode = context.getSourceCode()
Literal: (node) ->
token = sourceCode.getFirstToken node
if (
token.type is 'RegularExpression' and
token.value[1] is '=' and
node.delimiter isnt '///'
)
context.report {
node
messageId: 'unexpected'
fix: (fixer) ->
fixer.replaceTextRange(
[token.range[0] + 1, token.range[0] + 2]
'[=]'
)
}
| true | ###*
# @fileoverview Rule to check for ambiguous div operator in regexes
# @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com>
###
'use strict'
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description:
'disallow division operators explicitly at the beginning of regular expressions'
category: 'Best Practices'
recommended: no
url: 'https://eslint.org/docs/rules/no-div-regex'
fixable: 'code'
schema: []
messages:
unexpected: "A regular expression literal can be confused with '/='."
create: (context) ->
sourceCode = context.getSourceCode()
Literal: (node) ->
token = sourceCode.getFirstToken node
if (
token.type is 'RegularExpression' and
token.value[1] is '=' and
node.delimiter isnt '///'
)
context.report {
node
messageId: 'unexpected'
fix: (fixer) ->
fixer.replaceTextRange(
[token.range[0] + 1, token.range[0] + 2]
'[=]'
)
}
|
[
{
"context": "ta: (key) ->\n return false unless key\n key = parseName key\n @els.some (el) -> el.dataset and key of e",
"end": 175,
"score": 0.796818196773529,
"start": 166,
"tag": "KEY",
"value": "parseName"
}
] | src/coffee/kernel/data/has-data.coffee | oatw/luda | 183 | import luda from '../base/luda.coffee'
import parseName from './helpers/parse-name.coffee'
luda.include
hasData: (key) ->
return false unless key
key = parseName key
@els.some (el) -> el.dataset and key of el.dataset | 171523 | import luda from '../base/luda.coffee'
import parseName from './helpers/parse-name.coffee'
luda.include
hasData: (key) ->
return false unless key
key = <KEY> key
@els.some (el) -> el.dataset and key of el.dataset | true | import luda from '../base/luda.coffee'
import parseName from './helpers/parse-name.coffee'
luda.include
hasData: (key) ->
return false unless key
key = PI:KEY:<KEY>END_PI key
@els.some (el) -> el.dataset and key of el.dataset |
[
{
"context": " searchAct = { type: \"search\" }\n addr = \"Class@component.example.com/instance\"\n\n readObj = {a:\"foo\", b:2}\n (",
"end": 1769,
"score": 0.9964660406112671,
"start": 1742,
"tag": "EMAIL",
"value": "Class@component.example.com"
}
] | spec/Serializer.spec.coffee | flosse/node-xmpp-joap | 0 | chai = require 'chai'
expect = chai.expect
describe "Serializer", ->
Serializer = require "../src/Serializer"
ltx = require "ltx"
describe "serialize", ->
it "serializes basic data types", ->
(expect Serializer.serialize null ).to.equal ""
(expect Serializer.serialize undefined ).to.equal ""
(expect Serializer.serialize("foo").toString()).to.eql "<string>foo</string>"
(expect Serializer.serialize(2).toString()).to.eql ltx.parse("<int>2</int>").toString()
(expect Serializer.serialize(-0.3).toString()).to.deep.eql ltx.parse("<double>-0.3</double>").toString()
(expect Serializer.serialize(true).toString()).to.deep.eql ltx.parse("<boolean>1</boolean>").toString()
(expect Serializer.serialize([]).toString()).to.eql ltx.parse("<array><data></data></array>").toString()
(expect Serializer.serialize(["x", -0.35, false]).toString()).to.eql ltx.parse("<array><data>" +
"<value><string>x</string></value><value><double>-0.35</double></value><value>" +
"<boolean>0</boolean></value></data></array>").toString()
(expect Serializer.serialize({a:"foo", b:["bar"]}).toString()).to.eql ltx.parse("<struct>"+
"<member><name>a</name><value><string>foo</string></value></member>" +
"<member><name>b</name>" +
"<value><array><data><value><string>bar</string></value></data></array>" +
"</value></member></struct>").toString()
it "serializes result attributes", ->
descAct = { type: "describe" }
readAct = { type: "read" }
addAct = { type: "add" }
editAct = { type: "edit" }
delAct = { type: "delete" }
searchAct = { type: "search" }
addr = "Class@component.example.com/instance"
readObj = {a:"foo", b:2}
(expect Serializer.serialize(readObj, readAct).toString()).to.deep.equal ltx.parse("<read xmlns='jabber:iq:joap'>"+
"<attribute><name>a</name><value><string>foo</string></value></attribute>" +
"<attribute><name>b</name><value><int>2</int></value></attribute>" +
"</read>").toString()
(expect Serializer.serialize addr, addAct).to.deep.equal ltx.parse "<add xmlns='jabber:iq:joap'>"+
"<newAddress>#{addr}</newAddress></add>"
(expect Serializer.serialize null, editAct).to.deep.equal ltx.parse "<edit xmlns='jabber:iq:joap' />"
(expect Serializer.serialize addr, editAct).to.deep.equal ltx.parse "<edit xmlns='jabber:iq:joap' >" +
"<newAddress>#{addr}</newAddress></edit>"
(expect Serializer.serialize null, delAct).to.deep.equal ltx.parse "<delete xmlns='jabber:iq:joap' />"
serverDesc =
desc:
"en-US":"A server"
"de-DE":"Ein Server"
attributes:
foo:
writable:true
type: "bar"
desc:
"en-US":"Hello world"
"de-DE":"Hallo Welt"
bar:
writable:false
type: "int"
(expect Serializer.serialize(serverDesc, descAct).toString()).to.eql ltx.parse("<describe xmlns='jabber:iq:joap' >" +
"<desc xml:lang='en-US' >A server</desc>"+
"<desc xml:lang='de-DE' >Ein Server</desc>"+
"<attributeDescription writable='true'><name>foo</name><type>bar</type>" +
"<desc xml:lang='en-US' >Hello world</desc>"+
"<desc xml:lang='de-DE' >Hallo Welt</desc>"+
"</attributeDescription>"+
"<attributeDescription writable='false'><name>bar</name><type>int</type>" +
"</attributeDescription>"+
"</describe>").toString()
searchResults = ["a", "b", "c"]
(expect Serializer.serialize searchResults, searchAct).to.deep.equal ltx.parse "<search xmlns='jabber:iq:joap' >" +
"<item>a</item>" +
"<item>b</item>" +
"<item>c</item>" +
"</search>"
it "serializes custom joap data", ->
customAct = { type: "foo" }
customData = { x: "y" }
xmlData = ltx.parse "<cutom><data><foo bar='baz' /></data></cutom>"
(expect Serializer.serialize null, customAct).to.deep.equal ltx.parse "<foo xmlns='jabber:iq:joap' />"
(expect Serializer.serialize(customData, customAct).toString()).to.deep.equal ltx.parse("<foo xmlns='jabber:iq:joap' >" +
"<struct><member><name>x</name><value><string>y</string></value></member></struct></foo>").toString()
(expect Serializer.serialize xmlData, customAct).to.deep.equal ltx.parse "<foo xmlns='jabber:iq:joap' >" +
"<cutom><data><foo bar='baz' /></data></cutom>" + "</foo>"
| 9769 | chai = require 'chai'
expect = chai.expect
describe "Serializer", ->
Serializer = require "../src/Serializer"
ltx = require "ltx"
describe "serialize", ->
it "serializes basic data types", ->
(expect Serializer.serialize null ).to.equal ""
(expect Serializer.serialize undefined ).to.equal ""
(expect Serializer.serialize("foo").toString()).to.eql "<string>foo</string>"
(expect Serializer.serialize(2).toString()).to.eql ltx.parse("<int>2</int>").toString()
(expect Serializer.serialize(-0.3).toString()).to.deep.eql ltx.parse("<double>-0.3</double>").toString()
(expect Serializer.serialize(true).toString()).to.deep.eql ltx.parse("<boolean>1</boolean>").toString()
(expect Serializer.serialize([]).toString()).to.eql ltx.parse("<array><data></data></array>").toString()
(expect Serializer.serialize(["x", -0.35, false]).toString()).to.eql ltx.parse("<array><data>" +
"<value><string>x</string></value><value><double>-0.35</double></value><value>" +
"<boolean>0</boolean></value></data></array>").toString()
(expect Serializer.serialize({a:"foo", b:["bar"]}).toString()).to.eql ltx.parse("<struct>"+
"<member><name>a</name><value><string>foo</string></value></member>" +
"<member><name>b</name>" +
"<value><array><data><value><string>bar</string></value></data></array>" +
"</value></member></struct>").toString()
it "serializes result attributes", ->
descAct = { type: "describe" }
readAct = { type: "read" }
addAct = { type: "add" }
editAct = { type: "edit" }
delAct = { type: "delete" }
searchAct = { type: "search" }
addr = "<EMAIL>/instance"
readObj = {a:"foo", b:2}
(expect Serializer.serialize(readObj, readAct).toString()).to.deep.equal ltx.parse("<read xmlns='jabber:iq:joap'>"+
"<attribute><name>a</name><value><string>foo</string></value></attribute>" +
"<attribute><name>b</name><value><int>2</int></value></attribute>" +
"</read>").toString()
(expect Serializer.serialize addr, addAct).to.deep.equal ltx.parse "<add xmlns='jabber:iq:joap'>"+
"<newAddress>#{addr}</newAddress></add>"
(expect Serializer.serialize null, editAct).to.deep.equal ltx.parse "<edit xmlns='jabber:iq:joap' />"
(expect Serializer.serialize addr, editAct).to.deep.equal ltx.parse "<edit xmlns='jabber:iq:joap' >" +
"<newAddress>#{addr}</newAddress></edit>"
(expect Serializer.serialize null, delAct).to.deep.equal ltx.parse "<delete xmlns='jabber:iq:joap' />"
serverDesc =
desc:
"en-US":"A server"
"de-DE":"Ein Server"
attributes:
foo:
writable:true
type: "bar"
desc:
"en-US":"Hello world"
"de-DE":"Hallo Welt"
bar:
writable:false
type: "int"
(expect Serializer.serialize(serverDesc, descAct).toString()).to.eql ltx.parse("<describe xmlns='jabber:iq:joap' >" +
"<desc xml:lang='en-US' >A server</desc>"+
"<desc xml:lang='de-DE' >Ein Server</desc>"+
"<attributeDescription writable='true'><name>foo</name><type>bar</type>" +
"<desc xml:lang='en-US' >Hello world</desc>"+
"<desc xml:lang='de-DE' >Hallo Welt</desc>"+
"</attributeDescription>"+
"<attributeDescription writable='false'><name>bar</name><type>int</type>" +
"</attributeDescription>"+
"</describe>").toString()
searchResults = ["a", "b", "c"]
(expect Serializer.serialize searchResults, searchAct).to.deep.equal ltx.parse "<search xmlns='jabber:iq:joap' >" +
"<item>a</item>" +
"<item>b</item>" +
"<item>c</item>" +
"</search>"
it "serializes custom joap data", ->
customAct = { type: "foo" }
customData = { x: "y" }
xmlData = ltx.parse "<cutom><data><foo bar='baz' /></data></cutom>"
(expect Serializer.serialize null, customAct).to.deep.equal ltx.parse "<foo xmlns='jabber:iq:joap' />"
(expect Serializer.serialize(customData, customAct).toString()).to.deep.equal ltx.parse("<foo xmlns='jabber:iq:joap' >" +
"<struct><member><name>x</name><value><string>y</string></value></member></struct></foo>").toString()
(expect Serializer.serialize xmlData, customAct).to.deep.equal ltx.parse "<foo xmlns='jabber:iq:joap' >" +
"<cutom><data><foo bar='baz' /></data></cutom>" + "</foo>"
| true | chai = require 'chai'
expect = chai.expect
describe "Serializer", ->
Serializer = require "../src/Serializer"
ltx = require "ltx"
describe "serialize", ->
it "serializes basic data types", ->
(expect Serializer.serialize null ).to.equal ""
(expect Serializer.serialize undefined ).to.equal ""
(expect Serializer.serialize("foo").toString()).to.eql "<string>foo</string>"
(expect Serializer.serialize(2).toString()).to.eql ltx.parse("<int>2</int>").toString()
(expect Serializer.serialize(-0.3).toString()).to.deep.eql ltx.parse("<double>-0.3</double>").toString()
(expect Serializer.serialize(true).toString()).to.deep.eql ltx.parse("<boolean>1</boolean>").toString()
(expect Serializer.serialize([]).toString()).to.eql ltx.parse("<array><data></data></array>").toString()
(expect Serializer.serialize(["x", -0.35, false]).toString()).to.eql ltx.parse("<array><data>" +
"<value><string>x</string></value><value><double>-0.35</double></value><value>" +
"<boolean>0</boolean></value></data></array>").toString()
(expect Serializer.serialize({a:"foo", b:["bar"]}).toString()).to.eql ltx.parse("<struct>"+
"<member><name>a</name><value><string>foo</string></value></member>" +
"<member><name>b</name>" +
"<value><array><data><value><string>bar</string></value></data></array>" +
"</value></member></struct>").toString()
it "serializes result attributes", ->
descAct = { type: "describe" }
readAct = { type: "read" }
addAct = { type: "add" }
editAct = { type: "edit" }
delAct = { type: "delete" }
searchAct = { type: "search" }
addr = "PI:EMAIL:<EMAIL>END_PI/instance"
readObj = {a:"foo", b:2}
(expect Serializer.serialize(readObj, readAct).toString()).to.deep.equal ltx.parse("<read xmlns='jabber:iq:joap'>"+
"<attribute><name>a</name><value><string>foo</string></value></attribute>" +
"<attribute><name>b</name><value><int>2</int></value></attribute>" +
"</read>").toString()
(expect Serializer.serialize addr, addAct).to.deep.equal ltx.parse "<add xmlns='jabber:iq:joap'>"+
"<newAddress>#{addr}</newAddress></add>"
(expect Serializer.serialize null, editAct).to.deep.equal ltx.parse "<edit xmlns='jabber:iq:joap' />"
(expect Serializer.serialize addr, editAct).to.deep.equal ltx.parse "<edit xmlns='jabber:iq:joap' >" +
"<newAddress>#{addr}</newAddress></edit>"
(expect Serializer.serialize null, delAct).to.deep.equal ltx.parse "<delete xmlns='jabber:iq:joap' />"
serverDesc =
desc:
"en-US":"A server"
"de-DE":"Ein Server"
attributes:
foo:
writable:true
type: "bar"
desc:
"en-US":"Hello world"
"de-DE":"Hallo Welt"
bar:
writable:false
type: "int"
(expect Serializer.serialize(serverDesc, descAct).toString()).to.eql ltx.parse("<describe xmlns='jabber:iq:joap' >" +
"<desc xml:lang='en-US' >A server</desc>"+
"<desc xml:lang='de-DE' >Ein Server</desc>"+
"<attributeDescription writable='true'><name>foo</name><type>bar</type>" +
"<desc xml:lang='en-US' >Hello world</desc>"+
"<desc xml:lang='de-DE' >Hallo Welt</desc>"+
"</attributeDescription>"+
"<attributeDescription writable='false'><name>bar</name><type>int</type>" +
"</attributeDescription>"+
"</describe>").toString()
searchResults = ["a", "b", "c"]
(expect Serializer.serialize searchResults, searchAct).to.deep.equal ltx.parse "<search xmlns='jabber:iq:joap' >" +
"<item>a</item>" +
"<item>b</item>" +
"<item>c</item>" +
"</search>"
it "serializes custom joap data", ->
customAct = { type: "foo" }
customData = { x: "y" }
xmlData = ltx.parse "<cutom><data><foo bar='baz' /></data></cutom>"
(expect Serializer.serialize null, customAct).to.deep.equal ltx.parse "<foo xmlns='jabber:iq:joap' />"
(expect Serializer.serialize(customData, customAct).toString()).to.deep.equal ltx.parse("<foo xmlns='jabber:iq:joap' >" +
"<struct><member><name>x</name><value><string>y</string></value></member></struct></foo>").toString()
(expect Serializer.serialize xmlData, customAct).to.deep.equal ltx.parse "<foo xmlns='jabber:iq:joap' >" +
"<cutom><data><foo bar='baz' /></data></cutom>" + "</foo>"
|
[
{
"context": "indow.lastLoad = now()\n window.refreshPassword = 30000\n window.tickerInterval = 200\n\n window.ticker = ",
"end": 284,
"score": 0.9990344047546387,
"start": 279,
"tag": "PASSWORD",
"value": "30000"
}
] | frontend/assets/application.coffee | funkjedi/password | 0 | if window.Storage and window.JSON
window.$storage = (key) ->
set: (value) ->
localStorage.setItem(key, JSON.stringify(value))
get: ->
item = localStorage.getItem(key)
JSON.parse(item) if item
$ ->
window.lastLoad = now()
window.refreshPassword = 30000
window.tickerInterval = 200
window.ticker = setInterval tick, window.tickerInterval
$('#focusedInput').bind 'click', stopRefresh
$('#focusedInput').bind 'blur', restartRefresh
$('#optionSave').bind 'click', saveOptions
loadOptions()
loadPassword()
now = () ->
d = new Date()
d.getTime()
stopRefresh = () ->
clearInterval(window.ticker)
$('#focusedInput').select()
false
restartRefresh = () ->
window.lastLoad = now()
window.ticker = setInterval tick, window.tickerInterval
setProgress = (perc) ->
$('.progress-bar').css('width', "#{perc}%")
loadPassword = () ->
options = loadOptions()
$.get "/v1/getPassword?length=#{options.passwordLength}&special=#{options.useSpecial}&xkcd=#{options.useXKCD}", (data) ->
$('#focusedInput').val(data)
window.lastLoad = now()
saveOptions = () ->
options =
passwordLength: $('#passwordLengthOption').val()
useSpecial: $('#useSpecialOption')[0].checked
useXKCD: $('#useXKCDOption')[0].checked
window.$storage('SecurePasswordOptions').set(options)
$('#settingsModal').modal('hide')
loadPassword()
loadOptions = () ->
options = window.$storage('SecurePasswordOptions').get()
if options == undefined
options =
passwordLength: 20
useSpecial: false
useXKCD: false
$('#passwordLengthOption').val(options.passwordLength)
$('#useSpecialOption')[0].checked = options.useSpecial
$('#useXKCDOption')[0].checked = options.useXKCD
options
tick = () ->
diff = now() - window.lastLoad
perc = (window.refreshPassword - diff) / window.refreshPassword * 100
setProgress perc
if diff >= window.refreshPassword
loadPassword()
| 123869 | if window.Storage and window.JSON
window.$storage = (key) ->
set: (value) ->
localStorage.setItem(key, JSON.stringify(value))
get: ->
item = localStorage.getItem(key)
JSON.parse(item) if item
$ ->
window.lastLoad = now()
window.refreshPassword = <PASSWORD>
window.tickerInterval = 200
window.ticker = setInterval tick, window.tickerInterval
$('#focusedInput').bind 'click', stopRefresh
$('#focusedInput').bind 'blur', restartRefresh
$('#optionSave').bind 'click', saveOptions
loadOptions()
loadPassword()
now = () ->
d = new Date()
d.getTime()
stopRefresh = () ->
clearInterval(window.ticker)
$('#focusedInput').select()
false
restartRefresh = () ->
window.lastLoad = now()
window.ticker = setInterval tick, window.tickerInterval
setProgress = (perc) ->
$('.progress-bar').css('width', "#{perc}%")
loadPassword = () ->
options = loadOptions()
$.get "/v1/getPassword?length=#{options.passwordLength}&special=#{options.useSpecial}&xkcd=#{options.useXKCD}", (data) ->
$('#focusedInput').val(data)
window.lastLoad = now()
saveOptions = () ->
options =
passwordLength: $('#passwordLengthOption').val()
useSpecial: $('#useSpecialOption')[0].checked
useXKCD: $('#useXKCDOption')[0].checked
window.$storage('SecurePasswordOptions').set(options)
$('#settingsModal').modal('hide')
loadPassword()
loadOptions = () ->
options = window.$storage('SecurePasswordOptions').get()
if options == undefined
options =
passwordLength: 20
useSpecial: false
useXKCD: false
$('#passwordLengthOption').val(options.passwordLength)
$('#useSpecialOption')[0].checked = options.useSpecial
$('#useXKCDOption')[0].checked = options.useXKCD
options
tick = () ->
diff = now() - window.lastLoad
perc = (window.refreshPassword - diff) / window.refreshPassword * 100
setProgress perc
if diff >= window.refreshPassword
loadPassword()
| true | if window.Storage and window.JSON
window.$storage = (key) ->
set: (value) ->
localStorage.setItem(key, JSON.stringify(value))
get: ->
item = localStorage.getItem(key)
JSON.parse(item) if item
$ ->
window.lastLoad = now()
window.refreshPassword = PI:PASSWORD:<PASSWORD>END_PI
window.tickerInterval = 200
window.ticker = setInterval tick, window.tickerInterval
$('#focusedInput').bind 'click', stopRefresh
$('#focusedInput').bind 'blur', restartRefresh
$('#optionSave').bind 'click', saveOptions
loadOptions()
loadPassword()
now = () ->
d = new Date()
d.getTime()
stopRefresh = () ->
clearInterval(window.ticker)
$('#focusedInput').select()
false
restartRefresh = () ->
window.lastLoad = now()
window.ticker = setInterval tick, window.tickerInterval
setProgress = (perc) ->
$('.progress-bar').css('width', "#{perc}%")
loadPassword = () ->
options = loadOptions()
$.get "/v1/getPassword?length=#{options.passwordLength}&special=#{options.useSpecial}&xkcd=#{options.useXKCD}", (data) ->
$('#focusedInput').val(data)
window.lastLoad = now()
saveOptions = () ->
options =
passwordLength: $('#passwordLengthOption').val()
useSpecial: $('#useSpecialOption')[0].checked
useXKCD: $('#useXKCDOption')[0].checked
window.$storage('SecurePasswordOptions').set(options)
$('#settingsModal').modal('hide')
loadPassword()
loadOptions = () ->
options = window.$storage('SecurePasswordOptions').get()
if options == undefined
options =
passwordLength: 20
useSpecial: false
useXKCD: false
$('#passwordLengthOption').val(options.passwordLength)
$('#useSpecialOption')[0].checked = options.useSpecial
$('#useXKCDOption')[0].checked = options.useXKCD
options
tick = () ->
diff = now() - window.lastLoad
perc = (window.refreshPassword - diff) / window.refreshPassword * 100
setProgress perc
if diff >= window.refreshPassword
loadPassword()
|
[
{
"context": ".HUBOT_BITLY_USERNAME\n apiKey: process.env.HUBOT_BITLY_API_KEY\n longUrl: msg.match[3]\n ",
"end": 333,
"score": 0.5904248952865601,
"start": 328,
"tag": "KEY",
"value": "HUBOT"
},
{
"context": "_BITLY_USERNAME\n apiKey: process.env.HUBOT_BITLY_API_KEY\n longUrl: msg.match[3]\n for",
"end": 339,
"score": 0.7858227491378784,
"start": 334,
"tag": "KEY",
"value": "BITLY"
}
] | src/scripts/shorten.coffee | mcollina/hubot-scripts | 1 | # Shorten URLs with bit.ly
#
# hubot (bitly|shorten) (me) <url> - Shorten the URL using bit.ly
module.exports = (robot) ->
robot.respond /(bitly|shorten)\s?(me)?\s?(.+)$/, (msg) ->
msg
.http("http://api.bitly.com/v3/shorten")
.query
login: process.env.HUBOT_BITLY_USERNAME
apiKey: process.env.HUBOT_BITLY_API_KEY
longUrl: msg.match[3]
format: "json"
.get() (err, res, body) ->
response = JSON.parse body
msg.send if response.status_code is 200 then response.data.url else response.status_txt
| 219482 | # Shorten URLs with bit.ly
#
# hubot (bitly|shorten) (me) <url> - Shorten the URL using bit.ly
module.exports = (robot) ->
robot.respond /(bitly|shorten)\s?(me)?\s?(.+)$/, (msg) ->
msg
.http("http://api.bitly.com/v3/shorten")
.query
login: process.env.HUBOT_BITLY_USERNAME
apiKey: process.env.<KEY>_<KEY>_API_KEY
longUrl: msg.match[3]
format: "json"
.get() (err, res, body) ->
response = JSON.parse body
msg.send if response.status_code is 200 then response.data.url else response.status_txt
| true | # Shorten URLs with bit.ly
#
# hubot (bitly|shorten) (me) <url> - Shorten the URL using bit.ly
module.exports = (robot) ->
robot.respond /(bitly|shorten)\s?(me)?\s?(.+)$/, (msg) ->
msg
.http("http://api.bitly.com/v3/shorten")
.query
login: process.env.HUBOT_BITLY_USERNAME
apiKey: process.env.PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI_API_KEY
longUrl: msg.match[3]
format: "json"
.get() (err, res, body) ->
response = JSON.parse body
msg.send if response.status_code is 200 then response.data.url else response.status_txt
|
[
{
"context": " for own key, expansion of config\n key = _.sortBy(_.uniq(_.toArray(key))).join('')\n mapping[",
"end": 1289,
"score": 0.5682982206344604,
"start": 1283,
"tag": "KEY",
"value": "sortBy"
},
{
"context": "ig\n key = _.sortBy(_.uniq(_.toArray(key))).join('')\n mapping[key] = expansion\n @chords ",
"end": 1318,
"score": 0.6359625458717346,
"start": 1314,
"tag": "KEY",
"value": "join"
}
] | lib/arpeggio.coffee | dtinth/atom-arpeggio | 8 | {CompositeDisposable} = require 'atom'
_ = require 'underscore-plus'
module.exports = Arpeggio =
subscriptions: null
chords: null
matchChords: (historyString) ->
maxChordLength = Math.max((key.length for key of @chords)...)
for i in [Math.min(historyString.length, maxChordLength)..2] by -1
key = _.sortBy(historyString.substr(-i)).join('')
result = @chords[key]
if result
return {
length: i
expansion: result
}
return null
validateMatch: (match, history) ->
{ expansion } = match
if expansion and expansion.timeout
lastTimeStamp = null
for { timeStamp } in history.slice(-match.length)
if lastTimeStamp isnt null and timeStamp > lastTimeStamp + expansion.timeout
return false
lastTimeStamp = timeStamp
return true
else
return true
activate: (state) ->
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.observe 'arpeggio.chords', (chords) =>
@loadConfig(chords)
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@enableChords(editor)
loadConfig: (config) ->
mapping = { }
if config and typeof config is 'object'
for own key, expansion of config
key = _.sortBy(_.uniq(_.toArray(key))).join('')
mapping[key] = expansion
@chords = mapping
enableChords: (editor) ->
view = atom.views.getView(editor)
history = []
onKeyPress = (event) =>
if event.charCode
history.push
char: String.fromCharCode(event.charCode)
keyIdentifier: event.keyIdentifier
timeStamp: event.timeStamp
else
history.length = 0
onKeyUp = (event) =>
historyString = (char for { char } in history).join('')
match = @matchChords(historyString)
if match and @validateMatch(match, history)
history.length = 0
editor.transact =>
editor.selectLeft(match.length)
editor.insertText('')
@trigger(editor, view, match.expansion)
history = history.filter ({ keyIdentifier }) -> keyIdentifier isnt event.keyIdentifier
view.addEventListener 'keypress', onKeyPress
view.addEventListener 'keyup', onKeyUp
@subscriptions.add
dispose: ->
view.removeEventListener 'keypress', onKeyPress
view.removeEventListener 'keyup', onKeyUp
trigger: (editor, view, expansion) ->
if typeof expansion is 'string'
expansion = { text: expansion }
if expansion.command
atom.commands.dispatch(view, expansion.command)
if expansion.text
editor.insertText(expansion.text)
if expansion.snippet
snippets = atom.packages.getActivePackage('snippets').mainModule
snippets.insert(expansion.snippet)
deactivate: ->
@subscriptions.dispose()
| 44281 | {CompositeDisposable} = require 'atom'
_ = require 'underscore-plus'
module.exports = Arpeggio =
subscriptions: null
chords: null
matchChords: (historyString) ->
maxChordLength = Math.max((key.length for key of @chords)...)
for i in [Math.min(historyString.length, maxChordLength)..2] by -1
key = _.sortBy(historyString.substr(-i)).join('')
result = @chords[key]
if result
return {
length: i
expansion: result
}
return null
validateMatch: (match, history) ->
{ expansion } = match
if expansion and expansion.timeout
lastTimeStamp = null
for { timeStamp } in history.slice(-match.length)
if lastTimeStamp isnt null and timeStamp > lastTimeStamp + expansion.timeout
return false
lastTimeStamp = timeStamp
return true
else
return true
activate: (state) ->
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.observe 'arpeggio.chords', (chords) =>
@loadConfig(chords)
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@enableChords(editor)
loadConfig: (config) ->
mapping = { }
if config and typeof config is 'object'
for own key, expansion of config
key = _.<KEY>(_.uniq(_.toArray(key))).<KEY>('')
mapping[key] = expansion
@chords = mapping
enableChords: (editor) ->
view = atom.views.getView(editor)
history = []
onKeyPress = (event) =>
if event.charCode
history.push
char: String.fromCharCode(event.charCode)
keyIdentifier: event.keyIdentifier
timeStamp: event.timeStamp
else
history.length = 0
onKeyUp = (event) =>
historyString = (char for { char } in history).join('')
match = @matchChords(historyString)
if match and @validateMatch(match, history)
history.length = 0
editor.transact =>
editor.selectLeft(match.length)
editor.insertText('')
@trigger(editor, view, match.expansion)
history = history.filter ({ keyIdentifier }) -> keyIdentifier isnt event.keyIdentifier
view.addEventListener 'keypress', onKeyPress
view.addEventListener 'keyup', onKeyUp
@subscriptions.add
dispose: ->
view.removeEventListener 'keypress', onKeyPress
view.removeEventListener 'keyup', onKeyUp
trigger: (editor, view, expansion) ->
if typeof expansion is 'string'
expansion = { text: expansion }
if expansion.command
atom.commands.dispatch(view, expansion.command)
if expansion.text
editor.insertText(expansion.text)
if expansion.snippet
snippets = atom.packages.getActivePackage('snippets').mainModule
snippets.insert(expansion.snippet)
deactivate: ->
@subscriptions.dispose()
| true | {CompositeDisposable} = require 'atom'
_ = require 'underscore-plus'
module.exports = Arpeggio =
subscriptions: null
chords: null
matchChords: (historyString) ->
maxChordLength = Math.max((key.length for key of @chords)...)
for i in [Math.min(historyString.length, maxChordLength)..2] by -1
key = _.sortBy(historyString.substr(-i)).join('')
result = @chords[key]
if result
return {
length: i
expansion: result
}
return null
validateMatch: (match, history) ->
{ expansion } = match
if expansion and expansion.timeout
lastTimeStamp = null
for { timeStamp } in history.slice(-match.length)
if lastTimeStamp isnt null and timeStamp > lastTimeStamp + expansion.timeout
return false
lastTimeStamp = timeStamp
return true
else
return true
activate: (state) ->
@subscriptions = new CompositeDisposable
@subscriptions.add atom.config.observe 'arpeggio.chords', (chords) =>
@loadConfig(chords)
@subscriptions.add atom.workspace.observeTextEditors (editor) =>
@enableChords(editor)
loadConfig: (config) ->
mapping = { }
if config and typeof config is 'object'
for own key, expansion of config
key = _.PI:KEY:<KEY>END_PI(_.uniq(_.toArray(key))).PI:KEY:<KEY>END_PI('')
mapping[key] = expansion
@chords = mapping
enableChords: (editor) ->
view = atom.views.getView(editor)
history = []
onKeyPress = (event) =>
if event.charCode
history.push
char: String.fromCharCode(event.charCode)
keyIdentifier: event.keyIdentifier
timeStamp: event.timeStamp
else
history.length = 0
onKeyUp = (event) =>
historyString = (char for { char } in history).join('')
match = @matchChords(historyString)
if match and @validateMatch(match, history)
history.length = 0
editor.transact =>
editor.selectLeft(match.length)
editor.insertText('')
@trigger(editor, view, match.expansion)
history = history.filter ({ keyIdentifier }) -> keyIdentifier isnt event.keyIdentifier
view.addEventListener 'keypress', onKeyPress
view.addEventListener 'keyup', onKeyUp
@subscriptions.add
dispose: ->
view.removeEventListener 'keypress', onKeyPress
view.removeEventListener 'keyup', onKeyUp
trigger: (editor, view, expansion) ->
if typeof expansion is 'string'
expansion = { text: expansion }
if expansion.command
atom.commands.dispatch(view, expansion.command)
if expansion.text
editor.insertText(expansion.text)
if expansion.snippet
snippets = atom.packages.getActivePackage('snippets').mainModule
snippets.insert(expansion.snippet)
deactivate: ->
@subscriptions.dispose()
|
[
{
"context": "gement service\n#\n# Commands:\n# hubot ums login <username> <password> - stores the credentials for the call",
"end": 104,
"score": 0.5905429124832153,
"start": 96,
"tag": "USERNAME",
"value": "username"
},
{
"context": " modules/i, (msg) ->\n# robot.http(\"https://54.186.169.148/ums-service/api/1/apps\").get()\n# ",
"end": 1581,
"score": 0.9679434895515442,
"start": 1579,
"tag": "IP_ADDRESS",
"value": "54"
},
{
"context": "dules/i, (msg) ->\n# robot.http(\"https://54.186.169.148/ums-service/api/1/apps\").get()\n# https://5",
"end": 1593,
"score": 0.9633626341819763,
"start": 1582,
"tag": "IP_ADDRESS",
"value": "186.169.148"
},
{
"context": "8/ums-service/api/1/apps\").get()\n# https://54.186.169.148/ums-service/api/1/apps",
"end": 1656,
"score": 0.9695339798927307,
"start": 1642,
"tag": "IP_ADDRESS",
"value": "54.186.169.148"
}
] | scripts/ums-commands.coffee | manzke/sample-hubot | 0 | # Description:
# interact with the user management service
#
# Commands:
# hubot ums login <username> <password> - stores the credentials for the calling user
# hubot ums logout - removes the credentials for the calling user
UMS = require "./ums-bridge"
module.exports = (robot) ->
robot.respond /(ums) login (.+) (.+)/i, (msg) ->
jid = msg.message.user.jid
username = msg.match[2]
password = msg.match[3]
if username == null
msg.send 'username is missing'
return
if password == null
msg.send 'password is missing'
return
error = (err, res, body) ->
if !!err
msg.send 'error: '+err
if !!body
msg.send 'body: '+body
return
success = () ->
msg.send 'stored credentials'
return
name = robot.brain.get "#{jid}-server"
options = undefined
if name?
options = robot.brain.get name
bridge = new UMS jid, robot, options
bridge.login(username, password, success, error)
robot.respond /(ums) logout/i, (msg) ->
jid = msg.message.user.jid
name = robot.brain.get "#{jid}-server"
options = undefined
if name?
options = robot.brain.get name
bridge = new UMS jid, robot
bridge.logout()
msg.send 'logged out successfully'
# TODO: add call to check which modules are installed
# robot.respond /(ums) modules/i, (msg) ->
# robot.http("https://54.186.169.148/ums-service/api/1/apps").get()
# https://54.186.169.148/ums-service/api/1/apps | 203845 | # Description:
# interact with the user management service
#
# Commands:
# hubot ums login <username> <password> - stores the credentials for the calling user
# hubot ums logout - removes the credentials for the calling user
UMS = require "./ums-bridge"
module.exports = (robot) ->
robot.respond /(ums) login (.+) (.+)/i, (msg) ->
jid = msg.message.user.jid
username = msg.match[2]
password = msg.match[3]
if username == null
msg.send 'username is missing'
return
if password == null
msg.send 'password is missing'
return
error = (err, res, body) ->
if !!err
msg.send 'error: '+err
if !!body
msg.send 'body: '+body
return
success = () ->
msg.send 'stored credentials'
return
name = robot.brain.get "#{jid}-server"
options = undefined
if name?
options = robot.brain.get name
bridge = new UMS jid, robot, options
bridge.login(username, password, success, error)
robot.respond /(ums) logout/i, (msg) ->
jid = msg.message.user.jid
name = robot.brain.get "#{jid}-server"
options = undefined
if name?
options = robot.brain.get name
bridge = new UMS jid, robot
bridge.logout()
msg.send 'logged out successfully'
# TODO: add call to check which modules are installed
# robot.respond /(ums) modules/i, (msg) ->
# robot.http("https://54.186.169.148/ums-service/api/1/apps").get()
# https://172.16.31.10/ums-service/api/1/apps | true | # Description:
# interact with the user management service
#
# Commands:
# hubot ums login <username> <password> - stores the credentials for the calling user
# hubot ums logout - removes the credentials for the calling user
UMS = require "./ums-bridge"
module.exports = (robot) ->
robot.respond /(ums) login (.+) (.+)/i, (msg) ->
jid = msg.message.user.jid
username = msg.match[2]
password = msg.match[3]
if username == null
msg.send 'username is missing'
return
if password == null
msg.send 'password is missing'
return
error = (err, res, body) ->
if !!err
msg.send 'error: '+err
if !!body
msg.send 'body: '+body
return
success = () ->
msg.send 'stored credentials'
return
name = robot.brain.get "#{jid}-server"
options = undefined
if name?
options = robot.brain.get name
bridge = new UMS jid, robot, options
bridge.login(username, password, success, error)
robot.respond /(ums) logout/i, (msg) ->
jid = msg.message.user.jid
name = robot.brain.get "#{jid}-server"
options = undefined
if name?
options = robot.brain.get name
bridge = new UMS jid, robot
bridge.logout()
msg.send 'logged out successfully'
# TODO: add call to check which modules are installed
# robot.respond /(ums) modules/i, (msg) ->
# robot.http("https://54.186.169.148/ums-service/api/1/apps").get()
# https://PI:IP_ADDRESS:172.16.31.10END_PI/ums-service/api/1/apps |
[
{
"context": " # ask_hn\n # front_page\n # author_:USERNAME\n # story_:ID\n \n # author_pg,(story",
"end": 7823,
"score": 0.9992688894271851,
"start": 7815,
"tag": "USERNAME",
"value": "USERNAME"
},
{
"context": "I\"\n \n broughtToYouByURL:\"https://github.com/reddit/reddit/wiki/API\"\n \n brandingImage: null\n ",
"end": 8270,
"score": 0.9985571503639221,
"start": 8264,
"tag": "USERNAME",
"value": "reddit"
},
{
"context": "\n # so many great communities out there! ping me @spencenow if an API surfaces for yours!\n # 2015-8-13 - pro",
"end": 10172,
"score": 0.9992564916610718,
"start": 10162,
"tag": "USERNAME",
"value": "@spencenow"
},
{
"context": "\n refreshView: 'userPreferences'\n keyName: 'kiwi_userPreferences'\n newValue: dataFromPopup.kiwi_userPreferences",
"end": 30022,
"score": 0.9980536699295044,
"start": 30002,
"tag": "KEY",
"value": "kiwi_userPreferences"
},
{
"context": " # profile_url: \"http://www.producthunt.com/@andreasklinger\"\n # name: \"Andreas Klinger\"\n # ",
"end": 56777,
"score": 0.9994505643844604,
"start": 56762,
"tag": "USERNAME",
"value": "@andreasklinger"
},
{
"context": "oducthunt.com/@andreasklinger\"\n # name: \"Andreas Klinger\"\n # username: \"andreasklinger\"\n #",
"end": 56813,
"score": 0.9998777508735657,
"start": 56798,
"tag": "NAME",
"value": "Andreas Klinger"
},
{
"context": " name: \"Andreas Klinger\"\n # username: \"andreasklinger\"\n # website_url: \"http://klinger.io\"\n ",
"end": 56852,
"score": 0.9994438886642456,
"start": 56838,
"tag": "USERNAME",
"value": "andreasklinger"
},
{
"context": "ame = maker.name\n makerObj.username = maker.username\n makerObj.profile_url = maker.profile_",
"end": 58419,
"score": 0.9071771502494812,
"start": 58406,
"tag": "USERNAME",
"value": "aker.username"
},
{
"context": ".name = maker.name\n makerObj.username = maker.username\n makerObj.profile_url = maker.profile_",
"end": 61049,
"score": 0.9738422632217407,
"start": 61035,
"tag": "USERNAME",
"value": "maker.username"
}
] | coffeescripts/background.coffee | sdailey/kiwi-firefox | 5 |
self = require('sdk/self')
tabs = require("sdk/tabs")
base64 = require("sdk/base64")
firefoxStorage = require("sdk/simple-storage")
Panel = require("sdk/panel").Panel # <-> same thing, but one is clearer # { Panel } = require("sdk/panel")
IconButton = require("sdk/ui/button/action").ActionButton
{ setTimeout, clearTimeout } = require("sdk/timers")
{ Cc, Ci } = require('chrome')
# kiwi_popup = require('./KiwiPopup')
Request = require("sdk/request").Request
_ = require('./data/vendor/underscore-min')
tabUrl = ''
tabTitleObject = null
popupOpen = false
checkForUrlHourInterval = 16
checkForUrl_Persistent_ChromeNotification_HourInterval = 3 # (max of 5 notification items)
last_periodicCleanup = 0 # timestamp
CLEANUP_INTERVAL = 3 * 3600000 # three hours
queryThrottleSeconds = 3 # to respect the no-more-than 30/min stiplation for Reddit's api
serviceQueryTimestamps = {}
maxUrlResultsStoredInLocalStorage = 800 # they're deleted after they've expired anyway - so this likely won't be reached by user
popupParcel = {}
# proactively set if each services' preppedResults are ready.
# will be set with available results if queried by popup.
# {
# forUrl:
# allPreppedResults:
# kiwi_servicesInfo:
# kiwi_customSearchResults:
# kiwi_alerts:
# kiwi_userPreferences:
# }
kiwi_userMessages = {
"redditDown":
"baseValue":"reddit's API is unavailable, so results may not appear from this service for some time"
"name":"redditDown"
"sentAndAcknowledgedInstanceObjects": []
# {
# "sentTimestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"productHuntDown":
"name":"productHuntDown"
"baseValue":"Product Hunt's API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
"productHuntDown__customSearch":
"name":"productHuntDown__customSearch"
"baseValue":"Product Hunt's custom search API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"hackerNewsDown":
"name":"hackerNewsDown"
"baseValue":"Hacker News' API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"generalConnectionFailure":
"name":"generalConnectionFailure"
"baseValue":"There has been a network connection issue. Check your internet connection / try again in a few minutes :)"
"sentAndAcknowledgedInstanceObjects": []
}
kiwi_urlsResultsCache = {}
# < url >:
# < serviceName >: {
# forUrl: url
# timestamp:
# service_PreppedResults:
# urlBlocked:
# }
kiwi_customSearchResults = {} # stores temporarily so if they close popup, they'll still have results
# maybe it won't clear until new result -- "see last search"
# queryString
# servicesSearchesRequested = responsePackage.servicesToSearch
# servicesSearched
# <serviceName>
# results
kiwi_autoOffClearInterval = null
kiwi_reddit_token_refresh_interval = null
# timestamp:
# intervalId:
kiwi_productHunt_token_refresh_interval = null
# timestamp:
# intervalId:
tempResponsesStore = {}
# forUrl: < url >
# results:
# < serviceName > :
# timestamp:
# service_PreppedResults:
# forUrl: url
getRandom = (min, max) ->
return min + Math.floor(Math.random() * (max - min + 1))
randomishDeviceId = -> # to be held in localStorage
randomClientLength = getRandom(21,29)
characterCounter = 0
randomString = ""
while characterCounter <= randomClientLength
characterCounter++
randomASCIIcharcode = getRandom(33,125)
#console.log randomASCIIcharcode
randomString += String.fromCharCode(randomASCIIcharcode)
return randomString
temp__kiwi_reddit_oauth =
token: null
token_type: null
token_lifespan_timestamp: null
client_id: "" # your client id here
device_id: randomishDeviceId()
temp__kiwi_productHunt_oauth =
token: null
token_type: null
token_lifespan_timestamp: null
client_id: "" # your client id here
client_secret: "" # your secret id here
defaultUserPreferences = {
fontSize: .8 # not yet implemented
researchModeOnOff: 'off' # or 'on'
autoOffAtUTCmilliTimestamp: null
autoOffTimerType: 'always' # 'custom','always','20','60'
autoOffTimerValue: null
sortByPref: 'attention' # 'recency' # "attention" means 'comments' if story, 'points' if comment, 'clusterUrl' if news
installedTime: Date.now()
urlSubstring_whitelists:
anyMatch: []
beginsWith: []
endingIn: []
unless: [
# ['twitter.com/','/status/'] # unless /status/
]
# suggested values to all users -- any can be overriden with the "Research this URL" button
# unfortunately, because of Chrome's discouragement of storing sensitive
# user info with chrome.storage, blacklists are fixed for now . see: https://news.ycombinator.com/item?id=9993030
urlSubstring_blacklists:
anyMatch: [
'facebook.com'
'news.ycombinator.com'
'reddit.com'
'imgur.com'
'www.google.com'
'docs.google'
'drive.google'
'accounts.google'
'.slack.com/'
'//t.co'
'//bit.ly'
'//goo.gl'
'//mail.google'
'//mail.yahoo.com'
'hotmail.com'
'outlook.com'
'chrome-extension://'
'chrome-devtools://' # hardcoded block
# "about:blank"
# "about:newtab"
]
beginsWith: [
"about:"
'chrome://'
]
endingIn: [
#future - ending in:
'youtube.com' # /
]
unless: [
#unless
['twitter.com/','/status/'] # unless /status/
# ,
# 'twitter.com'
]
}
defaultServicesInfo = [
name:"hackerNews"
title: "Hacker News"
abbreviation: "H"
queryApi:"https://hn.algolia.com/api/v1/search?restrictSearchableAttributes=url&query="
broughtToYouByTitle:"Algolia Hacker News API"
broughtToYouByURL:"https://hn.algolia.com/api"
brandingImage: null
brandingSlogan: null
permalinkBase: 'https://news.ycombinator.com/item?id='
userPageBaselink: 'https://news.ycombinator.com/user?id='
submitTitle: 'Be the first to submit on Hacker News!'
submitUrl: 'https://news.ycombinator.com/submit'
active: 'on'
notableConditions:
hoursSincePosted: 4 # an exact match is less than 5 hours old
num_comments: 10 # an exact match has 10 comments
updateBadgeOnlyWithExactMatch: true
customSearchApi: "https://hn.algolia.com/api/v1/search?query="
customSearchTags__convention: {'string':'&tags=','delimeter':','}
customSearchTags:
story:
title: "stories"
string: "story"
include: true
commentPolls:
title: "comments or polls"
string:"(comment,poll,pollopt)"
include: false
showHnAskHn:
title: "Show HN or Ask HN"
string:"(show_hn,ask_hn)"
include: false
# customSearch
# queryApi https://hn.algolia.com/api/v1/search?query=
# tags= filter on a specific tag. Available tags:
# story
# comment
# poll
# pollopt
# show_hn
# ask_hn
# front_page
# author_:USERNAME
# story_:ID
# author_pg,(story,poll) filters on author=pg AND (type=story OR type=poll).
customSearchBroughtToYouByURL: null
customSearchBroughtToYouByTitle: null
conversationSite: true
,
name:"reddit"
title: "reddit"
abbreviation: "R"
queryApi:"https://www.reddit.com/submit.json?url="
broughtToYouByTitle:"Reddit API"
broughtToYouByURL:"https://github.com/reddit/reddit/wiki/API"
brandingImage: null
brandingSlogan: null
permalinkBase: 'https://www.reddit.com'
userPageBaselink: 'https://www.reddit.com/user/'
submitTitle: 'Be the first to submit on Reddit!'
submitUrl: 'https://www.reddit.com/submit'
active: 'on'
notableConditions:
hoursSincePosted: 1 # an exact match is less than 5 hours old
num_comments: 30 # an exact match has 30 comments
updateBadgeOnlyWithExactMatch: true
customSearchApi: "https://www.reddit.com/search.json?q="
customSearchTags: {}
customSearchBroughtToYouByURL: null
customSearchBroughtToYouByTitle: null
conversationSite: true
,
name:"productHunt"
title: "Product Hunt"
abbreviation: "P"
queryApi:"https://api.producthunt.com/v1/posts/all?search[url]="
broughtToYouByTitle:"Product Hunt API"
broughtToYouByURL:"https://api.producthunt.com/v1/docs"
permalinkBase: 'https://producthunt.com/'
userPageBaselink: 'https://www.producthunt.com/@'
brandingImage: "product-hunt-logo-orange-240.png"
brandingSlogan: null
submitTitle: 'Be the first to submit to Product Hunt!'
submitUrl: 'https://www.producthunt.com/tech/new'
active: 'on'
notableConditions:
hoursSincePosted: 4 # an exact match is less than 5 hours old
num_comments: 10 # an exact match has 30 comments
# 'featured'
updateBadgeOnlyWithExactMatch: true
# uses Algolia index, not a typical rest api
customSearchApi: ""
customSearchTags: {}
customSearchBroughtToYouByURL: 'https://www.algolia.com/doc/javascript'
customSearchBroughtToYouByTitle: "Algolia's Search API"
conversationSite: true
# {
# so many great communities out there! ping me @spencenow if an API surfaces for yours!
# 2015-8-13 - producthunt has been implemented! holy crap this is cool! :D
# working on Slashdot...!
# },
]
send_kiwi_userMessage = (messageName, urgencyLevel, extraNote = null) ->
currentTime = Date.now()
sendMessageBool = true
# messageName
# if the same message has been sent in last five minutes, don't worry.
messageObj = kiwi_userMessages[messageName]
for sentInstance in messageObj.sentAndAcknowledgedInstanceObjects
if sentInstance.userAcknowledged? and (currentTime - sentInstance.userAcknowledged < 1000 * 60 * 20)
sendMessageBool = false
else if !sentInstance.userAcknowledged?
sendMessageBool = false
if sendMessageBool is true
kiwi_userMessages[messageName].sentAndAcknowledgedInstanceObjects.push {
"sentTimestamp": currentTime
"userAcknowledged": null # <timestamp>
}
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else if tempResponsesStore? and tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
shuffle_array = (array) ->
currentIndex = array.length;
# // While there remain elements to shuffle...
while (0 != currentIndex)
# // Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
# // And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
return array
randomizeDefaultConversationSiteOrder = ->
conversationSiteServices = []
nonConversationSiteServices = []
for service in defaultServicesInfo
if service.conversationSite
conversationSiteServices.push service
else
nonConversationSiteServices.push service
newDefaultServices = []
conversationSiteServices = shuffle_array(conversationSiteServices)
defaultServicesInfo = conversationSiteServices.concat(nonConversationSiteServices)
randomizeDefaultConversationSiteOrder()
# ~~~ starting out with negotiating oAuth tokens and initializing necessary api objects ~~~ #
reduceHashByHalf = (hash, reducedByAFactorOf = 1) ->
reduceStringByHalf = (_string_) ->
newShortenedString = ''
for char, index in _string_
if index % 2 is 0 and (_string_.length - 1 > index + 1)
char = if char > _string_[index + 1] then char else _string_[index + 1]
newShortenedString += char
return newShortenedString
finalHash = ''
counter = 0
while counter < reducedByAFactorOf
hash = reduceStringByHalf(hash)
counter++
return hash
kiwi_iconButton = IconButton {
id: "kiwi-button",
label: "Kiwi Conversations",
badge: '',
badgeColor: "#00AAAA",
icon: {
"16": "./kiwiFavico16.png",
"32": "./kiwiFavico32.png",
"64": "./kiwiFavico64.png"
},
onClick: (iconButtonState) ->
# console.log("button '" + iconButtonState.label + "' was clicked")
iconButtonClicked(iconButtonState)
}
iconButtonClicked = (iconButtonState) ->
# kiwi_iconButton.badge = iconButtonState.badge + 1
if (iconButtonState.checked)
kiwi_iconButton.badgeColor = "#AA00AA"
else
kiwi_iconButton.badgeColor = "#00AAAA"
kiwiPP_request_popupParcel()
kiwi_panel.show({'position':kiwi_iconButton})
# <link rel="stylesheet" href="vendor/bootstrap-3.3.5-dist/css/bootstrap.min.css"></link>
# <link rel="stylesheet" href="vendor/bootstrap-3.3.5-dist/css/bootstrap-theme.min.css"></link>
# <link rel="stylesheet" href="vendor/behigh-bootstrap_dropdown_enhancement/css/dropdowns-enhancement.min.css"></link>
# <script src="vendor/jquery-2.1.4.min.js" ></script>
# <script src="vendor/Underscore1-8-3.js"></script>
# <script src="vendor/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
# <script src=""></script>
kiwiPP_request_popupParcel = (dataFromPopup = {}) ->
# console.log 'kiwiPP_request_popupParcel = (dataFromPopup = {}) ->'
popupOpen = true
preppedResponsesInPopupParcel = 0
if popupParcel? and popupParcel.allPreppedResults?
#console.log 'popupParcel.allPreppedResults? '
#console.debug popupParcel.allPreppedResults
for serviceName, service of popupParcel.allPreppedResults
if service.service_PreppedResults?
preppedResponsesInPopupParcel += service.service_PreppedResults.length
preppedResponsesInTempResponsesStore = 0
if tempResponsesStore? and tempResponsesStore.services?
for serviceName, service of tempResponsesStore.services
preppedResponsesInTempResponsesStore += service.service_PreppedResults.length
newResultsBool = false
if tempResponsesStore.forUrl == tabUrl and preppedResponsesInTempResponsesStore != preppedResponsesInPopupParcel
newResultsBool = true
if popupParcel? and popupParcel.forUrl is tabUrl and newResultsBool == false
#console.log "popup parcel ready"
parcel = {}
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = popupParcel
sendParcel(parcel)
else
if !tempResponsesStore.services? or tempResponsesStore.forUrl != tabUrl
_set_popupParcel({}, tabUrl, true)
else
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
kiwi_panel = Panel({
width: 500,
height: 640,
# contentURL: "https://en.wikipedia.org/w/index.php?title=Jetpack&useformat=mobile",
contentURL: "./popup.html",
contentStyleFile: ["./bootstrap-3.3.5-dist/css/bootstrap.min.css",
"./bootstrap-3.3.5-dist/css/bootstrap-theme.min.css",
"./behigh-bootstrap_dropdown_enhancement/css/dropdowns-enhancement.min.css"
],
contentScriptFile: ["./vendor/jquery-2.1.4.min.js",
"./vendor/underscore-min.js",
"./behigh-bootstrap_dropdown_enhancement/js/dropdowns-enhancement.js",
"./vendor/algoliasearch.min.js",
"./KiwiPopup.js"]
})
updateBadgeText = (newBadgeText) ->
kiwi_iconButton.badge = newBadgeText
setTimeout_forRedditRefresh = (token_timestamp, kiwi_reddit_oauth, ignoreTimeoutDelayComparison = false) ->
currentTime = Date.now()
timeoutDelay = token_timestamp - currentTime
if kiwi_reddit_token_refresh_interval? and kiwi_reddit_token_refresh_interval.timestamp? and ignoreTimeoutDelayComparison is false
if timeoutDelay > kiwi_reddit_token_refresh_interval.timestamp - currentTime
# console.log 'patience, we will be trying again soon'
return 0
if kiwi_reddit_token_refresh_interval? and kiwi_reddit_token_refresh_interval.timestamp?
clearTimeout(kiwi_reddit_token_refresh_interval.intervalId)
timeoutIntervalId = setTimeout( ->
requestRedditOathToken(kiwi_reddit_oauth)
, timeoutDelay )
kiwi_reddit_token_refresh_interval =
timestamp: token_timestamp
intervalId: timeoutIntervalId
requestRedditOathToken = (kiwi_reddit_oauth) ->
currentTime = Date.now()
Request({
url: 'https://www.reddit.com/api/v1/access_token',
headers: {
'Authorization': 'Basic ' + base64.encode(kiwi_reddit_oauth.client_id + ":")
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
},
content: {
grant_type: "https://oauth.reddit.com/grants/installed_client"
device_id: kiwi_reddit_oauth.device_id
},
onComplete: (response) ->
if(response.status == 0 or response.status == 504 or response.status == 503 or
response.status == 502 or response.status == 401)
tryAgainTimestamp = currentTime + (1000 * 60 * 3)
setTimeout_forRedditRefresh(tryAgainTimestamp, kiwi_reddit_oauth)
send_kiwi_userMessage("redditDown")
# console.log('unavailable!2')
else
if response.json.access_token? and response.json.expires_in? and response.json.token_type == "bearer"
#console.log 'response from reddit!'
token_lifespan_timestamp = currentTime + response.json.expires_in * 1000
setObj =
token: response.json.access_token
token_type: 'bearer'
token_lifespan_timestamp: token_lifespan_timestamp
client_id: kiwi_reddit_oauth.client_id
device_id: kiwi_reddit_oauth.device_id
firefoxStorage.storage.kiwi_reddit_oauth = setObj
setTimeout_forRedditRefresh(token_lifespan_timestamp, setObj)
}).post()
setTimeout_forProductHuntRefresh = (token_timestamp, kiwi_productHunt_oauth, ignoreTimeoutDelayComparison = false) ->
currentTime = Date.now()
timeoutDelay = token_timestamp - currentTime
if kiwi_productHunt_token_refresh_interval? and kiwi_productHunt_token_refresh_interval.timestamp? and ignoreTimeoutDelayComparison is false
if timeoutDelay > kiwi_productHunt_token_refresh_interval.timestamp - currentTime
# console.log 'patience, we will be trying again soon'
return 0
if kiwi_productHunt_token_refresh_interval? and kiwi_productHunt_token_refresh_interval.timestamp?
clearTimeout(kiwi_productHunt_token_refresh_interval.intervalId)
timeoutIntervalId = setTimeout( ->
requestProductHuntOauthToken(kiwi_productHunt_oauth)
, timeoutDelay )
kiwi_productHunt_token_refresh_interval =
timestamp: token_timestamp
intervalId: timeoutIntervalId
requestProductHuntOauthToken = (kiwi_productHunt_oauth) ->
currentTime = Date.now()
Request({
content: {
"client_id": kiwi_productHunt_oauth.client_id
"client_secret": kiwi_productHunt_oauth.client_secret
"grant_type" : "client_credentials"
}
url: 'https://api.producthunt.com/v1/oauth/token'
headers: {}
onComplete: (response) ->
if(response.status == 0 or response.status == 504 or response.status == 503 or
response.status == 502 or response.status == 401)
# // do connection timeout handling
tryAgainTimestamp = currentTime + (1000 * 60 * 3)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, kiwi_productHunt_oauth)
send_kiwi_userMessage("productHuntDown")
# console.log('unavailable!3')
else
# console.log 'check this'
# console.log response.json
if response.json? and response.json.access_token? and response.json.expires_in? and response.json.token_type == "bearer"
token_lifespan_timestamp = currentTime + response.json.expires_in * 1000
setObj = {}
setObj =
token: response.json.access_token
scope: "public"
token_type: 'bearer'
token_lifespan_timestamp: token_lifespan_timestamp
client_id: kiwi_productHunt_oauth.client_id
client_secret: kiwi_productHunt_oauth.client_secret
firefoxStorage.storage.kiwi_productHunt_oauth = setObj
setTimeout_forProductHuntRefresh(token_lifespan_timestamp, setObj)
}).post()
negotiateOauthTokens = ->
currentTime = Date.now()
if !firefoxStorage.storage.kiwi_productHunt_oauth? or !firefoxStorage.storage.kiwi_productHunt_oauth.token?
# console.log 'ph oauth does not exist in firefox storage'
requestProductHuntOauthToken(temp__kiwi_productHunt_oauth)
if !firefoxStorage.storage.kiwi_productHunt_oauth? or !firefoxStorage.storage.kiwi_productHunt_oauth.token?
# do nothing
else if (firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp? and
currentTime > firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp) or
!firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp?
#console.log "3 setObj['kiwi_productHunt_oauth'] ="
requestProductHuntOauthToken(temp__kiwi_productHunt_oauth)
else if firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp? and firefoxStorage.storage.kiwi_productHunt_oauth?
#console.log "4 setObj['kiwi_productHunt_oauth'] ="
token_timestamp = firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp
if !kiwi_productHunt_token_refresh_interval? or kiwi_productHunt_token_refresh_interval.timestamp != token_timestamp
setTimeout_forProductHuntRefresh(token_timestamp, firefoxStorage.storage.kiwi_productHunt_oauth)
if !firefoxStorage.storage.kiwi_reddit_oauth? or !firefoxStorage.storage.kiwi_reddit_oauth.token?
requestRedditOathToken(temp__kiwi_reddit_oauth)
if !firefoxStorage.storage.kiwi_reddit_oauth? or !firefoxStorage.storage.kiwi_reddit_oauth.token?
# do nothing
else if (firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp? and
currentTime > firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp) or
!firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp?
#console.log "3 setObj['kiwi_reddit_oauth'] ="
requestRedditOathToken(temp__kiwi_reddit_oauth)
else if firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp? and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log "4 setObj['kiwi_reddit_oauth'] ="
token_timestamp = firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp
if !kiwi_reddit_token_refresh_interval? or kiwi_reddit_token_refresh_interval.timestamp != token_timestamp
setTimeout_forRedditRefresh(token_timestamp, firefoxStorage.storage.kiwi_reddit_oauth)
negotiateOauthTokens()
is_url_blocked = (blockedLists, url) ->
return doesURLmatchSubstringLists(blockedLists, url)
is_url_whitelisted = (whiteLists, url) ->
return doesURLmatchSubstringLists(whiteLists, url)
doesURLmatchSubstringLists = (urlSubstringLists, url) ->
if urlSubstringLists.anyMatch?
for urlSubstring in urlSubstringLists.anyMatch
if url.indexOf(urlSubstring) != -1
return true
if urlSubstringLists.beginsWith?
for urlSubstring in urlSubstringLists.beginsWith
if url.indexOf(urlSubstring) == 0
return true
if urlSubstringLists.endingIn?
for urlSubstring in urlSubstringLists.endingIn
if url.indexOf(urlSubstring) == url.length - urlSubstring.length
return true
urlSubstring += '/'
if url.indexOf(urlSubstring) == url.length - urlSubstring.length
return true
if urlSubstringLists.unless?
for urlSubstringArray in urlSubstringLists.unless
if url.indexOf(urlSubstringArray[0]) != -1
if url.indexOf(urlSubstringArray[1]) == -1
return true
return false
returnNumberOfActiveServices = (servicesInfo) ->
numberOfActiveServices = 0
for service in servicesInfo
if service.active == 'on'
numberOfActiveServices++
return numberOfActiveServices
sendParcel = (parcel) ->
if !parcel.msg? or !parcel.forUrl?
return false
switch parcel.msg
when 'kiwiPP_popupParcel_ready'
kiwi_panel.port.emit('kiwi_fromBackgroundToPopup', parcel)
_save_a_la_carte = (parcel) ->
firefoxStorage.storage[parcel.keyName] = parcel.newValue
if !tempResponsesStore? or !tempResponsesStore.services?
tempResponsesStoreServices = {}
else
tempResponsesStoreServices = tempResponsesStore.services
if parcel.refreshView?
_set_popupParcel(tempResponsesStoreServices, tabUrl, true, parcel.refreshView)
else
_set_popupParcel(tempResponsesStoreServices, tabUrl, false)
kiwi_panel.port.on("kiwiPP_acknowledgeMessage", (dataFromPopup) ->
popupOpen = true
currentTime = Date.now()
for sentInstance, index in kiwi_userMessages[dataFromPopup.messageToAcknowledge].sentAndAcknowledgedInstanceObjects
if !sentInstance.userAcknowledged?
kiwi_userMessages[dataFromPopup.messageToAcknowledge].sentAndAcknowledgedInstanceObjects[index] = currentTime
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else if tempResponsesStore? and tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
)
kiwi_panel.port.on("kiwiPP_post_customSearch", (dataFromPopup) ->
popupOpen = true
if dataFromPopup.customSearchRequest? and dataFromPopup.customSearchRequest.queryString? and
dataFromPopup.customSearchRequest.queryString != ''
if firefoxStorage.storage['kiwi_servicesInfo']?
# #console.log 'when kiwiPP_post_customSearch3'
for serviceInfoObject in firefoxStorage.storage['kiwi_servicesInfo']
#console.log 'when kiwiPP_post_customSearch4 for ' + serviceInfoObject.name
if dataFromPopup.customSearchRequest.servicesToSearch[serviceInfoObject.name]?
# console.log 'trying custom search PH'
# console.log dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults
if serviceInfoObject.name is 'productHunt' and dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults?
responsePackage = {
servicesInfo: firefoxStorage.storage['kiwi_servicesInfo']
servicesToSearch: dataFromPopup.customSearchRequest.servicesToSearch
customSearchQuery: dataFromPopup.customSearchRequest.queryString
serviceName: serviceInfoObject.name
queryResult: dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults
}
setPreppedServiceResults__customSearch(responsePackage, firefoxStorage.storage['kiwi_servicesInfo'])
else
if serviceInfoObject.customSearchApi? and serviceInfoObject.customSearchApi != ''
dispatchQuery__customSearch(dataFromPopup.customSearchRequest.queryString, dataFromPopup.customSearchRequest.servicesToSearch, serviceInfoObject, firefoxStorage.storage['kiwi_servicesInfo'])
)
kiwi_panel.port.on "kiwiPP_researchUrlOverrideButton", (dataFromPopup) ->
popupOpen = true
initIfNewURL(true,true)
kiwi_panel.port.on "kiwiPP_clearAllURLresults", (dataFromPopup) ->
popupOpen = true
updateBadgeText('')
kiwi_urlsResultsCache = {}
tempResponsesStore = {}
_set_popupParcel({}, tabUrl, true)
kiwi_panel.port.on "kiwiPP_refreshSearchQuery", (dataFromPopup) ->
popupOpen = true
kiwi_customSearchResults = {}
if tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
kiwi_panel.port.on "kiwiPP_refreshURLresults", (dataFromPopup) ->
popupOpen = true
if kiwi_urlsResultsCache? and kiwi_urlsResultsCache[tabUrl]?
delete kiwi_urlsResultsCache[tabUrl]
tempResponsesStore = {}
initIfNewURL(true)
kiwi_panel.port.on "kiwiPP_reset_timer", (dataFromPopup) ->
popupOpen = true
dataFromPopup.kiwi_userPreferences['autoOffAtUTCmilliTimestamp'] = setAutoOffTimer(true,
dataFromPopup.kiwi_userPreferences.autoOffAtUTCmilliTimestamp,
dataFromPopup.kiwi_userPreferences.autoOffTimerValue,
dataFromPopup.kiwi_userPreferences.autoOffTimerType,
dataFromPopup.kiwi_userPreferences.researchModeOnOff
)
parcel =
refreshView: 'userPreferences'
keyName: 'kiwi_userPreferences'
newValue: dataFromPopup.kiwi_userPreferences
localOrSync: 'sync'
_save_a_la_carte(parcel)
kiwi_panel.port.on "kiwiPP_post_save_a_la_carte", (dataFromPopup) ->
popupOpen = true
_save_a_la_carte(dataFromPopup)
kiwi_panel.port.on "kiwiPP_post_savePopupParcel", (dataFromPopup) ->
popupOpen = true
_save_from_popupParcel(dataFromPopup.newPopupParcel, tabUrl, dataFromPopup.refreshView)
if kiwi_urlsResultsCache[tabUrl]?
refreshBadge(dataFromPopup.newPopupParcel.kiwi_servicesInfo, kiwi_urlsResultsCache[tabUrl])
kiwi_panel.port.on "kiwiPP_request_popupParcel", (dataFromPopup) ->
kiwiPP_request_popupParcel(dataFromPopup)
initialize = (currentUrl) ->
if !firefoxStorage.storage.kiwi_servicesInfo?
firefoxStorage.storage.kiwi_servicesInfo = defaultServicesInfo
getUrlResults_to_refreshBadgeIcon(defaultServicesInfo, currentUrl)
else
getUrlResults_to_refreshBadgeIcon(firefoxStorage.storage['kiwi_servicesInfo'], currentUrl)
getUrlResults_to_refreshBadgeIcon = (servicesInfo, currentUrl) ->
currentTime = Date.now()
if Object.keys(kiwi_urlsResultsCache).length > 0
# to prevent repeated api requests - we check to see if we have up-to-date request results in local storage
if kiwi_urlsResultsCache[currentUrl]?
# start off by instantly updating UI with what we know
refreshBadge(servicesInfo, kiwi_urlsResultsCache[currentUrl])
for service in servicesInfo
if kiwi_urlsResultsCache[currentUrl][service.name]?
if (currentTime - kiwi_urlsResultsCache[currentUrl][service.name].timestamp) > checkForUrlHourInterval * 3600000
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
return 0
else
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
return 0
# for urls that are being visited a second time,
# all recent results present kiwi_urlsResultsCache (for all services)
# we set tempResponsesStore before setting popupParcel
tempResponsesStore.forUrl = currentUrl
tempResponsesStore.services = kiwi_urlsResultsCache[currentUrl]
#console.log '#console.debug tempResponsesStore.services'
#console.debug tempResponsesStore.services
_set_popupParcel(tempResponsesStore.services, currentUrl, true)
else
# this url has not been checked
#console.log '# this url has not been checked'
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
else
#console.log '# no urls have been checked'
check_updateServiceResults(servicesInfo, currentUrl, null)
_save_url_results = (servicesInfo, tempResponsesStore, _urlsResultsCache) ->
#console.log 'yolo 3'
urlsResultsCache = _.extend {}, _urlsResultsCache
previousUrl = tempResponsesStore.forUrl
if urlsResultsCache[previousUrl]?
# these will always be at least as recent as what's in the store.
for service in servicesInfo
if tempResponsesStore.services[service.name]?
urlsResultsCache[previousUrl][service.name] =
forUrl: previousUrl
timestamp: tempResponsesStore.services[service.name].timestamp
service_PreppedResults: tempResponsesStore.services[service.name].service_PreppedResults
else
urlsResultsCache[previousUrl] = {}
urlsResultsCache[previousUrl] = tempResponsesStore.services
return urlsResultsCache
__randomishStringPadding = ->
randomPaddingLength = getRandom(1,3)
characterCounter = 0
paddingString = ""
while characterCounter <= randomPaddingLength
randomLatinKeycode = getRandom(33,121)
String.fromCharCode(randomLatinKeycode)
paddingString += String.fromCharCode(randomLatinKeycode)
characterCounter++
return paddingString
toSHA512 = (str) ->
# // Convert string to an array of bytes
array = Array.prototype.slice.call(str)
# // Create SHA512 hash
hashEngine = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash)
hashEngine.init(hashEngine.MD5)
hashEngine.update(array, array.length)
return hashEngine.finish(true)
_save_historyBlob = (kiwi_urlsResultsCache, tabUrl) ->
tabUrl_hash = toSHA512(tabUrl)
# firefox's toSHA512 function usually returned a string ending in "=="
tabUrl_hash = tabUrl_hash.substring(0, tabUrl_hash.length - 2);
historyString = reduceHashByHalf(tabUrl_hash)
paddedHistoryString = __randomishStringPadding() + historyString + __randomishStringPadding()
if firefoxStorage.storage.kiwi_historyBlob? and typeof firefoxStorage.storage.kiwi_historyBlob == 'string' and
firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) < 15000 and firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) != -1
#console.log '# already exists in history blob ' + allItemsInLocalStorage.kiwi_historyBlob.indexOf(historyString)
return 0
else
if firefoxStorage.storage['kiwi_historyBlob']?
newKiwi_historyBlob = paddedHistoryString + firefoxStorage.storage['kiwi_historyBlob']
else
newKiwi_historyBlob = paddedHistoryString
# we cap the size of the history blob at 17000 characters
if firefoxStorage.storage.kiwi_historyBlob? and firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) > 17000
newKiwi_historyBlob = newKiwi_historyBlob.substring(0,15500)
firefoxStorage.storage.kiwi_historyBlob = newKiwi_historyBlob
check_updateServiceResults = (servicesInfo, currentUrl, urlsResultsCache = null) ->
#console.log 'yolo 4'
# if any results from previous tab have not been set, set them.
if urlsResultsCache? and Object.keys(tempResponsesStore).length > 0
previousResponsesStore = _.extend {}, tempResponsesStore
_urlsResultsCache = _.extend {}, urlsResultsCache
kiwi_urlsResultsCache = _save_url_results(servicesInfo, previousResponsesStore, _urlsResultsCache)
_save_historyBlob(kiwi_urlsResultsCache, previousResponsesStore.forUrl)
# refresh tempResponsesStore for new url
tempResponsesStore.forUrl = currentUrl
tempResponsesStore.services = {}
currentTime = Date.now()
if !urlsResultsCache?
urlsResultsCache = {}
if !urlsResultsCache[currentUrl]?
urlsResultsCache[currentUrl] = {}
# #console.log 'about to check for dispatch query'
# #console.debug urlsResultsCache[currentUrl]
# check on a service-by-service basis (so we don't requery all services just b/c one api/service is down)
for service in servicesInfo
# #console.log 'for service in servicesInfo'
# #console.debug service
if service.active == 'on'
if urlsResultsCache[currentUrl][service.name]?
if (currentTime - urlsResultsCache[currentUrl][service.name].timestamp) > checkForUrlHourInterval * 3600000
dispatchQuery(service, currentUrl, servicesInfo)
else
dispatchQuery(service, currentUrl, servicesInfo)
dispatchQuery = (service_info, currentUrl, servicesInfo) ->
# console.log 'yolo 5 ~ for ' + service_info.name
currentTime = Date.now()
# self imposed rate limiting per api
if !serviceQueryTimestamps[service_info.name]?
serviceQueryTimestamps[service_info.name] = currentTime
else
if (currentTime - serviceQueryTimestamps[service_info.name]) < queryThrottleSeconds * 1000
#wait a couple seconds before querying service
#console.log 'too soon on dispatch, waiting a couple seconds'
setTimeout(->
dispatchQuery(service_info, currentUrl, servicesInfo)
, 2000
)
return 0
else
serviceQueryTimestamps[service_info.name] = currentTime
queryObj = {
url: service_info.queryApi + encodeURIComponent(currentUrl),
onComplete: (queryResult) ->
if queryResult.status == 401
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated4');
setPreppedServiceResults(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
if service_info.name is 'productHunt'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
else if service_info.name is 'reddit'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
else if (queryResult.status == 0 or queryResult.status == 504 or queryResult.status == 503 or
queryResult.status == 502)
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated4');
setPreppedServiceResults(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
else
# console.log 'back with'
# for key, val of queryResult
# console.log key + ' : ' + val
responsePackage =
forUrl: currentUrl
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: queryResult.json
setPreppedServiceResults(responsePackage, servicesInfo)
}
headers = {}
if service_info.name is 'reddit' and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log 'we are trying with oauth!'
#console.debug allItemsInLocalStorage.kiwi_reddit_oauth
queryObj.headers =
'Authorization': "'bearer " + firefoxStorage.storage.kiwi_reddit_oauth.token + "'"
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
else if service_info.name is 'reddit' and !firefoxStorage.storage.kiwi_reddit_oauth?
# console.log 'adfaeaefae'
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated5');
setPreppedServiceResults(responsePackage, servicesInfo)
# if kiwi_userMessages[service_info.name + "Down"]?
# send_kiwi_userMessage(service_info.name + "Down")
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
return 0
# console.log firefoxStorage.storage.kiwi_productHunt_oauth.token
if service_info.name is 'productHunt' and firefoxStorage.storage.kiwi_productHunt_oauth?
# console.log 'trying PH with'
# console.debug allItemsInLocalStorage.kiwi_productHunt_oauth
queryObj.headers =
'Authorization': "Bearer " + firefoxStorage.storage.kiwi_productHunt_oauth.token
'Accept': 'application/json'
'Content-Type': 'application/json'
else if service_info.name is 'productHunt' and !firefoxStorage.storage.kiwi_productHunt_oauth?
# console.log 'asdfasdfasdfdas'
# call out and to a reset / refresh timer thingy
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated5');
setPreppedServiceResults(responsePackage, servicesInfo)
# if kiwi_userMessages[service_info.name + "Down"]?
# send_kiwi_userMessage(service_info.name + "Down")
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
return 0
Request(queryObj).get()
dispatchQuery__customSearch = (customSearchQuery, servicesToSearch, service_info, servicesInfo) ->
#console.log 'yolo 5 ~ for CUSTOM ' + service_info.name
#console.debug servicesToSearch
currentTime = Date.now()
# self imposed rate limiting per api
if !serviceQueryTimestamps[service_info.name]?
serviceQueryTimestamps[service_info.name] = currentTime
else
if (currentTime - serviceQueryTimestamps[service_info.name]) < queryThrottleSeconds * 1000
#wait a couple seconds before querying service
#console.log 'too soon on dispatch, waiting a couple seconds'
setTimeout(->
dispatchQuery__customSearch(customSearchQuery, servicesToSearch, service_info, servicesInfo)
, 2000
)
return 0
else
serviceQueryTimestamps[service_info.name] = currentTime
queryUrl = service_info.customSearchApi + encodeURIComponent(customSearchQuery)
if servicesToSearch[service_info.name].customSearchTags? and Object.keys(servicesToSearch[service_info.name].customSearchTags).length > 0
for tagIdentifier, tagObject of servicesToSearch[service_info.name].customSearchTags
queryUrl = queryUrl + service_info.customSearchTags__convention.string + service_info.customSearchTags[tagIdentifier].string
#console.log 'asd;lfkjaewo;ifjae; '
# console.log 'for tagIdentifier, tagObject of servicesToSearch[service_info.name].customSearchTags'
# console.log queryUrl
# tagObject might one day accept special parameters like author name, etc
queryObj = {
url: queryUrl,
onComplete: (queryResult) ->
if queryResult.status == 401
responsePackage = {
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: null
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
};
# console.log('unauthenticated1');
setPreppedServiceResults__customSearch(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
if service_info.name is 'productHunt'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
else if service_info.name is 'reddit'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
else if (queryResult.status == 0 or queryResult.status == 504 or queryResult.status == 503 or
queryResult.status == 502)
responsePackage = {
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: null
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
};
# console.log('Fail!1');
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
setPreppedServiceResults__customSearch(responsePackage, servicesInfo);
else
# console.log 'onComplete: (queryResult) ->'
# console.log queryResult.json
responsePackage = {
# forUrl: currentUrl
servicesInfo: servicesInfo
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
serviceName: service_info.name
queryResult: queryResult.json
}
setPreppedServiceResults__customSearch(responsePackage, servicesInfo)
}
headers = {}
if service_info.name is 'reddit' and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log 'we are trying with oauth!'
#console.debug allItemsInLocalStorage.kiwi_reddit_oauth
queryObj.headers =
'Authorization': "'bearer " + firefoxStorage.storage.kiwi_reddit_oauth.token + "'"
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
# console.log 'console.log queryObj monkeybutt'
# console.log queryObj
Request(queryObj).get()
# proactively set if all service_PreppedResults are ready.
# will be set with available results if queried by popup.
# the popup should always have enough to render with a properly set popupParcel.
setPreppedServiceResults__customSearch = (responsePackage, servicesInfo) ->
# console.log 'yolo 6'
currentTime = Date.now()
for serviceObj in servicesInfo
if serviceObj.name == responsePackage.serviceName
serviceInfo = serviceObj
# responsePackage =
# servicesInfo: servicesInfo
# serviceName: service_info.name
# queryResult: queryResult
# servicesToSearch: servicesToSearch
# customSearchQuery: customSearchQuery
# kiwi_customSearchResults = {} # stores temporarily so if they close popup, they'll still have results
# maybe it won't clear until new result -- "see last search"
# queryString
# servicesSearchesRequested = responsePackage.servicesToSearch
# servicesSearched
# <serviceName>
# results
# even if there are zero matches returned, that counts as a proper query response
service_PreppedResults = parseResults[responsePackage.serviceName](responsePackage.queryResult, responsePackage.customSearchQuery, serviceInfo, true)
if kiwi_customSearchResults? and kiwi_customSearchResults.queryString? and
kiwi_customSearchResults.queryString == responsePackage.customSearchQuery
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName] = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName].results = service_PreppedResults
else
kiwi_customSearchResults = {}
kiwi_customSearchResults.queryString = responsePackage.customSearchQuery
kiwi_customSearchResults.servicesSearchesRequested = responsePackage.servicesToSearch
kiwi_customSearchResults.servicesSearched = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName] = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName].results = service_PreppedResults
# console.log 'yolo 6 results service_PreppedResults'
# console.debug service_PreppedResults
#console.log 'numberOfActiveServices'
#console.debug returnNumberOfActiveServices(servicesInfo)
numberOfActiveServices = Object.keys(responsePackage.servicesToSearch).length
completedQueryServicesArray = []
#number of completed responses
if kiwi_customSearchResults.queryString == responsePackage.customSearchQuery
for serviceName, service of kiwi_customSearchResults.servicesSearched
completedQueryServicesArray.push(serviceName)
completedQueryServicesArray = _.uniq(completedQueryServicesArray)
#console.log 'completedQueryServicesArray.length '
#console.log completedQueryServicesArray.length
if completedQueryServicesArray.length is numberOfActiveServices and numberOfActiveServices != 0
# NO LONGER STORING URL CACHE IN LOCALSTORAGE - BECAUSE : INFORMATION LEAKAGE / BROKEN EXTENSION SECURITY MODEL
# get a fresh copy of urls results and reset with updated info
# chrome.storage.local.get(null, (allItemsInLocalStorage) ->
# #console.log 'trying to save all'
# if !allItemsInLocalStorage['kiwi_urlsResultsCache']?
# allItemsInLocalStorage['kiwi_urlsResultsCache'] = {}
# console.log 'yolo 6 _save_ results(servicesInfo, tempRes -- for ' + serviceInfo.name
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
# else
# #console.log 'yolo 6 not finished ' + serviceInfo.name
# _set_popupParcel(tempResponsesStore.services, responsePackage.forUrl, false)
_set_popupParcel = (setWith_urlResults = {}, forUrl, sendPopupParcel, renderView = null, oldUrl = false) ->
# console.log 'monkey butt _set_popupParcel = (setWith_urlResults, forUrl, sendPopupParcel, '
#console.log 'trying to set popupParcel, forUrl tabUrl' + forUrl + tabUrl
# tabUrl
if setWith_urlResults != {}
if forUrl != tabUrl
#console.log "_set_popupParcel request for old url"
return false
setObj_popupParcel = {}
setObj_popupParcel.forUrl = tabUrl
if !firefoxStorage.storage['kiwi_userPreferences']?
setObj_popupParcel.kiwi_userPreferences = defaultUserPreferences
else
setObj_popupParcel.kiwi_userPreferences = firefoxStorage.storage['kiwi_userPreferences']
if !firefoxStorage.storage['kiwi_servicesInfo']?
setObj_popupParcel.kiwi_servicesInfo = defaultServicesInfo
else
setObj_popupParcel.kiwi_servicesInfo = firefoxStorage.storage['kiwi_servicesInfo']
if renderView != null
setObj_popupParcel.view = renderView
if !firefoxStorage.storage['kiwi_alerts']?
setObj_popupParcel.kiwi_alerts = []
else
setObj_popupParcel.kiwi_alerts = firefoxStorage.storage['kiwi_alerts']
setObj_popupParcel.kiwi_customSearchResults = kiwi_customSearchResults
if !setWith_urlResults?
#console.log '_set_popupParcel called with undefined responses (not supposed to happen, ever)'
return 0
else
setObj_popupParcel.allPreppedResults = setWith_urlResults
if tabUrl == forUrl
setObj_popupParcel.tabInfo = {}
setObj_popupParcel.tabInfo.tabUrl = tabUrl
setObj_popupParcel.tabInfo.tabTitle = tabTitleObject.tabTitle
else
setObj_popupParcel.tabInfo = null
setObj_popupParcel.urlBlocked = false
isUrlBlocked = is_url_blocked(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true
setObj_popupParcel.urlBlocked = true
if oldUrl is true
setObj_popupParcel.oldUrl = true
else
setObj_popupParcel.oldUrl = false
setObj_popupParcel.kiwi_userMessages = []
for messageName, messageObj of kiwi_userMessages
for sentInstance in messageObj.sentAndAcknowledgedInstanceObjects
if sentInstance.userAcknowledged is null
setObj_popupParcel.kiwi_userMessages.push messageObj
popupParcel = setObj_popupParcel
if sendPopupParcel
parcel = {}
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = setObj_popupParcel
sendParcel(parcel)
setPreppedServiceResults = (responsePackage, servicesInfo) ->
currentTime = Date.now()
# if tabUrl == responsePackage.forUrl # if false, then do nothing (user's probably switched to new tab)
for serviceObj in servicesInfo
if serviceObj.name == responsePackage.serviceName
serviceInfo = serviceObj
# serviceInfo = servicesInfo[responsePackage.serviceName]
# even if there are zero matches returned, that counts as a proper query response
service_PreppedResults = parseResults[responsePackage.serviceName](responsePackage.queryResult, tabUrl, serviceInfo)
if !tempResponsesStore.services?
tempResponsesStore = {}
tempResponsesStore.services = {}
tempResponsesStore.services[responsePackage.serviceName] =
timestamp: currentTime
service_PreppedResults: service_PreppedResults
forUrl: tabUrl
#console.log 'yolo 6 results service_PreppedResults'
#console.debug service_PreppedResults
#console.log 'numberOfActiveServices'
#console.debug returnNumberOfActiveServices(servicesInfo)
numberOfActiveServices = returnNumberOfActiveServices(servicesInfo)
completedQueryServicesArray = []
#number of completed responses
if tempResponsesStore.forUrl == tabUrl
for serviceName, service of tempResponsesStore.services
completedQueryServicesArray.push(serviceName)
if kiwi_urlsResultsCache[tabUrl]?
for serviceName, service of kiwi_urlsResultsCache[tabUrl]
completedQueryServicesArray.push(serviceName)
completedQueryServicesArray = _.uniq(completedQueryServicesArray)
if completedQueryServicesArray.length is numberOfActiveServices and numberOfActiveServices != 0
# NO LONGER STORING URL CACHE IN LOCALSTORAGE - BECAUSE 1.) INFORMATION LEAKAGE, 2.) SLOWER
# get a fresh copy of urls results and reset with updated info
# chrome.storage.local.get(null, (allItemsInLocalStorage) ->
# #console.log 'trying to save all'
# if !allItemsInLocalStorage['kiwi_urlsResultsCache']?
# allItemsInLocalStorage['kiwi_urlsResultsCache'] = {}
#console.log 'yolo 6 _save_url_results(servicesInfo, tempRes -- for ' + serviceInfo.name
kiwi_urlsResultsCache = _save_url_results(servicesInfo, tempResponsesStore, kiwi_urlsResultsCache)
_save_historyBlob(kiwi_urlsResultsCache, tabUrl)
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
refreshBadge(servicesInfo, kiwi_urlsResultsCache[tabUrl])
else
#console.log 'yolo 6 not finished ' + serviceInfo.name
_set_popupParcel(tempResponsesStore.services, tabUrl, false)
refreshBadge(servicesInfo, tempResponsesStore.services)
#returns an array of 'preppedResults' for url - just the keys we care about from the query-response
parseResults =
productHunt: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
# console.log 'resultsObj'
# console.log 'for: ' + searchQueryString
# console.debug resultsObj
# console.log 'customSearchBool ' + customSearchBool
# console.log resultsObj.posts
matchedListings = [];
if ( resultsObj == null )
return matchedListings;
if customSearchBool is false # so, normal URL-based queries
# created_at: "2014-08-18T06:40:47.000-07:00"
# discussion_url: "http://www.producthunt.com/tech/product-hunt-api-beta"
# comments_count: 13
# votes_count: 514
# name: "Product Hunt API (beta)"
# featured: true
# id: 6970
# maker_inside: true
# tagline: "Make stuff with us. Signup for early access to the PH API :)"
# user:
# headline: "Tech at Product Hunt 💃"
# profile_url: "http://www.producthunt.com/@andreasklinger"
# name: "Andreas Klinger"
# username: "andreasklinger"
# website_url: "http://klinger.io"
if resultsObj.posts? and _.isArray(resultsObj.posts) is true
for post in resultsObj.posts
listingKeys = [
'created_at','discussion_url','comments_count','redirect_url','votes_count','name',
'featured','id','user','screenshot_url','tagline','maker_inside','makers'
]
preppedResult = _.pick(post, listingKeys)
preppedResult.kiwi_created_at = Date.parse(preppedResult.created_at)
preppedResult.kiwi_discussion_url = preppedResult.discussion_url
if preppedResult.user? and preppedResult.user.name?
preppedResult.kiwi_author_name = preppedResult.user.name.trim()
else
preppedResult.kiwi_author_name = ""
if preppedResult.user? and preppedResult.user.username?
preppedResult.kiwi_author_username = preppedResult.user.username
else
preppedResult.kiwi_author_username = ""
if preppedResult.user? and preppedResult.user.headline?
preppedResult.kiwi_author_headline = preppedResult.user.headline.trim()
else
preppedResult.kiwi_author_headline = ""
preppedResult.kiwi_makers = []
for maker, index in post.makers
makerObj = {}
makerObj.headline = maker.headline
makerObj.name = maker.name
makerObj.username = maker.username
makerObj.profile_url = maker.profile_url
makerObj.website_url = maker.website_url
preppedResult.kiwi_makers.push makerObj
preppedResult.kiwi_exact_match = true # PH won't return fuzzy matches
preppedResult.kiwi_score = preppedResult.votes_count
preppedResult.kiwi_num_comments = preppedResult.comments_count
preppedResult.kiwi_permaId = preppedResult.permalink
matchedListings.push preppedResult
else # custom string queries
# comment_count
# vote_count
# name
# url #
# tagline
# category
# tech
# product_makers
# headline
# name
# username
# is_maker
# console.log ' else # custom string queries ' + _.isArray(resultsObj) #
if resultsObj? and _.isArray(resultsObj)
# console.log ' yoyoyoy1 '
for searchMatch in resultsObj
listingKeys = [
'author'
'url',
'tagline',
'product_makers'
'comment_count',
'vote_count',
'name',
'id',
'user',
'screenshot_url',
]
preppedResult = _.pick(searchMatch, listingKeys)
preppedResult.kiwi_created_at = null # algolia doesn't provide created at value :<
preppedResult.kiwi_discussion_url = "http://www.producthunt.com/" + preppedResult.url
if preppedResult.author? and preppedResult.author.name?
preppedResult.kiwi_author_name = preppedResult.author.name.trim()
else
preppedResult.kiwi_author_name = ""
if preppedResult.author? and preppedResult.author.username?
preppedResult.kiwi_author_username = preppedResult.author.username
else
preppedResult.kiwi_author_username = ""
if preppedResult.author? and preppedResult.author.headline?
preppedResult.kiwi_author_headline = preppedResult.author.headline.trim()
else
preppedResult.kiwi_author_headline = ""
preppedResult.kiwi_makers = []
for maker, index in searchMatch.product_makers
makerObj = {}
makerObj.headline = maker.headline
makerObj.name = maker.name
makerObj.username = maker.username
makerObj.profile_url = maker.profile_url
makerObj.website_url = maker.website_url
preppedResult.kiwi_makers.push makerObj
preppedResult.kiwi_exact_match = true # PH won't return fuzzy matches
preppedResult.kiwi_score = preppedResult.vote_count
preppedResult.kiwi_num_comments = preppedResult.comment_count
preppedResult.kiwi_permaId = preppedResult.permalink
matchedListings.push preppedResult
return matchedListings
reddit: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
matchedListings = []
if ( resultsObj == null )
return matchedListings
# console.log 'reddit: (resultsObj) ->'
# console.debug resultsObj
# occasionally Reddit will decide to return an array instead of an object, so...
# in response to user's feedback, see: https://news.ycombinator.com/item?id=9994202
forEachQueryObject = (resultsObj, _matchedListings) ->
if resultsObj.kind? and resultsObj.kind == "Listing" and resultsObj.data? and
resultsObj.data.children? and resultsObj.data.children.length > 0
for child in resultsObj.data.children
if child.data? and child.kind? and child.kind == "t3"
listingKeys = ["subreddit",'url',"score",'domain','gilded',"over_18","author","hidden","downs","permalink","created","title","created_utc","ups","num_comments"]
preppedResult = _.pick(child.data, listingKeys)
preppedResult.kiwi_created_at = preppedResult.created_utc * 1000 # to normalize to JS's Date.now() millisecond UTC timestamp
if customSearchBool is false
preppedResult.kiwi_exact_match = _exact_match_url_check(searchQueryString, preppedResult.url)
else
preppedResult.kiwi_exact_match = true
preppedResult.kiwi_score = preppedResult.score
preppedResult.kiwi_permaId = preppedResult.permalink
_matchedListings.push preppedResult
return _matchedListings
if _.isArray(resultsObj)
for result in resultsObj
matchedListings = forEachQueryObject(result, matchedListings)
else
matchedListings = forEachQueryObject(resultsObj, matchedListings)
return matchedListings
hackerNews: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
matchedListings = []
if ( resultsObj == null )
return matchedListings
#console.log ' hacker news #console.debug resultsObj'
#console.debug resultsObj
# if resultsObj.nbHits? and resultsObj.nbHits > 0 and resultsObj.hits? and resultsObj.hits.length is resultsObj.nbHits
if resultsObj? and resultsObj.hits?
for hit in resultsObj.hits
listingKeys = ["points","num_comments","objectID","author","created_at","title","url","created_at_i"
"story_text","comment_text","story_id","story_title","story_url"
]
preppedResult = _.pick(hit, listingKeys)
preppedResult.kiwi_created_at = preppedResult.created_at_i * 1000 # to normalize to JS's Date.now() millisecond UTC timestamp
if customSearchBool is false
preppedResult.kiwi_exact_match = _exact_match_url_check(searchQueryString, preppedResult.url)
else
preppedResult.kiwi_exact_match = true
preppedResult.kiwi_score = preppedResult.points
preppedResult.kiwi_permaId = preppedResult.objectID
matchedListings.push preppedResult
return matchedListings
_exact_match_url_check = (forUrl, preppedResultUrl) ->
# warning:: one of the worst algo-s i've ever written... please don't use as reference
kiwi_exact_match = false
modifications = [
name: 'trailingSlash'
modify: (tOrF, forUrl) ->
if tOrF is 't'
if forUrl[forUrl.length - 1] != '/'
trailingSlashURL = forUrl + '/'
else
trailingSlashURL = forUrl
return trailingSlashURL
else
if forUrl[forUrl.length - 1] == '/'
noTrailingSlashURL = forUrl.substr(0,forUrl.length - 1)
else
noTrailingSlashURL = forUrl
return noTrailingSlashURL
# if forUrl[forUrl.length - 1] == '/'
# noTrailingSlashURL = forUrl.substr(0,forUrl.length - 1)
existsTest: (forUrl) ->
if forUrl[forUrl.length - 1] == '/'
return 't'
else
return 'f'
,
name: 'www'
modify: (tOrF, forUrl) ->
if tOrF is 't'
protocolSplitUrlArray = forUrl.split('://')
if protocolSplitUrlArray.length > 1
if protocolSplitUrlArray[1].indexOf('www.') != 0
protocolSplitUrlArray[1] = 'www.' + protocolSplitUrlArray[1]
WWWurl = protocolSplitUrlArray.join('://')
else
WWWurl = forUrl
return WWWurl
else
if protocolSplitUrlArray[0].indexOf('www.') != 0
protocolSplitUrlArray[0] = 'www.' + protocolSplitUrlArray[1]
WWWurl = protocolSplitUrlArray.join('://')
else
WWWurl = forUrl
return WWWurl
else
wwwSplitUrlArray = forUrl.split('www.')
if wwwSplitUrlArray.length is 2
noWWWurl = wwwSplitUrlArray.join('')
else if wwwSplitUrlArray.length > 2
noWWWurl = wwwSplitUrlArray.shift()
noWWWurl += wwwSplitUrlArray.shift()
noWWWurl += wwwSplitUrlArray.join('www.')
else
noWWWurl = forUrl
return noWWWurl
existsTest: (forUrl) ->
if forUrl.split('//www.').length > 0
return 't'
else
return 'f'
,
name:'http'
existsTest: (forUrl) ->
if forUrl.indexOf('http://') is 0
return 't'
else
return 'f'
modify: (tOrF, forUrl) ->
if tOrF is 't'
if forUrl.indexOf('https://') == 0
HTTPurl = 'http://' + forUrl.substr(8, forUrl.length - 1)
else
HTTPurl = forUrl
else
if forUrl.indexOf('http://') == 0
HTTPSurl = 'https://' + forUrl.substr(7, forUrl.length - 1)
else
HTTPSurl = forUrl
]
modPermutations = {}
forUrlUnmodded = ''
for mod in modifications
forUrlUnmodded += mod.existsTest(forUrl)
modPermutations[forUrlUnmodded] = forUrl
existStates = ['t','f']
for existState in existStates
for mod, index in modifications
checkArray = []
for m in modifications
checkArray.push existState
forUrl_ = modifications[index].modify(existState, forUrl)
for existState_ in existStates
checkArray[index] = existState_
for mod_, index_ in modifications
if index != index_
for existState__ in existStates
checkArray[index_] = existState__
checkString = checkArray.join('')
if !modPermutations[checkString]?
altUrl = forUrl_
for existState_Char, cSindex in checkString
altUrl = modifications[cSindex].modify(existState_Char, altUrl)
modPermutations[checkString] = altUrl
kiwi_exact_match = false
if preppedResultUrl == forUrl
kiwi_exact_match = true
for modKey, moddedUrl of modPermutations
if preppedResultUrl == moddedUrl
kiwi_exact_match = true
return kiwi_exact_match
refreshBadge = (servicesInfo, resultsObjForCurrentUrl) ->
# #console.log 'yolo 8'
# #console.debug resultsObjForCurrentUrl
# #console.debug servicesInfo
# icon badges typically only have room for 5 characters
currentTime = Date.now()
abbreviationLettersArray = []
for service, index in servicesInfo
# if resultsObjForCurrentUrl[service.name]
if resultsObjForCurrentUrl[service.name]? and resultsObjForCurrentUrl[service.name].service_PreppedResults.length > 0
exactMatch = false
noteworthy = false
for listing in resultsObjForCurrentUrl[service.name].service_PreppedResults
if listing.kiwi_exact_match
exactMatch = true
if listing.num_comments? and listing.num_comments >= service.notableConditions.num_comments
noteworthy = true
break
if (currentTime - listing.kiwi_created_at) < service.notableConditions.hoursSincePosted * 3600000
noteworthy = true
break
if service.updateBadgeOnlyWithExactMatch and exactMatch = false
break
#console.log service.name + ' noteworthy ' + noteworthy
if noteworthy
abbreviationLettersArray.push service.abbreviation
else
abbreviationLettersArray.push service.abbreviation.toLowerCase()
#console.debug abbreviationLettersArray
badgeText = ''
if abbreviationLettersArray.length == 0
if firefoxStorage.storage.kiwi_userPreferences? and firefoxStorage.storage['kiwi_userPreferences'].researchModeOnOff == 'off'
badgeText = ''
else if defaultUserPreferences.researchModeOnOff == 'off'
badgeText = ''
else
badgeText = ''
else
badgeText = abbreviationLettersArray.join(" ")
#console.log 'yolo 8 ' + badgeText
updateBadgeText(badgeText)
periodicCleanup = (tab, initialize_callback) ->
#console.log 'wtf a'
currentTime = Date.now()
if(last_periodicCleanup < (currentTime - CLEANUP_INTERVAL))
last_periodicCleanup = currentTime
#console.log 'wtf b'
# delete any results older than checkForUrlHourInterval
if Object.keys(kiwi_urlsResultsCache).length is 0
#console.log 'wtf ba'
# nothing to (potentially) clean up!
initialize_callback(tab)
else
#console.log 'wtf bb'
# allItemsInLocalStorage.kiwi_urlsResultsCache
cull_kiwi_urlsResultsCache = _.extend {}, kiwi_urlsResultsCache
for url, urlServiceResults of cull_kiwi_urlsResultsCache
for serviceKey, serviceResults of urlServiceResults
if currentTime - serviceResults.timestamp > checkForUrlHourInterval
delete kiwi_urlsResultsCache[url]
if Object.keys(kiwi_urlsResultsCache).length > maxUrlResultsStoredInLocalStorage
# you've been surfing! wow
num_results_to_delete = Object.keys(kiwi_urlsResultsCache).length - maxUrlResultsStoredInLocalStorage
deletedCount = 0
cull_kiwi_urlsResultsCache = _.extend {}, kiwi_urlsResultsCache
for url, urlServiceResults of cull_kiwi_urlsResultsCache
if deleteCount >= num_results_to_delete
break
if url != tab.url
delete kiwi_urlsResultsCache[url]
deletedCount++
# chrome.storage.local.set({'kiwi_urlsResultsCache':kiwi_urlsResultsCache}, ->
initialize_callback(tab)
# )
else
initialize_callback(tab)
else
#console.log 'wtf c'
initialize_callback(tab)
_save_from_popupParcel = (_popupParcel, forUrl, updateToView) ->
formerResearchModeValue = null
formerKiwi_servicesInfo = null
former_autoOffTimerType = null
former_autoOffTimerValue = null
# #console.log '#console.debug popupParcel
# #console.debug _popupParcel'
# #console.debug popupParcel
# #console.debug _popupParcel
if popupParcel? and popupParcel.kiwi_userPreferences? and popupParcel.kiwi_servicesInfo
formerResearchModeValue = popupParcel.kiwi_userPreferences.researchModeOnOff
formerKiwi_servicesInfo = popupParcel.kiwi_servicesInfo
former_autoOffTimerType = popupParcel.kiwi_userPreferences.autoOffTimerType
former_autoOffTimerValue = popupParcel.kiwi_userPreferences.autoOffTimerValue
popupParcel = {}
# #console.log ' asdfasdfasd formerKiwi_autoOffTimerType'
# #console.log former_autoOffTimerType
# #console.log _popupParcel.kiwi_userPreferences.autoOffTimerType
# #console.log ' a;woeifjaw;ef formerKiwi_autoOffTimerValue'
# #console.log former_autoOffTimerValue
# #console.log _popupParcel.kiwi_userPreferences.autoOffTimerValue
if formerResearchModeValue? and formerResearchModeValue == 'off' and
_popupParcel.kiwi_userPreferences? and _popupParcel.kiwi_userPreferences.researchModeOnOff == 'on' or
(former_autoOffTimerType != _popupParcel.kiwi_userPreferences.autoOffTimerType or
former_autoOffTimerValue != _popupParcel.kiwi_userPreferences.autoOffTimerValue)
resetTimerBool = true
else
resetTimerBool = false
_autoOffAtUTCmilliTimestamp = setAutoOffTimer(resetTimerBool, _popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp,
_popupParcel.kiwi_userPreferences.autoOffTimerValue, _popupParcel.kiwi_userPreferences.autoOffTimerType,
_popupParcel.kiwi_userPreferences.researchModeOnOff)
_popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp = _autoOffAtUTCmilliTimestamp
firefoxStorage.storage.kiwi_userPreferences = _popupParcel.kiwi_userPreferences
firefoxStorage.storage.kiwi_servicesInfo = _popupParcel.kiwi_servicesInfo
if updateToView?
parcel = {}
_popupParcel['view'] = updateToView
popupParcel = _popupParcel
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = _popupParcel
sendParcel(parcel)
#console.log 'in _save_from_popupParcel _popupParcel.forUrl ' + _popupParcel.forUrl
#console.log 'in _save_from_popupParcel tabUrl ' + tabUrl
if _popupParcel.forUrl == tabUrl
if formerResearchModeValue? and formerResearchModeValue == 'off' and
_popupParcel.kiwi_userPreferences? and _popupParcel.kiwi_userPreferences.researchModeOnOff == 'on'
initIfNewURL(true); return 0
else if formerKiwi_servicesInfo?
# so if user turns on a service and saves - it will immediately begin new query
formerActiveServicesList = _.pluck(formerKiwi_servicesInfo, 'active')
newActiveServicesList = _.pluck(_popupParcel.kiwi_servicesInfo, 'active')
#console.log 'formerActiveServicesList = _.pluck(formerKiwi_servicesInfo)'
#console.debug formerActiveServicesList
#console.log 'newActiveServicesList = _.pluck(_popupParcel.kiwi_servicesInfo)'
#console.debug newActiveServicesList
if !_.isEqual(formerActiveServicesList, newActiveServicesList)
initIfNewURL(true); return 0
else
refreshBadge(_popupParcel.kiwi_servicesInfo, _popupParcel.allPreppedResults); return 0
else
refreshBadge(_popupParcel.kiwi_servicesInfo, _popupParcel.allPreppedResults); return 0
setAutoOffTimer = (resetTimerBool, autoOffAtUTCmilliTimestamp, autoOffTimerValue, autoOffTimerType, researchModeOnOff) ->
#console.log 'trying setAutoOffTimer 43234'
if resetTimerBool and kiwi_autoOffClearInterval?
#console.log 'clearing timout'
clearTimeout(kiwi_autoOffClearInterval)
kiwi_autoOffClearInterval = null
currentTime = Date.now()
new_autoOffAtUTCmilliTimestamp = null
if researchModeOnOff == 'on'
if autoOffAtUTCmilliTimestamp == null || resetTimerBool
if autoOffTimerType == '20'
new_autoOffAtUTCmilliTimestamp = currentTime + 20 * 60 * 1000
else if autoOffTimerType == '60'
new_autoOffAtUTCmilliTimestamp = currentTime + 60 * 60 * 1000
else if autoOffTimerType == 'always'
new_autoOffAtUTCmilliTimestamp = null
else if autoOffTimerType == 'custom'
new_autoOffAtUTCmilliTimestamp = currentTime + parseInt(autoOffTimerValue) * 60 * 1000
#console.log 'setting custom new_autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
else
new_autoOffAtUTCmilliTimestamp = autoOffAtUTCmilliTimestamp
if !kiwi_autoOffClearInterval? and autoOffAtUTCmilliTimestamp > currentTime
#console.log 'resetting timer timeout'
kiwi_autoOffClearInterval = setTimeout( ->
turnResearchModeOff()
, new_autoOffAtUTCmilliTimestamp - currentTime )
#console.log ' setting 123 autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
return new_autoOffAtUTCmilliTimestamp
else
# it's already off - no need for timer
new_autoOffAtUTCmilliTimestamp = null
#console.log 'researchModeOnOff is off - resetting autoOff timestamp and clearInterval'
if kiwi_autoOffClearInterval?
clearTimeout(kiwi_autoOffClearInterval)
kiwi_autoOffClearInterval = null
#console.log ' setting 000 autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
if new_autoOffAtUTCmilliTimestamp != null
#console.log 'setting timer timeout'
kiwi_autoOffClearInterval = setTimeout( ->
turnResearchModeOff()
, new_autoOffAtUTCmilliTimestamp - currentTime )
return new_autoOffAtUTCmilliTimestamp
turnResearchModeOff = ->
#console.log 'turning off research mode - in turnResearchModeOff'
# chrome.storage.sync.get(null, (allItemsInSyncedStorage) -> )
if kiwi_urlsResultsCache[tabUrl]?
urlResults = kiwi_urlsResultsCache[tabUrl]
else
urlResults = {}
if firefoxStorage.storage.kiwi_userPreferences?
firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff = 'off'
firefoxStorage.storage['kiwi_userPreferences'] = firefoxStorage.storage.kiwi_userPreferences
_set_popupParcel(urlResults, tabUrl, true)
if firefoxStorage.storage.kiwi_servicesInfo?
refreshBadge(firefoxStorage.storage.kiwi_servicesInfo, urlResults)
else
defaultUserPreferences.researchModeOnOff = 'off'
firefoxStorage.storage['kiwi_userPreferences'] = defaultUserPreferences
_set_popupParcel(urlResults, tabUrl, true)
if firefoxStorage.storage.kiwi_servicesInfo?
refreshBadge(firefoxStorage.storage.kiwi_servicesInfo, urlResults)
autoOffTimerExpired_orResearchModeOff_withoutURLoverride = (currentTime, overrideResearchModeOff, tabUrl, kiwi_urlsResultsCache) ->
if firefoxStorage.storage.kiwi_userPreferences?
if firefoxStorage.storage.kiwi_userPreferences.autoOffAtUTCmilliTimestamp?
if currentTime > firefoxStorage.storage.kiwi_userPreferences.autoOffAtUTCmilliTimestamp
#console.log 'timer is past due - turning off - in initifnewurl'
firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff = 'off'
if firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff is 'off' and overrideResearchModeOff == false
updateBadgeText('') # off
return true
return false
proceedWithPreInitCheck = (overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen) ->
if firefoxStorage.storage['kiwi_userPreferences']? and overrideResearchModeOff is false
# overrideResearchModeOff = is_url_whitelisted(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_whitelists, tabUrl)
isUrlWhitelistedBool = is_url_whitelisted(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_whitelists, tabUrl)
# provided that the user isn't specifically researching a URL, if it's whitelisted, then that acts as override
overrideResearchModeOff = isUrlWhitelistedBool
if autoOffTimerExpired_orResearchModeOff_withoutURLoverride(currentTime, overrideResearchModeOff, tabUrl, kiwi_urlsResultsCache) is true
# show cached responses, if present
#console.log 'if tabUrl == tempResponsesStore.forUrl'
#console.log tabUrl
#console.log tempResponsesStore.forUrl
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl],tabUrl,false);
if firefoxStorage.storage['kiwi_servicesInfo']?
refreshBadge(firefoxStorage.storage['kiwi_servicesInfo'], kiwi_urlsResultsCache[tabUrl])
else
_set_popupParcel({},tabUrl,true);
else
periodicCleanup(tabUrl, (tabUrl) ->
#console.log 'in initialize callback'
if !firefoxStorage.storage['kiwi_userPreferences']?
# defaultUserPreferences
#console.log "#console.debug allItemsInSyncedStorage['kiwi_userPreferences']"
#console.debug allItemsInSyncedStorage['kiwi_userPreferences']
_autoOffAtUTCmilliTimestamp = setAutoOffTimer(false, defaultUserPreferences.autoOffAtUTCmilliTimestamp,
defaultUserPreferences.autoOffTimerValue, defaultUserPreferences.autoOffTimerType, defaultUserPreferences.researchModeOnOff)
defaultUserPreferences.autoOffAtUTCmilliTimestamp = _autoOffAtUTCmilliTimestamp
# setObj =
# kiwi_servicesInfo: defaultServicesInfo
# kiwi_userPreferences: defaultUserPreferences
firefoxStorage.storage.kiwi_servicesInfo = defaultServicesInfo
firefoxStorage.storage.kiwi_userPreferences = defaultUserPreferences
# chrome.storage.sync.set(setObj, -> )
isUrlBlocked = is_url_blocked(defaultUserPreferences.urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true and overrideResearchModeOff == false
# user is not interested in results for this url
updateBadgeText('block')
#console.log '# user is not interested in results for this url: ' + tabUrl
_set_popupParcel({}, tabUrl, true) # trying to send, because options page
return 0 # we return before initializing script
initialize(tabUrl)
else
#console.log "allItemsInSyncedStorage['kiwi_userPreferences'].urlSubstring_blacklists"
#console.debug allItemsInSyncedStorage['kiwi_userPreferences'].urlSubstring_blacklists
isUrlBlocked = is_url_blocked(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true and overrideResearchModeOff == false
# user is not interested in results for this url
updateBadgeText('block')
#console.log '# user is not interested in results for this url: ' + tabUrl
_set_popupParcel({}, tabUrl, true) # trying to send, because options page
return 0 # we return/cease before initializing script
initialize(tabUrl)
)
checkForNewDefaultUserPreferenceAttributes_thenProceedWithInitCheck = (overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen) ->
# ^^ checks if newly added default user preference attributes exist (so new features don't break current installs)
setObj = {}
newUserPrefsAttribute = false
newServicesInfoAttribute = false
newServicesInfo = []
newUserPreferences = {}
if firefoxStorage.storage['kiwi_userPreferences']?
newUserPreferences = _.extend {}, firefoxStorage.storage['kiwi_userPreferences']
for keyName, value of defaultUserPreferences
if typeof firefoxStorage.storage['kiwi_userPreferences'][keyName] is 'undefined'
# console.log 'the following is a new keyName '
# console.log keyName
newUserPrefsAttribute = true
newUserPreferences[keyName] = value
if firefoxStorage.storage['kiwi_servicesInfo']?
# needs to handle entirely new services as well as simplly new attributes
newServicesInfo = _.extend [], firefoxStorage.storage['kiwi_servicesInfo']
for service_default, index in defaultServicesInfo
matchingService = _.find(firefoxStorage.storage['kiwi_servicesInfo'], (service_info) ->
if service_info.name is service_default.name
return true
else
return false
)
if matchingService?
newServiceObj = _.extend {}, matchingService
for keyName, value of service_default
# console.log keyName
if typeof matchingService[keyName] is 'undefined'
newServicesInfoAttribute = true
newServiceObj[keyName] = value
indexOfServiceToReplace = _.indexOf(newServicesInfo, matchingService)
newServicesInfo[indexOfServiceToReplace] = newServiceObj
else
# supports adding an entirely new service
newServicesInfoAttribute = true
# users that don't download with a specific service will need to opt-in to the new one
if service_default.active?
service_default.active = 'off'
newServicesInfo.push service_default
if newUserPrefsAttribute or newServicesInfoAttribute
if newUserPrefsAttribute
setObj['kiwi_userPreferences'] = newUserPreferences
if newServicesInfoAttribute
setObj['kiwi_servicesInfo'] = newServicesInfo
# this reminds me of the frog DNA injection from jurassic park
if newUserPrefsAttribute
firefoxStorage.storage['kiwi_userPreferences'] = newUserPreferences
if newServicesInfoAttribute
firefoxStorage.storage['kiwi_servicesInfo'] = newServicesInfo
# console.log 'console.debug allItemsInSyncedStorage'
# console.debug allItemsInSyncedStorage
proceedWithPreInitCheck(overrideSameURLCheck_popupOpen, overrideResearchModeOff,
sameURLCheck, tabUrl, currentTime, popupOpen)
else
proceedWithPreInitCheck(overrideSameURLCheck_popupOpen, overrideResearchModeOff,
sameURLCheck, tabUrl, currentTime, popupOpen)
# a wise coder once told me "try to keep functions to 10 lines or less." yea, welcome to initIfNewURL! let me find my cowboy hat :D
initIfNewURL = (overrideSameURLCheck_popupOpen = false, overrideResearchModeOff = false) ->
# console.log 'yoyoyo'
# if firefoxStorage.storage['kiwi_userPreferences']?
# console.log 'nothing 0 '
# console.log firefoxStorage.storage['kiwi_userPreferences'].researchModeOnOff
# # console.debug firefoxStorage.storage['kiwi_userPreferences']
# else
# console.log 'nothing'
if typeof overrideSameURLCheck_popupOpen != 'boolean'
# ^^ because the Chrome api tab listening functions were exec-ing callback with an integer argument
# that has since been negated by nesting the callback, but why not leave the check here?
overrideSameURLCheck_popupOpen = false
# #console.log 'wtf 1 kiwi_urlsResultsCache ' + overrideSameURLCheck_popupOpen
if overrideSameURLCheck_popupOpen # for when a user turns researchModeOnOff "on" or refreshes results from popup
popupOpen = true
else
popupOpen = false
currentTime = Date.now()
# chrome.tabs.getSelected(null,(tab) ->
# chrome.tabs.query({ currentWindow: true, active: true }, (tabs) ->
if tabs.activeTab.url?
# console.log 'if tabs.activeTab.url?'
# console.log tabs.activeTab.url
# console.log tabs.activeTab
if tabs.activeTab.url.indexOf('chrome-devtools://') != 0
tabUrl = tabs.activeTab.url
# console.log 'tabUrl = tabs.activeTab.url'
# console.log tabUrl
# we care about the title, because it's the best way to search google news
if tabs.activeTab.readyState == 'complete'
title = tabs.activeTab.title
# a little custom title formatting for sites that begin their tab titles with "(<number>)" like twitter.com
if title.length > 3 and title[0] == "(" and isNaN(title[1]) == false and title.indexOf(')') != -1 and
title.indexOf(')') != title.length - 1
title = title.slice(title.indexOf(')') + 1 , title.length).trim()
tabTitleObject =
tabTitle: title
forUrl: tabUrl
else
tabTitleObject =
tabTitle: null
forUrl: tabUrl
else
_set_popupParcel({}, tabUrl, false)
#console.log 'chrome-devtools:// has been the only url visited so far'
return 0
tabUrl_hash = toSHA512(tabUrl)
sameURLCheck = true
# firefox's toSHA512 function usually returned a string ending in "=="
tabUrl_hash = tabUrl_hash.substring(0, tabUrl_hash.length - 2);
historyString = reduceHashByHalf(tabUrl_hash)
updateBadgeText('')
if !firefoxStorage.storage.persistentUrlHash?
firefoxStorage.storage.persistentUrlHash = ''
if overrideSameURLCheck_popupOpen == false and firefoxStorage.storage['kiwi_historyBlob']? and
firefoxStorage.storage['kiwi_historyBlob'].indexOf(historyString) != -1 and
(!kiwi_urlsResultsCache? or !kiwi_urlsResultsCache[tabUrl]?)
# console.log ' trying to set as old 123412341241234 '
updateBadgeText('old')
sameURLCheck = true
_set_popupParcel({}, tabUrl, false, null, true)
else if (overrideSameURLCheck_popupOpen == false and !firefoxStorage.storage.persistentUrlHash?) or
firefoxStorage.storage.persistentUrlHash? and firefoxStorage.storage.persistentUrlHash != tabUrl_hash
sameURLCheck = false
else if overrideSameURLCheck_popupOpen == true
sameURLCheck = false
#useful for switching window contexts
# chrome.storage.local.set({'persistentUrlHash': tabUrl_hash}, ->)
firefoxStorage.storage['persistentUrlHash'] = tabUrl_hash
if sameURLCheck == false
updateBadgeText('')
checkForNewDefaultUserPreferenceAttributes_thenProceedWithInitCheck(overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen)
tabs.on 'ready', (tab) ->
# console.log('tab is loaded', tab.title, tab.url)
initIfNewURL()
tabs.on('activate', ->
# console.log('active: ' + tabs.activeTab.url);
initIfNewURL()
)
# intial startup
if tabTitleObject == null
initIfNewURL(true)
| 163375 |
self = require('sdk/self')
tabs = require("sdk/tabs")
base64 = require("sdk/base64")
firefoxStorage = require("sdk/simple-storage")
Panel = require("sdk/panel").Panel # <-> same thing, but one is clearer # { Panel } = require("sdk/panel")
IconButton = require("sdk/ui/button/action").ActionButton
{ setTimeout, clearTimeout } = require("sdk/timers")
{ Cc, Ci } = require('chrome')
# kiwi_popup = require('./KiwiPopup')
Request = require("sdk/request").Request
_ = require('./data/vendor/underscore-min')
tabUrl = ''
tabTitleObject = null
popupOpen = false
checkForUrlHourInterval = 16
checkForUrl_Persistent_ChromeNotification_HourInterval = 3 # (max of 5 notification items)
last_periodicCleanup = 0 # timestamp
CLEANUP_INTERVAL = 3 * 3600000 # three hours
queryThrottleSeconds = 3 # to respect the no-more-than 30/min stiplation for Reddit's api
serviceQueryTimestamps = {}
maxUrlResultsStoredInLocalStorage = 800 # they're deleted after they've expired anyway - so this likely won't be reached by user
popupParcel = {}
# proactively set if each services' preppedResults are ready.
# will be set with available results if queried by popup.
# {
# forUrl:
# allPreppedResults:
# kiwi_servicesInfo:
# kiwi_customSearchResults:
# kiwi_alerts:
# kiwi_userPreferences:
# }
kiwi_userMessages = {
"redditDown":
"baseValue":"reddit's API is unavailable, so results may not appear from this service for some time"
"name":"redditDown"
"sentAndAcknowledgedInstanceObjects": []
# {
# "sentTimestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"productHuntDown":
"name":"productHuntDown"
"baseValue":"Product Hunt's API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
"productHuntDown__customSearch":
"name":"productHuntDown__customSearch"
"baseValue":"Product Hunt's custom search API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"hackerNewsDown":
"name":"hackerNewsDown"
"baseValue":"Hacker News' API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"generalConnectionFailure":
"name":"generalConnectionFailure"
"baseValue":"There has been a network connection issue. Check your internet connection / try again in a few minutes :)"
"sentAndAcknowledgedInstanceObjects": []
}
kiwi_urlsResultsCache = {}
# < url >:
# < serviceName >: {
# forUrl: url
# timestamp:
# service_PreppedResults:
# urlBlocked:
# }
kiwi_customSearchResults = {} # stores temporarily so if they close popup, they'll still have results
# maybe it won't clear until new result -- "see last search"
# queryString
# servicesSearchesRequested = responsePackage.servicesToSearch
# servicesSearched
# <serviceName>
# results
kiwi_autoOffClearInterval = null
kiwi_reddit_token_refresh_interval = null
# timestamp:
# intervalId:
kiwi_productHunt_token_refresh_interval = null
# timestamp:
# intervalId:
tempResponsesStore = {}
# forUrl: < url >
# results:
# < serviceName > :
# timestamp:
# service_PreppedResults:
# forUrl: url
getRandom = (min, max) ->
return min + Math.floor(Math.random() * (max - min + 1))
randomishDeviceId = -> # to be held in localStorage
randomClientLength = getRandom(21,29)
characterCounter = 0
randomString = ""
while characterCounter <= randomClientLength
characterCounter++
randomASCIIcharcode = getRandom(33,125)
#console.log randomASCIIcharcode
randomString += String.fromCharCode(randomASCIIcharcode)
return randomString
temp__kiwi_reddit_oauth =
token: null
token_type: null
token_lifespan_timestamp: null
client_id: "" # your client id here
device_id: randomishDeviceId()
temp__kiwi_productHunt_oauth =
token: null
token_type: null
token_lifespan_timestamp: null
client_id: "" # your client id here
client_secret: "" # your secret id here
defaultUserPreferences = {
fontSize: .8 # not yet implemented
researchModeOnOff: 'off' # or 'on'
autoOffAtUTCmilliTimestamp: null
autoOffTimerType: 'always' # 'custom','always','20','60'
autoOffTimerValue: null
sortByPref: 'attention' # 'recency' # "attention" means 'comments' if story, 'points' if comment, 'clusterUrl' if news
installedTime: Date.now()
urlSubstring_whitelists:
anyMatch: []
beginsWith: []
endingIn: []
unless: [
# ['twitter.com/','/status/'] # unless /status/
]
# suggested values to all users -- any can be overriden with the "Research this URL" button
# unfortunately, because of Chrome's discouragement of storing sensitive
# user info with chrome.storage, blacklists are fixed for now . see: https://news.ycombinator.com/item?id=9993030
urlSubstring_blacklists:
anyMatch: [
'facebook.com'
'news.ycombinator.com'
'reddit.com'
'imgur.com'
'www.google.com'
'docs.google'
'drive.google'
'accounts.google'
'.slack.com/'
'//t.co'
'//bit.ly'
'//goo.gl'
'//mail.google'
'//mail.yahoo.com'
'hotmail.com'
'outlook.com'
'chrome-extension://'
'chrome-devtools://' # hardcoded block
# "about:blank"
# "about:newtab"
]
beginsWith: [
"about:"
'chrome://'
]
endingIn: [
#future - ending in:
'youtube.com' # /
]
unless: [
#unless
['twitter.com/','/status/'] # unless /status/
# ,
# 'twitter.com'
]
}
defaultServicesInfo = [
name:"hackerNews"
title: "Hacker News"
abbreviation: "H"
queryApi:"https://hn.algolia.com/api/v1/search?restrictSearchableAttributes=url&query="
broughtToYouByTitle:"Algolia Hacker News API"
broughtToYouByURL:"https://hn.algolia.com/api"
brandingImage: null
brandingSlogan: null
permalinkBase: 'https://news.ycombinator.com/item?id='
userPageBaselink: 'https://news.ycombinator.com/user?id='
submitTitle: 'Be the first to submit on Hacker News!'
submitUrl: 'https://news.ycombinator.com/submit'
active: 'on'
notableConditions:
hoursSincePosted: 4 # an exact match is less than 5 hours old
num_comments: 10 # an exact match has 10 comments
updateBadgeOnlyWithExactMatch: true
customSearchApi: "https://hn.algolia.com/api/v1/search?query="
customSearchTags__convention: {'string':'&tags=','delimeter':','}
customSearchTags:
story:
title: "stories"
string: "story"
include: true
commentPolls:
title: "comments or polls"
string:"(comment,poll,pollopt)"
include: false
showHnAskHn:
title: "Show HN or Ask HN"
string:"(show_hn,ask_hn)"
include: false
# customSearch
# queryApi https://hn.algolia.com/api/v1/search?query=
# tags= filter on a specific tag. Available tags:
# story
# comment
# poll
# pollopt
# show_hn
# ask_hn
# front_page
# author_:USERNAME
# story_:ID
# author_pg,(story,poll) filters on author=pg AND (type=story OR type=poll).
customSearchBroughtToYouByURL: null
customSearchBroughtToYouByTitle: null
conversationSite: true
,
name:"reddit"
title: "reddit"
abbreviation: "R"
queryApi:"https://www.reddit.com/submit.json?url="
broughtToYouByTitle:"Reddit API"
broughtToYouByURL:"https://github.com/reddit/reddit/wiki/API"
brandingImage: null
brandingSlogan: null
permalinkBase: 'https://www.reddit.com'
userPageBaselink: 'https://www.reddit.com/user/'
submitTitle: 'Be the first to submit on Reddit!'
submitUrl: 'https://www.reddit.com/submit'
active: 'on'
notableConditions:
hoursSincePosted: 1 # an exact match is less than 5 hours old
num_comments: 30 # an exact match has 30 comments
updateBadgeOnlyWithExactMatch: true
customSearchApi: "https://www.reddit.com/search.json?q="
customSearchTags: {}
customSearchBroughtToYouByURL: null
customSearchBroughtToYouByTitle: null
conversationSite: true
,
name:"productHunt"
title: "Product Hunt"
abbreviation: "P"
queryApi:"https://api.producthunt.com/v1/posts/all?search[url]="
broughtToYouByTitle:"Product Hunt API"
broughtToYouByURL:"https://api.producthunt.com/v1/docs"
permalinkBase: 'https://producthunt.com/'
userPageBaselink: 'https://www.producthunt.com/@'
brandingImage: "product-hunt-logo-orange-240.png"
brandingSlogan: null
submitTitle: 'Be the first to submit to Product Hunt!'
submitUrl: 'https://www.producthunt.com/tech/new'
active: 'on'
notableConditions:
hoursSincePosted: 4 # an exact match is less than 5 hours old
num_comments: 10 # an exact match has 30 comments
# 'featured'
updateBadgeOnlyWithExactMatch: true
# uses Algolia index, not a typical rest api
customSearchApi: ""
customSearchTags: {}
customSearchBroughtToYouByURL: 'https://www.algolia.com/doc/javascript'
customSearchBroughtToYouByTitle: "Algolia's Search API"
conversationSite: true
# {
# so many great communities out there! ping me @spencenow if an API surfaces for yours!
# 2015-8-13 - producthunt has been implemented! holy crap this is cool! :D
# working on Slashdot...!
# },
]
send_kiwi_userMessage = (messageName, urgencyLevel, extraNote = null) ->
currentTime = Date.now()
sendMessageBool = true
# messageName
# if the same message has been sent in last five minutes, don't worry.
messageObj = kiwi_userMessages[messageName]
for sentInstance in messageObj.sentAndAcknowledgedInstanceObjects
if sentInstance.userAcknowledged? and (currentTime - sentInstance.userAcknowledged < 1000 * 60 * 20)
sendMessageBool = false
else if !sentInstance.userAcknowledged?
sendMessageBool = false
if sendMessageBool is true
kiwi_userMessages[messageName].sentAndAcknowledgedInstanceObjects.push {
"sentTimestamp": currentTime
"userAcknowledged": null # <timestamp>
}
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else if tempResponsesStore? and tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
shuffle_array = (array) ->
currentIndex = array.length;
# // While there remain elements to shuffle...
while (0 != currentIndex)
# // Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
# // And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
return array
randomizeDefaultConversationSiteOrder = ->
conversationSiteServices = []
nonConversationSiteServices = []
for service in defaultServicesInfo
if service.conversationSite
conversationSiteServices.push service
else
nonConversationSiteServices.push service
newDefaultServices = []
conversationSiteServices = shuffle_array(conversationSiteServices)
defaultServicesInfo = conversationSiteServices.concat(nonConversationSiteServices)
randomizeDefaultConversationSiteOrder()
# ~~~ starting out with negotiating oAuth tokens and initializing necessary api objects ~~~ #
reduceHashByHalf = (hash, reducedByAFactorOf = 1) ->
reduceStringByHalf = (_string_) ->
newShortenedString = ''
for char, index in _string_
if index % 2 is 0 and (_string_.length - 1 > index + 1)
char = if char > _string_[index + 1] then char else _string_[index + 1]
newShortenedString += char
return newShortenedString
finalHash = ''
counter = 0
while counter < reducedByAFactorOf
hash = reduceStringByHalf(hash)
counter++
return hash
kiwi_iconButton = IconButton {
id: "kiwi-button",
label: "Kiwi Conversations",
badge: '',
badgeColor: "#00AAAA",
icon: {
"16": "./kiwiFavico16.png",
"32": "./kiwiFavico32.png",
"64": "./kiwiFavico64.png"
},
onClick: (iconButtonState) ->
# console.log("button '" + iconButtonState.label + "' was clicked")
iconButtonClicked(iconButtonState)
}
iconButtonClicked = (iconButtonState) ->
# kiwi_iconButton.badge = iconButtonState.badge + 1
if (iconButtonState.checked)
kiwi_iconButton.badgeColor = "#AA00AA"
else
kiwi_iconButton.badgeColor = "#00AAAA"
kiwiPP_request_popupParcel()
kiwi_panel.show({'position':kiwi_iconButton})
# <link rel="stylesheet" href="vendor/bootstrap-3.3.5-dist/css/bootstrap.min.css"></link>
# <link rel="stylesheet" href="vendor/bootstrap-3.3.5-dist/css/bootstrap-theme.min.css"></link>
# <link rel="stylesheet" href="vendor/behigh-bootstrap_dropdown_enhancement/css/dropdowns-enhancement.min.css"></link>
# <script src="vendor/jquery-2.1.4.min.js" ></script>
# <script src="vendor/Underscore1-8-3.js"></script>
# <script src="vendor/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
# <script src=""></script>
kiwiPP_request_popupParcel = (dataFromPopup = {}) ->
# console.log 'kiwiPP_request_popupParcel = (dataFromPopup = {}) ->'
popupOpen = true
preppedResponsesInPopupParcel = 0
if popupParcel? and popupParcel.allPreppedResults?
#console.log 'popupParcel.allPreppedResults? '
#console.debug popupParcel.allPreppedResults
for serviceName, service of popupParcel.allPreppedResults
if service.service_PreppedResults?
preppedResponsesInPopupParcel += service.service_PreppedResults.length
preppedResponsesInTempResponsesStore = 0
if tempResponsesStore? and tempResponsesStore.services?
for serviceName, service of tempResponsesStore.services
preppedResponsesInTempResponsesStore += service.service_PreppedResults.length
newResultsBool = false
if tempResponsesStore.forUrl == tabUrl and preppedResponsesInTempResponsesStore != preppedResponsesInPopupParcel
newResultsBool = true
if popupParcel? and popupParcel.forUrl is tabUrl and newResultsBool == false
#console.log "popup parcel ready"
parcel = {}
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = popupParcel
sendParcel(parcel)
else
if !tempResponsesStore.services? or tempResponsesStore.forUrl != tabUrl
_set_popupParcel({}, tabUrl, true)
else
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
kiwi_panel = Panel({
width: 500,
height: 640,
# contentURL: "https://en.wikipedia.org/w/index.php?title=Jetpack&useformat=mobile",
contentURL: "./popup.html",
contentStyleFile: ["./bootstrap-3.3.5-dist/css/bootstrap.min.css",
"./bootstrap-3.3.5-dist/css/bootstrap-theme.min.css",
"./behigh-bootstrap_dropdown_enhancement/css/dropdowns-enhancement.min.css"
],
contentScriptFile: ["./vendor/jquery-2.1.4.min.js",
"./vendor/underscore-min.js",
"./behigh-bootstrap_dropdown_enhancement/js/dropdowns-enhancement.js",
"./vendor/algoliasearch.min.js",
"./KiwiPopup.js"]
})
updateBadgeText = (newBadgeText) ->
kiwi_iconButton.badge = newBadgeText
setTimeout_forRedditRefresh = (token_timestamp, kiwi_reddit_oauth, ignoreTimeoutDelayComparison = false) ->
currentTime = Date.now()
timeoutDelay = token_timestamp - currentTime
if kiwi_reddit_token_refresh_interval? and kiwi_reddit_token_refresh_interval.timestamp? and ignoreTimeoutDelayComparison is false
if timeoutDelay > kiwi_reddit_token_refresh_interval.timestamp - currentTime
# console.log 'patience, we will be trying again soon'
return 0
if kiwi_reddit_token_refresh_interval? and kiwi_reddit_token_refresh_interval.timestamp?
clearTimeout(kiwi_reddit_token_refresh_interval.intervalId)
timeoutIntervalId = setTimeout( ->
requestRedditOathToken(kiwi_reddit_oauth)
, timeoutDelay )
kiwi_reddit_token_refresh_interval =
timestamp: token_timestamp
intervalId: timeoutIntervalId
requestRedditOathToken = (kiwi_reddit_oauth) ->
currentTime = Date.now()
Request({
url: 'https://www.reddit.com/api/v1/access_token',
headers: {
'Authorization': 'Basic ' + base64.encode(kiwi_reddit_oauth.client_id + ":")
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
},
content: {
grant_type: "https://oauth.reddit.com/grants/installed_client"
device_id: kiwi_reddit_oauth.device_id
},
onComplete: (response) ->
if(response.status == 0 or response.status == 504 or response.status == 503 or
response.status == 502 or response.status == 401)
tryAgainTimestamp = currentTime + (1000 * 60 * 3)
setTimeout_forRedditRefresh(tryAgainTimestamp, kiwi_reddit_oauth)
send_kiwi_userMessage("redditDown")
# console.log('unavailable!2')
else
if response.json.access_token? and response.json.expires_in? and response.json.token_type == "bearer"
#console.log 'response from reddit!'
token_lifespan_timestamp = currentTime + response.json.expires_in * 1000
setObj =
token: response.json.access_token
token_type: 'bearer'
token_lifespan_timestamp: token_lifespan_timestamp
client_id: kiwi_reddit_oauth.client_id
device_id: kiwi_reddit_oauth.device_id
firefoxStorage.storage.kiwi_reddit_oauth = setObj
setTimeout_forRedditRefresh(token_lifespan_timestamp, setObj)
}).post()
setTimeout_forProductHuntRefresh = (token_timestamp, kiwi_productHunt_oauth, ignoreTimeoutDelayComparison = false) ->
currentTime = Date.now()
timeoutDelay = token_timestamp - currentTime
if kiwi_productHunt_token_refresh_interval? and kiwi_productHunt_token_refresh_interval.timestamp? and ignoreTimeoutDelayComparison is false
if timeoutDelay > kiwi_productHunt_token_refresh_interval.timestamp - currentTime
# console.log 'patience, we will be trying again soon'
return 0
if kiwi_productHunt_token_refresh_interval? and kiwi_productHunt_token_refresh_interval.timestamp?
clearTimeout(kiwi_productHunt_token_refresh_interval.intervalId)
timeoutIntervalId = setTimeout( ->
requestProductHuntOauthToken(kiwi_productHunt_oauth)
, timeoutDelay )
kiwi_productHunt_token_refresh_interval =
timestamp: token_timestamp
intervalId: timeoutIntervalId
requestProductHuntOauthToken = (kiwi_productHunt_oauth) ->
currentTime = Date.now()
Request({
content: {
"client_id": kiwi_productHunt_oauth.client_id
"client_secret": kiwi_productHunt_oauth.client_secret
"grant_type" : "client_credentials"
}
url: 'https://api.producthunt.com/v1/oauth/token'
headers: {}
onComplete: (response) ->
if(response.status == 0 or response.status == 504 or response.status == 503 or
response.status == 502 or response.status == 401)
# // do connection timeout handling
tryAgainTimestamp = currentTime + (1000 * 60 * 3)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, kiwi_productHunt_oauth)
send_kiwi_userMessage("productHuntDown")
# console.log('unavailable!3')
else
# console.log 'check this'
# console.log response.json
if response.json? and response.json.access_token? and response.json.expires_in? and response.json.token_type == "bearer"
token_lifespan_timestamp = currentTime + response.json.expires_in * 1000
setObj = {}
setObj =
token: response.json.access_token
scope: "public"
token_type: 'bearer'
token_lifespan_timestamp: token_lifespan_timestamp
client_id: kiwi_productHunt_oauth.client_id
client_secret: kiwi_productHunt_oauth.client_secret
firefoxStorage.storage.kiwi_productHunt_oauth = setObj
setTimeout_forProductHuntRefresh(token_lifespan_timestamp, setObj)
}).post()
negotiateOauthTokens = ->
currentTime = Date.now()
if !firefoxStorage.storage.kiwi_productHunt_oauth? or !firefoxStorage.storage.kiwi_productHunt_oauth.token?
# console.log 'ph oauth does not exist in firefox storage'
requestProductHuntOauthToken(temp__kiwi_productHunt_oauth)
if !firefoxStorage.storage.kiwi_productHunt_oauth? or !firefoxStorage.storage.kiwi_productHunt_oauth.token?
# do nothing
else if (firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp? and
currentTime > firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp) or
!firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp?
#console.log "3 setObj['kiwi_productHunt_oauth'] ="
requestProductHuntOauthToken(temp__kiwi_productHunt_oauth)
else if firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp? and firefoxStorage.storage.kiwi_productHunt_oauth?
#console.log "4 setObj['kiwi_productHunt_oauth'] ="
token_timestamp = firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp
if !kiwi_productHunt_token_refresh_interval? or kiwi_productHunt_token_refresh_interval.timestamp != token_timestamp
setTimeout_forProductHuntRefresh(token_timestamp, firefoxStorage.storage.kiwi_productHunt_oauth)
if !firefoxStorage.storage.kiwi_reddit_oauth? or !firefoxStorage.storage.kiwi_reddit_oauth.token?
requestRedditOathToken(temp__kiwi_reddit_oauth)
if !firefoxStorage.storage.kiwi_reddit_oauth? or !firefoxStorage.storage.kiwi_reddit_oauth.token?
# do nothing
else if (firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp? and
currentTime > firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp) or
!firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp?
#console.log "3 setObj['kiwi_reddit_oauth'] ="
requestRedditOathToken(temp__kiwi_reddit_oauth)
else if firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp? and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log "4 setObj['kiwi_reddit_oauth'] ="
token_timestamp = firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp
if !kiwi_reddit_token_refresh_interval? or kiwi_reddit_token_refresh_interval.timestamp != token_timestamp
setTimeout_forRedditRefresh(token_timestamp, firefoxStorage.storage.kiwi_reddit_oauth)
negotiateOauthTokens()
is_url_blocked = (blockedLists, url) ->
return doesURLmatchSubstringLists(blockedLists, url)
is_url_whitelisted = (whiteLists, url) ->
return doesURLmatchSubstringLists(whiteLists, url)
doesURLmatchSubstringLists = (urlSubstringLists, url) ->
if urlSubstringLists.anyMatch?
for urlSubstring in urlSubstringLists.anyMatch
if url.indexOf(urlSubstring) != -1
return true
if urlSubstringLists.beginsWith?
for urlSubstring in urlSubstringLists.beginsWith
if url.indexOf(urlSubstring) == 0
return true
if urlSubstringLists.endingIn?
for urlSubstring in urlSubstringLists.endingIn
if url.indexOf(urlSubstring) == url.length - urlSubstring.length
return true
urlSubstring += '/'
if url.indexOf(urlSubstring) == url.length - urlSubstring.length
return true
if urlSubstringLists.unless?
for urlSubstringArray in urlSubstringLists.unless
if url.indexOf(urlSubstringArray[0]) != -1
if url.indexOf(urlSubstringArray[1]) == -1
return true
return false
returnNumberOfActiveServices = (servicesInfo) ->
numberOfActiveServices = 0
for service in servicesInfo
if service.active == 'on'
numberOfActiveServices++
return numberOfActiveServices
sendParcel = (parcel) ->
if !parcel.msg? or !parcel.forUrl?
return false
switch parcel.msg
when 'kiwiPP_popupParcel_ready'
kiwi_panel.port.emit('kiwi_fromBackgroundToPopup', parcel)
_save_a_la_carte = (parcel) ->
firefoxStorage.storage[parcel.keyName] = parcel.newValue
if !tempResponsesStore? or !tempResponsesStore.services?
tempResponsesStoreServices = {}
else
tempResponsesStoreServices = tempResponsesStore.services
if parcel.refreshView?
_set_popupParcel(tempResponsesStoreServices, tabUrl, true, parcel.refreshView)
else
_set_popupParcel(tempResponsesStoreServices, tabUrl, false)
kiwi_panel.port.on("kiwiPP_acknowledgeMessage", (dataFromPopup) ->
popupOpen = true
currentTime = Date.now()
for sentInstance, index in kiwi_userMessages[dataFromPopup.messageToAcknowledge].sentAndAcknowledgedInstanceObjects
if !sentInstance.userAcknowledged?
kiwi_userMessages[dataFromPopup.messageToAcknowledge].sentAndAcknowledgedInstanceObjects[index] = currentTime
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else if tempResponsesStore? and tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
)
kiwi_panel.port.on("kiwiPP_post_customSearch", (dataFromPopup) ->
popupOpen = true
if dataFromPopup.customSearchRequest? and dataFromPopup.customSearchRequest.queryString? and
dataFromPopup.customSearchRequest.queryString != ''
if firefoxStorage.storage['kiwi_servicesInfo']?
# #console.log 'when kiwiPP_post_customSearch3'
for serviceInfoObject in firefoxStorage.storage['kiwi_servicesInfo']
#console.log 'when kiwiPP_post_customSearch4 for ' + serviceInfoObject.name
if dataFromPopup.customSearchRequest.servicesToSearch[serviceInfoObject.name]?
# console.log 'trying custom search PH'
# console.log dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults
if serviceInfoObject.name is 'productHunt' and dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults?
responsePackage = {
servicesInfo: firefoxStorage.storage['kiwi_servicesInfo']
servicesToSearch: dataFromPopup.customSearchRequest.servicesToSearch
customSearchQuery: dataFromPopup.customSearchRequest.queryString
serviceName: serviceInfoObject.name
queryResult: dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults
}
setPreppedServiceResults__customSearch(responsePackage, firefoxStorage.storage['kiwi_servicesInfo'])
else
if serviceInfoObject.customSearchApi? and serviceInfoObject.customSearchApi != ''
dispatchQuery__customSearch(dataFromPopup.customSearchRequest.queryString, dataFromPopup.customSearchRequest.servicesToSearch, serviceInfoObject, firefoxStorage.storage['kiwi_servicesInfo'])
)
kiwi_panel.port.on "kiwiPP_researchUrlOverrideButton", (dataFromPopup) ->
popupOpen = true
initIfNewURL(true,true)
kiwi_panel.port.on "kiwiPP_clearAllURLresults", (dataFromPopup) ->
popupOpen = true
updateBadgeText('')
kiwi_urlsResultsCache = {}
tempResponsesStore = {}
_set_popupParcel({}, tabUrl, true)
kiwi_panel.port.on "kiwiPP_refreshSearchQuery", (dataFromPopup) ->
popupOpen = true
kiwi_customSearchResults = {}
if tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
kiwi_panel.port.on "kiwiPP_refreshURLresults", (dataFromPopup) ->
popupOpen = true
if kiwi_urlsResultsCache? and kiwi_urlsResultsCache[tabUrl]?
delete kiwi_urlsResultsCache[tabUrl]
tempResponsesStore = {}
initIfNewURL(true)
kiwi_panel.port.on "kiwiPP_reset_timer", (dataFromPopup) ->
popupOpen = true
dataFromPopup.kiwi_userPreferences['autoOffAtUTCmilliTimestamp'] = setAutoOffTimer(true,
dataFromPopup.kiwi_userPreferences.autoOffAtUTCmilliTimestamp,
dataFromPopup.kiwi_userPreferences.autoOffTimerValue,
dataFromPopup.kiwi_userPreferences.autoOffTimerType,
dataFromPopup.kiwi_userPreferences.researchModeOnOff
)
parcel =
refreshView: 'userPreferences'
keyName: '<KEY>'
newValue: dataFromPopup.kiwi_userPreferences
localOrSync: 'sync'
_save_a_la_carte(parcel)
kiwi_panel.port.on "kiwiPP_post_save_a_la_carte", (dataFromPopup) ->
popupOpen = true
_save_a_la_carte(dataFromPopup)
kiwi_panel.port.on "kiwiPP_post_savePopupParcel", (dataFromPopup) ->
popupOpen = true
_save_from_popupParcel(dataFromPopup.newPopupParcel, tabUrl, dataFromPopup.refreshView)
if kiwi_urlsResultsCache[tabUrl]?
refreshBadge(dataFromPopup.newPopupParcel.kiwi_servicesInfo, kiwi_urlsResultsCache[tabUrl])
kiwi_panel.port.on "kiwiPP_request_popupParcel", (dataFromPopup) ->
kiwiPP_request_popupParcel(dataFromPopup)
initialize = (currentUrl) ->
if !firefoxStorage.storage.kiwi_servicesInfo?
firefoxStorage.storage.kiwi_servicesInfo = defaultServicesInfo
getUrlResults_to_refreshBadgeIcon(defaultServicesInfo, currentUrl)
else
getUrlResults_to_refreshBadgeIcon(firefoxStorage.storage['kiwi_servicesInfo'], currentUrl)
getUrlResults_to_refreshBadgeIcon = (servicesInfo, currentUrl) ->
currentTime = Date.now()
if Object.keys(kiwi_urlsResultsCache).length > 0
# to prevent repeated api requests - we check to see if we have up-to-date request results in local storage
if kiwi_urlsResultsCache[currentUrl]?
# start off by instantly updating UI with what we know
refreshBadge(servicesInfo, kiwi_urlsResultsCache[currentUrl])
for service in servicesInfo
if kiwi_urlsResultsCache[currentUrl][service.name]?
if (currentTime - kiwi_urlsResultsCache[currentUrl][service.name].timestamp) > checkForUrlHourInterval * 3600000
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
return 0
else
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
return 0
# for urls that are being visited a second time,
# all recent results present kiwi_urlsResultsCache (for all services)
# we set tempResponsesStore before setting popupParcel
tempResponsesStore.forUrl = currentUrl
tempResponsesStore.services = kiwi_urlsResultsCache[currentUrl]
#console.log '#console.debug tempResponsesStore.services'
#console.debug tempResponsesStore.services
_set_popupParcel(tempResponsesStore.services, currentUrl, true)
else
# this url has not been checked
#console.log '# this url has not been checked'
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
else
#console.log '# no urls have been checked'
check_updateServiceResults(servicesInfo, currentUrl, null)
_save_url_results = (servicesInfo, tempResponsesStore, _urlsResultsCache) ->
#console.log 'yolo 3'
urlsResultsCache = _.extend {}, _urlsResultsCache
previousUrl = tempResponsesStore.forUrl
if urlsResultsCache[previousUrl]?
# these will always be at least as recent as what's in the store.
for service in servicesInfo
if tempResponsesStore.services[service.name]?
urlsResultsCache[previousUrl][service.name] =
forUrl: previousUrl
timestamp: tempResponsesStore.services[service.name].timestamp
service_PreppedResults: tempResponsesStore.services[service.name].service_PreppedResults
else
urlsResultsCache[previousUrl] = {}
urlsResultsCache[previousUrl] = tempResponsesStore.services
return urlsResultsCache
__randomishStringPadding = ->
randomPaddingLength = getRandom(1,3)
characterCounter = 0
paddingString = ""
while characterCounter <= randomPaddingLength
randomLatinKeycode = getRandom(33,121)
String.fromCharCode(randomLatinKeycode)
paddingString += String.fromCharCode(randomLatinKeycode)
characterCounter++
return paddingString
toSHA512 = (str) ->
# // Convert string to an array of bytes
array = Array.prototype.slice.call(str)
# // Create SHA512 hash
hashEngine = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash)
hashEngine.init(hashEngine.MD5)
hashEngine.update(array, array.length)
return hashEngine.finish(true)
_save_historyBlob = (kiwi_urlsResultsCache, tabUrl) ->
tabUrl_hash = toSHA512(tabUrl)
# firefox's toSHA512 function usually returned a string ending in "=="
tabUrl_hash = tabUrl_hash.substring(0, tabUrl_hash.length - 2);
historyString = reduceHashByHalf(tabUrl_hash)
paddedHistoryString = __randomishStringPadding() + historyString + __randomishStringPadding()
if firefoxStorage.storage.kiwi_historyBlob? and typeof firefoxStorage.storage.kiwi_historyBlob == 'string' and
firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) < 15000 and firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) != -1
#console.log '# already exists in history blob ' + allItemsInLocalStorage.kiwi_historyBlob.indexOf(historyString)
return 0
else
if firefoxStorage.storage['kiwi_historyBlob']?
newKiwi_historyBlob = paddedHistoryString + firefoxStorage.storage['kiwi_historyBlob']
else
newKiwi_historyBlob = paddedHistoryString
# we cap the size of the history blob at 17000 characters
if firefoxStorage.storage.kiwi_historyBlob? and firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) > 17000
newKiwi_historyBlob = newKiwi_historyBlob.substring(0,15500)
firefoxStorage.storage.kiwi_historyBlob = newKiwi_historyBlob
check_updateServiceResults = (servicesInfo, currentUrl, urlsResultsCache = null) ->
#console.log 'yolo 4'
# if any results from previous tab have not been set, set them.
if urlsResultsCache? and Object.keys(tempResponsesStore).length > 0
previousResponsesStore = _.extend {}, tempResponsesStore
_urlsResultsCache = _.extend {}, urlsResultsCache
kiwi_urlsResultsCache = _save_url_results(servicesInfo, previousResponsesStore, _urlsResultsCache)
_save_historyBlob(kiwi_urlsResultsCache, previousResponsesStore.forUrl)
# refresh tempResponsesStore for new url
tempResponsesStore.forUrl = currentUrl
tempResponsesStore.services = {}
currentTime = Date.now()
if !urlsResultsCache?
urlsResultsCache = {}
if !urlsResultsCache[currentUrl]?
urlsResultsCache[currentUrl] = {}
# #console.log 'about to check for dispatch query'
# #console.debug urlsResultsCache[currentUrl]
# check on a service-by-service basis (so we don't requery all services just b/c one api/service is down)
for service in servicesInfo
# #console.log 'for service in servicesInfo'
# #console.debug service
if service.active == 'on'
if urlsResultsCache[currentUrl][service.name]?
if (currentTime - urlsResultsCache[currentUrl][service.name].timestamp) > checkForUrlHourInterval * 3600000
dispatchQuery(service, currentUrl, servicesInfo)
else
dispatchQuery(service, currentUrl, servicesInfo)
dispatchQuery = (service_info, currentUrl, servicesInfo) ->
# console.log 'yolo 5 ~ for ' + service_info.name
currentTime = Date.now()
# self imposed rate limiting per api
if !serviceQueryTimestamps[service_info.name]?
serviceQueryTimestamps[service_info.name] = currentTime
else
if (currentTime - serviceQueryTimestamps[service_info.name]) < queryThrottleSeconds * 1000
#wait a couple seconds before querying service
#console.log 'too soon on dispatch, waiting a couple seconds'
setTimeout(->
dispatchQuery(service_info, currentUrl, servicesInfo)
, 2000
)
return 0
else
serviceQueryTimestamps[service_info.name] = currentTime
queryObj = {
url: service_info.queryApi + encodeURIComponent(currentUrl),
onComplete: (queryResult) ->
if queryResult.status == 401
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated4');
setPreppedServiceResults(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
if service_info.name is 'productHunt'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
else if service_info.name is 'reddit'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
else if (queryResult.status == 0 or queryResult.status == 504 or queryResult.status == 503 or
queryResult.status == 502)
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated4');
setPreppedServiceResults(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
else
# console.log 'back with'
# for key, val of queryResult
# console.log key + ' : ' + val
responsePackage =
forUrl: currentUrl
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: queryResult.json
setPreppedServiceResults(responsePackage, servicesInfo)
}
headers = {}
if service_info.name is 'reddit' and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log 'we are trying with oauth!'
#console.debug allItemsInLocalStorage.kiwi_reddit_oauth
queryObj.headers =
'Authorization': "'bearer " + firefoxStorage.storage.kiwi_reddit_oauth.token + "'"
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
else if service_info.name is 'reddit' and !firefoxStorage.storage.kiwi_reddit_oauth?
# console.log 'adfaeaefae'
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated5');
setPreppedServiceResults(responsePackage, servicesInfo)
# if kiwi_userMessages[service_info.name + "Down"]?
# send_kiwi_userMessage(service_info.name + "Down")
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
return 0
# console.log firefoxStorage.storage.kiwi_productHunt_oauth.token
if service_info.name is 'productHunt' and firefoxStorage.storage.kiwi_productHunt_oauth?
# console.log 'trying PH with'
# console.debug allItemsInLocalStorage.kiwi_productHunt_oauth
queryObj.headers =
'Authorization': "Bearer " + firefoxStorage.storage.kiwi_productHunt_oauth.token
'Accept': 'application/json'
'Content-Type': 'application/json'
else if service_info.name is 'productHunt' and !firefoxStorage.storage.kiwi_productHunt_oauth?
# console.log 'asdfasdfasdfdas'
# call out and to a reset / refresh timer thingy
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated5');
setPreppedServiceResults(responsePackage, servicesInfo)
# if kiwi_userMessages[service_info.name + "Down"]?
# send_kiwi_userMessage(service_info.name + "Down")
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
return 0
Request(queryObj).get()
dispatchQuery__customSearch = (customSearchQuery, servicesToSearch, service_info, servicesInfo) ->
#console.log 'yolo 5 ~ for CUSTOM ' + service_info.name
#console.debug servicesToSearch
currentTime = Date.now()
# self imposed rate limiting per api
if !serviceQueryTimestamps[service_info.name]?
serviceQueryTimestamps[service_info.name] = currentTime
else
if (currentTime - serviceQueryTimestamps[service_info.name]) < queryThrottleSeconds * 1000
#wait a couple seconds before querying service
#console.log 'too soon on dispatch, waiting a couple seconds'
setTimeout(->
dispatchQuery__customSearch(customSearchQuery, servicesToSearch, service_info, servicesInfo)
, 2000
)
return 0
else
serviceQueryTimestamps[service_info.name] = currentTime
queryUrl = service_info.customSearchApi + encodeURIComponent(customSearchQuery)
if servicesToSearch[service_info.name].customSearchTags? and Object.keys(servicesToSearch[service_info.name].customSearchTags).length > 0
for tagIdentifier, tagObject of servicesToSearch[service_info.name].customSearchTags
queryUrl = queryUrl + service_info.customSearchTags__convention.string + service_info.customSearchTags[tagIdentifier].string
#console.log 'asd;lfkjaewo;ifjae; '
# console.log 'for tagIdentifier, tagObject of servicesToSearch[service_info.name].customSearchTags'
# console.log queryUrl
# tagObject might one day accept special parameters like author name, etc
queryObj = {
url: queryUrl,
onComplete: (queryResult) ->
if queryResult.status == 401
responsePackage = {
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: null
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
};
# console.log('unauthenticated1');
setPreppedServiceResults__customSearch(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
if service_info.name is 'productHunt'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
else if service_info.name is 'reddit'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
else if (queryResult.status == 0 or queryResult.status == 504 or queryResult.status == 503 or
queryResult.status == 502)
responsePackage = {
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: null
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
};
# console.log('Fail!1');
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
setPreppedServiceResults__customSearch(responsePackage, servicesInfo);
else
# console.log 'onComplete: (queryResult) ->'
# console.log queryResult.json
responsePackage = {
# forUrl: currentUrl
servicesInfo: servicesInfo
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
serviceName: service_info.name
queryResult: queryResult.json
}
setPreppedServiceResults__customSearch(responsePackage, servicesInfo)
}
headers = {}
if service_info.name is 'reddit' and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log 'we are trying with oauth!'
#console.debug allItemsInLocalStorage.kiwi_reddit_oauth
queryObj.headers =
'Authorization': "'bearer " + firefoxStorage.storage.kiwi_reddit_oauth.token + "'"
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
# console.log 'console.log queryObj monkeybutt'
# console.log queryObj
Request(queryObj).get()
# proactively set if all service_PreppedResults are ready.
# will be set with available results if queried by popup.
# the popup should always have enough to render with a properly set popupParcel.
setPreppedServiceResults__customSearch = (responsePackage, servicesInfo) ->
# console.log 'yolo 6'
currentTime = Date.now()
for serviceObj in servicesInfo
if serviceObj.name == responsePackage.serviceName
serviceInfo = serviceObj
# responsePackage =
# servicesInfo: servicesInfo
# serviceName: service_info.name
# queryResult: queryResult
# servicesToSearch: servicesToSearch
# customSearchQuery: customSearchQuery
# kiwi_customSearchResults = {} # stores temporarily so if they close popup, they'll still have results
# maybe it won't clear until new result -- "see last search"
# queryString
# servicesSearchesRequested = responsePackage.servicesToSearch
# servicesSearched
# <serviceName>
# results
# even if there are zero matches returned, that counts as a proper query response
service_PreppedResults = parseResults[responsePackage.serviceName](responsePackage.queryResult, responsePackage.customSearchQuery, serviceInfo, true)
if kiwi_customSearchResults? and kiwi_customSearchResults.queryString? and
kiwi_customSearchResults.queryString == responsePackage.customSearchQuery
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName] = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName].results = service_PreppedResults
else
kiwi_customSearchResults = {}
kiwi_customSearchResults.queryString = responsePackage.customSearchQuery
kiwi_customSearchResults.servicesSearchesRequested = responsePackage.servicesToSearch
kiwi_customSearchResults.servicesSearched = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName] = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName].results = service_PreppedResults
# console.log 'yolo 6 results service_PreppedResults'
# console.debug service_PreppedResults
#console.log 'numberOfActiveServices'
#console.debug returnNumberOfActiveServices(servicesInfo)
numberOfActiveServices = Object.keys(responsePackage.servicesToSearch).length
completedQueryServicesArray = []
#number of completed responses
if kiwi_customSearchResults.queryString == responsePackage.customSearchQuery
for serviceName, service of kiwi_customSearchResults.servicesSearched
completedQueryServicesArray.push(serviceName)
completedQueryServicesArray = _.uniq(completedQueryServicesArray)
#console.log 'completedQueryServicesArray.length '
#console.log completedQueryServicesArray.length
if completedQueryServicesArray.length is numberOfActiveServices and numberOfActiveServices != 0
# NO LONGER STORING URL CACHE IN LOCALSTORAGE - BECAUSE : INFORMATION LEAKAGE / BROKEN EXTENSION SECURITY MODEL
# get a fresh copy of urls results and reset with updated info
# chrome.storage.local.get(null, (allItemsInLocalStorage) ->
# #console.log 'trying to save all'
# if !allItemsInLocalStorage['kiwi_urlsResultsCache']?
# allItemsInLocalStorage['kiwi_urlsResultsCache'] = {}
# console.log 'yolo 6 _save_ results(servicesInfo, tempRes -- for ' + serviceInfo.name
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
# else
# #console.log 'yolo 6 not finished ' + serviceInfo.name
# _set_popupParcel(tempResponsesStore.services, responsePackage.forUrl, false)
_set_popupParcel = (setWith_urlResults = {}, forUrl, sendPopupParcel, renderView = null, oldUrl = false) ->
# console.log 'monkey butt _set_popupParcel = (setWith_urlResults, forUrl, sendPopupParcel, '
#console.log 'trying to set popupParcel, forUrl tabUrl' + forUrl + tabUrl
# tabUrl
if setWith_urlResults != {}
if forUrl != tabUrl
#console.log "_set_popupParcel request for old url"
return false
setObj_popupParcel = {}
setObj_popupParcel.forUrl = tabUrl
if !firefoxStorage.storage['kiwi_userPreferences']?
setObj_popupParcel.kiwi_userPreferences = defaultUserPreferences
else
setObj_popupParcel.kiwi_userPreferences = firefoxStorage.storage['kiwi_userPreferences']
if !firefoxStorage.storage['kiwi_servicesInfo']?
setObj_popupParcel.kiwi_servicesInfo = defaultServicesInfo
else
setObj_popupParcel.kiwi_servicesInfo = firefoxStorage.storage['kiwi_servicesInfo']
if renderView != null
setObj_popupParcel.view = renderView
if !firefoxStorage.storage['kiwi_alerts']?
setObj_popupParcel.kiwi_alerts = []
else
setObj_popupParcel.kiwi_alerts = firefoxStorage.storage['kiwi_alerts']
setObj_popupParcel.kiwi_customSearchResults = kiwi_customSearchResults
if !setWith_urlResults?
#console.log '_set_popupParcel called with undefined responses (not supposed to happen, ever)'
return 0
else
setObj_popupParcel.allPreppedResults = setWith_urlResults
if tabUrl == forUrl
setObj_popupParcel.tabInfo = {}
setObj_popupParcel.tabInfo.tabUrl = tabUrl
setObj_popupParcel.tabInfo.tabTitle = tabTitleObject.tabTitle
else
setObj_popupParcel.tabInfo = null
setObj_popupParcel.urlBlocked = false
isUrlBlocked = is_url_blocked(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true
setObj_popupParcel.urlBlocked = true
if oldUrl is true
setObj_popupParcel.oldUrl = true
else
setObj_popupParcel.oldUrl = false
setObj_popupParcel.kiwi_userMessages = []
for messageName, messageObj of kiwi_userMessages
for sentInstance in messageObj.sentAndAcknowledgedInstanceObjects
if sentInstance.userAcknowledged is null
setObj_popupParcel.kiwi_userMessages.push messageObj
popupParcel = setObj_popupParcel
if sendPopupParcel
parcel = {}
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = setObj_popupParcel
sendParcel(parcel)
setPreppedServiceResults = (responsePackage, servicesInfo) ->
currentTime = Date.now()
# if tabUrl == responsePackage.forUrl # if false, then do nothing (user's probably switched to new tab)
for serviceObj in servicesInfo
if serviceObj.name == responsePackage.serviceName
serviceInfo = serviceObj
# serviceInfo = servicesInfo[responsePackage.serviceName]
# even if there are zero matches returned, that counts as a proper query response
service_PreppedResults = parseResults[responsePackage.serviceName](responsePackage.queryResult, tabUrl, serviceInfo)
if !tempResponsesStore.services?
tempResponsesStore = {}
tempResponsesStore.services = {}
tempResponsesStore.services[responsePackage.serviceName] =
timestamp: currentTime
service_PreppedResults: service_PreppedResults
forUrl: tabUrl
#console.log 'yolo 6 results service_PreppedResults'
#console.debug service_PreppedResults
#console.log 'numberOfActiveServices'
#console.debug returnNumberOfActiveServices(servicesInfo)
numberOfActiveServices = returnNumberOfActiveServices(servicesInfo)
completedQueryServicesArray = []
#number of completed responses
if tempResponsesStore.forUrl == tabUrl
for serviceName, service of tempResponsesStore.services
completedQueryServicesArray.push(serviceName)
if kiwi_urlsResultsCache[tabUrl]?
for serviceName, service of kiwi_urlsResultsCache[tabUrl]
completedQueryServicesArray.push(serviceName)
completedQueryServicesArray = _.uniq(completedQueryServicesArray)
if completedQueryServicesArray.length is numberOfActiveServices and numberOfActiveServices != 0
# NO LONGER STORING URL CACHE IN LOCALSTORAGE - BECAUSE 1.) INFORMATION LEAKAGE, 2.) SLOWER
# get a fresh copy of urls results and reset with updated info
# chrome.storage.local.get(null, (allItemsInLocalStorage) ->
# #console.log 'trying to save all'
# if !allItemsInLocalStorage['kiwi_urlsResultsCache']?
# allItemsInLocalStorage['kiwi_urlsResultsCache'] = {}
#console.log 'yolo 6 _save_url_results(servicesInfo, tempRes -- for ' + serviceInfo.name
kiwi_urlsResultsCache = _save_url_results(servicesInfo, tempResponsesStore, kiwi_urlsResultsCache)
_save_historyBlob(kiwi_urlsResultsCache, tabUrl)
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
refreshBadge(servicesInfo, kiwi_urlsResultsCache[tabUrl])
else
#console.log 'yolo 6 not finished ' + serviceInfo.name
_set_popupParcel(tempResponsesStore.services, tabUrl, false)
refreshBadge(servicesInfo, tempResponsesStore.services)
#returns an array of 'preppedResults' for url - just the keys we care about from the query-response
parseResults =
productHunt: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
# console.log 'resultsObj'
# console.log 'for: ' + searchQueryString
# console.debug resultsObj
# console.log 'customSearchBool ' + customSearchBool
# console.log resultsObj.posts
matchedListings = [];
if ( resultsObj == null )
return matchedListings;
if customSearchBool is false # so, normal URL-based queries
# created_at: "2014-08-18T06:40:47.000-07:00"
# discussion_url: "http://www.producthunt.com/tech/product-hunt-api-beta"
# comments_count: 13
# votes_count: 514
# name: "Product Hunt API (beta)"
# featured: true
# id: 6970
# maker_inside: true
# tagline: "Make stuff with us. Signup for early access to the PH API :)"
# user:
# headline: "Tech at Product Hunt 💃"
# profile_url: "http://www.producthunt.com/@andreasklinger"
# name: "<NAME>"
# username: "andreasklinger"
# website_url: "http://klinger.io"
if resultsObj.posts? and _.isArray(resultsObj.posts) is true
for post in resultsObj.posts
listingKeys = [
'created_at','discussion_url','comments_count','redirect_url','votes_count','name',
'featured','id','user','screenshot_url','tagline','maker_inside','makers'
]
preppedResult = _.pick(post, listingKeys)
preppedResult.kiwi_created_at = Date.parse(preppedResult.created_at)
preppedResult.kiwi_discussion_url = preppedResult.discussion_url
if preppedResult.user? and preppedResult.user.name?
preppedResult.kiwi_author_name = preppedResult.user.name.trim()
else
preppedResult.kiwi_author_name = ""
if preppedResult.user? and preppedResult.user.username?
preppedResult.kiwi_author_username = preppedResult.user.username
else
preppedResult.kiwi_author_username = ""
if preppedResult.user? and preppedResult.user.headline?
preppedResult.kiwi_author_headline = preppedResult.user.headline.trim()
else
preppedResult.kiwi_author_headline = ""
preppedResult.kiwi_makers = []
for maker, index in post.makers
makerObj = {}
makerObj.headline = maker.headline
makerObj.name = maker.name
makerObj.username = maker.username
makerObj.profile_url = maker.profile_url
makerObj.website_url = maker.website_url
preppedResult.kiwi_makers.push makerObj
preppedResult.kiwi_exact_match = true # PH won't return fuzzy matches
preppedResult.kiwi_score = preppedResult.votes_count
preppedResult.kiwi_num_comments = preppedResult.comments_count
preppedResult.kiwi_permaId = preppedResult.permalink
matchedListings.push preppedResult
else # custom string queries
# comment_count
# vote_count
# name
# url #
# tagline
# category
# tech
# product_makers
# headline
# name
# username
# is_maker
# console.log ' else # custom string queries ' + _.isArray(resultsObj) #
if resultsObj? and _.isArray(resultsObj)
# console.log ' yoyoyoy1 '
for searchMatch in resultsObj
listingKeys = [
'author'
'url',
'tagline',
'product_makers'
'comment_count',
'vote_count',
'name',
'id',
'user',
'screenshot_url',
]
preppedResult = _.pick(searchMatch, listingKeys)
preppedResult.kiwi_created_at = null # algolia doesn't provide created at value :<
preppedResult.kiwi_discussion_url = "http://www.producthunt.com/" + preppedResult.url
if preppedResult.author? and preppedResult.author.name?
preppedResult.kiwi_author_name = preppedResult.author.name.trim()
else
preppedResult.kiwi_author_name = ""
if preppedResult.author? and preppedResult.author.username?
preppedResult.kiwi_author_username = preppedResult.author.username
else
preppedResult.kiwi_author_username = ""
if preppedResult.author? and preppedResult.author.headline?
preppedResult.kiwi_author_headline = preppedResult.author.headline.trim()
else
preppedResult.kiwi_author_headline = ""
preppedResult.kiwi_makers = []
for maker, index in searchMatch.product_makers
makerObj = {}
makerObj.headline = maker.headline
makerObj.name = maker.name
makerObj.username = maker.username
makerObj.profile_url = maker.profile_url
makerObj.website_url = maker.website_url
preppedResult.kiwi_makers.push makerObj
preppedResult.kiwi_exact_match = true # PH won't return fuzzy matches
preppedResult.kiwi_score = preppedResult.vote_count
preppedResult.kiwi_num_comments = preppedResult.comment_count
preppedResult.kiwi_permaId = preppedResult.permalink
matchedListings.push preppedResult
return matchedListings
reddit: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
matchedListings = []
if ( resultsObj == null )
return matchedListings
# console.log 'reddit: (resultsObj) ->'
# console.debug resultsObj
# occasionally Reddit will decide to return an array instead of an object, so...
# in response to user's feedback, see: https://news.ycombinator.com/item?id=9994202
forEachQueryObject = (resultsObj, _matchedListings) ->
if resultsObj.kind? and resultsObj.kind == "Listing" and resultsObj.data? and
resultsObj.data.children? and resultsObj.data.children.length > 0
for child in resultsObj.data.children
if child.data? and child.kind? and child.kind == "t3"
listingKeys = ["subreddit",'url',"score",'domain','gilded',"over_18","author","hidden","downs","permalink","created","title","created_utc","ups","num_comments"]
preppedResult = _.pick(child.data, listingKeys)
preppedResult.kiwi_created_at = preppedResult.created_utc * 1000 # to normalize to JS's Date.now() millisecond UTC timestamp
if customSearchBool is false
preppedResult.kiwi_exact_match = _exact_match_url_check(searchQueryString, preppedResult.url)
else
preppedResult.kiwi_exact_match = true
preppedResult.kiwi_score = preppedResult.score
preppedResult.kiwi_permaId = preppedResult.permalink
_matchedListings.push preppedResult
return _matchedListings
if _.isArray(resultsObj)
for result in resultsObj
matchedListings = forEachQueryObject(result, matchedListings)
else
matchedListings = forEachQueryObject(resultsObj, matchedListings)
return matchedListings
hackerNews: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
matchedListings = []
if ( resultsObj == null )
return matchedListings
#console.log ' hacker news #console.debug resultsObj'
#console.debug resultsObj
# if resultsObj.nbHits? and resultsObj.nbHits > 0 and resultsObj.hits? and resultsObj.hits.length is resultsObj.nbHits
if resultsObj? and resultsObj.hits?
for hit in resultsObj.hits
listingKeys = ["points","num_comments","objectID","author","created_at","title","url","created_at_i"
"story_text","comment_text","story_id","story_title","story_url"
]
preppedResult = _.pick(hit, listingKeys)
preppedResult.kiwi_created_at = preppedResult.created_at_i * 1000 # to normalize to JS's Date.now() millisecond UTC timestamp
if customSearchBool is false
preppedResult.kiwi_exact_match = _exact_match_url_check(searchQueryString, preppedResult.url)
else
preppedResult.kiwi_exact_match = true
preppedResult.kiwi_score = preppedResult.points
preppedResult.kiwi_permaId = preppedResult.objectID
matchedListings.push preppedResult
return matchedListings
_exact_match_url_check = (forUrl, preppedResultUrl) ->
# warning:: one of the worst algo-s i've ever written... please don't use as reference
kiwi_exact_match = false
modifications = [
name: 'trailingSlash'
modify: (tOrF, forUrl) ->
if tOrF is 't'
if forUrl[forUrl.length - 1] != '/'
trailingSlashURL = forUrl + '/'
else
trailingSlashURL = forUrl
return trailingSlashURL
else
if forUrl[forUrl.length - 1] == '/'
noTrailingSlashURL = forUrl.substr(0,forUrl.length - 1)
else
noTrailingSlashURL = forUrl
return noTrailingSlashURL
# if forUrl[forUrl.length - 1] == '/'
# noTrailingSlashURL = forUrl.substr(0,forUrl.length - 1)
existsTest: (forUrl) ->
if forUrl[forUrl.length - 1] == '/'
return 't'
else
return 'f'
,
name: 'www'
modify: (tOrF, forUrl) ->
if tOrF is 't'
protocolSplitUrlArray = forUrl.split('://')
if protocolSplitUrlArray.length > 1
if protocolSplitUrlArray[1].indexOf('www.') != 0
protocolSplitUrlArray[1] = 'www.' + protocolSplitUrlArray[1]
WWWurl = protocolSplitUrlArray.join('://')
else
WWWurl = forUrl
return WWWurl
else
if protocolSplitUrlArray[0].indexOf('www.') != 0
protocolSplitUrlArray[0] = 'www.' + protocolSplitUrlArray[1]
WWWurl = protocolSplitUrlArray.join('://')
else
WWWurl = forUrl
return WWWurl
else
wwwSplitUrlArray = forUrl.split('www.')
if wwwSplitUrlArray.length is 2
noWWWurl = wwwSplitUrlArray.join('')
else if wwwSplitUrlArray.length > 2
noWWWurl = wwwSplitUrlArray.shift()
noWWWurl += wwwSplitUrlArray.shift()
noWWWurl += wwwSplitUrlArray.join('www.')
else
noWWWurl = forUrl
return noWWWurl
existsTest: (forUrl) ->
if forUrl.split('//www.').length > 0
return 't'
else
return 'f'
,
name:'http'
existsTest: (forUrl) ->
if forUrl.indexOf('http://') is 0
return 't'
else
return 'f'
modify: (tOrF, forUrl) ->
if tOrF is 't'
if forUrl.indexOf('https://') == 0
HTTPurl = 'http://' + forUrl.substr(8, forUrl.length - 1)
else
HTTPurl = forUrl
else
if forUrl.indexOf('http://') == 0
HTTPSurl = 'https://' + forUrl.substr(7, forUrl.length - 1)
else
HTTPSurl = forUrl
]
modPermutations = {}
forUrlUnmodded = ''
for mod in modifications
forUrlUnmodded += mod.existsTest(forUrl)
modPermutations[forUrlUnmodded] = forUrl
existStates = ['t','f']
for existState in existStates
for mod, index in modifications
checkArray = []
for m in modifications
checkArray.push existState
forUrl_ = modifications[index].modify(existState, forUrl)
for existState_ in existStates
checkArray[index] = existState_
for mod_, index_ in modifications
if index != index_
for existState__ in existStates
checkArray[index_] = existState__
checkString = checkArray.join('')
if !modPermutations[checkString]?
altUrl = forUrl_
for existState_Char, cSindex in checkString
altUrl = modifications[cSindex].modify(existState_Char, altUrl)
modPermutations[checkString] = altUrl
kiwi_exact_match = false
if preppedResultUrl == forUrl
kiwi_exact_match = true
for modKey, moddedUrl of modPermutations
if preppedResultUrl == moddedUrl
kiwi_exact_match = true
return kiwi_exact_match
refreshBadge = (servicesInfo, resultsObjForCurrentUrl) ->
# #console.log 'yolo 8'
# #console.debug resultsObjForCurrentUrl
# #console.debug servicesInfo
# icon badges typically only have room for 5 characters
currentTime = Date.now()
abbreviationLettersArray = []
for service, index in servicesInfo
# if resultsObjForCurrentUrl[service.name]
if resultsObjForCurrentUrl[service.name]? and resultsObjForCurrentUrl[service.name].service_PreppedResults.length > 0
exactMatch = false
noteworthy = false
for listing in resultsObjForCurrentUrl[service.name].service_PreppedResults
if listing.kiwi_exact_match
exactMatch = true
if listing.num_comments? and listing.num_comments >= service.notableConditions.num_comments
noteworthy = true
break
if (currentTime - listing.kiwi_created_at) < service.notableConditions.hoursSincePosted * 3600000
noteworthy = true
break
if service.updateBadgeOnlyWithExactMatch and exactMatch = false
break
#console.log service.name + ' noteworthy ' + noteworthy
if noteworthy
abbreviationLettersArray.push service.abbreviation
else
abbreviationLettersArray.push service.abbreviation.toLowerCase()
#console.debug abbreviationLettersArray
badgeText = ''
if abbreviationLettersArray.length == 0
if firefoxStorage.storage.kiwi_userPreferences? and firefoxStorage.storage['kiwi_userPreferences'].researchModeOnOff == 'off'
badgeText = ''
else if defaultUserPreferences.researchModeOnOff == 'off'
badgeText = ''
else
badgeText = ''
else
badgeText = abbreviationLettersArray.join(" ")
#console.log 'yolo 8 ' + badgeText
updateBadgeText(badgeText)
periodicCleanup = (tab, initialize_callback) ->
#console.log 'wtf a'
currentTime = Date.now()
if(last_periodicCleanup < (currentTime - CLEANUP_INTERVAL))
last_periodicCleanup = currentTime
#console.log 'wtf b'
# delete any results older than checkForUrlHourInterval
if Object.keys(kiwi_urlsResultsCache).length is 0
#console.log 'wtf ba'
# nothing to (potentially) clean up!
initialize_callback(tab)
else
#console.log 'wtf bb'
# allItemsInLocalStorage.kiwi_urlsResultsCache
cull_kiwi_urlsResultsCache = _.extend {}, kiwi_urlsResultsCache
for url, urlServiceResults of cull_kiwi_urlsResultsCache
for serviceKey, serviceResults of urlServiceResults
if currentTime - serviceResults.timestamp > checkForUrlHourInterval
delete kiwi_urlsResultsCache[url]
if Object.keys(kiwi_urlsResultsCache).length > maxUrlResultsStoredInLocalStorage
# you've been surfing! wow
num_results_to_delete = Object.keys(kiwi_urlsResultsCache).length - maxUrlResultsStoredInLocalStorage
deletedCount = 0
cull_kiwi_urlsResultsCache = _.extend {}, kiwi_urlsResultsCache
for url, urlServiceResults of cull_kiwi_urlsResultsCache
if deleteCount >= num_results_to_delete
break
if url != tab.url
delete kiwi_urlsResultsCache[url]
deletedCount++
# chrome.storage.local.set({'kiwi_urlsResultsCache':kiwi_urlsResultsCache}, ->
initialize_callback(tab)
# )
else
initialize_callback(tab)
else
#console.log 'wtf c'
initialize_callback(tab)
_save_from_popupParcel = (_popupParcel, forUrl, updateToView) ->
formerResearchModeValue = null
formerKiwi_servicesInfo = null
former_autoOffTimerType = null
former_autoOffTimerValue = null
# #console.log '#console.debug popupParcel
# #console.debug _popupParcel'
# #console.debug popupParcel
# #console.debug _popupParcel
if popupParcel? and popupParcel.kiwi_userPreferences? and popupParcel.kiwi_servicesInfo
formerResearchModeValue = popupParcel.kiwi_userPreferences.researchModeOnOff
formerKiwi_servicesInfo = popupParcel.kiwi_servicesInfo
former_autoOffTimerType = popupParcel.kiwi_userPreferences.autoOffTimerType
former_autoOffTimerValue = popupParcel.kiwi_userPreferences.autoOffTimerValue
popupParcel = {}
# #console.log ' asdfasdfasd formerKiwi_autoOffTimerType'
# #console.log former_autoOffTimerType
# #console.log _popupParcel.kiwi_userPreferences.autoOffTimerType
# #console.log ' a;woeifjaw;ef formerKiwi_autoOffTimerValue'
# #console.log former_autoOffTimerValue
# #console.log _popupParcel.kiwi_userPreferences.autoOffTimerValue
if formerResearchModeValue? and formerResearchModeValue == 'off' and
_popupParcel.kiwi_userPreferences? and _popupParcel.kiwi_userPreferences.researchModeOnOff == 'on' or
(former_autoOffTimerType != _popupParcel.kiwi_userPreferences.autoOffTimerType or
former_autoOffTimerValue != _popupParcel.kiwi_userPreferences.autoOffTimerValue)
resetTimerBool = true
else
resetTimerBool = false
_autoOffAtUTCmilliTimestamp = setAutoOffTimer(resetTimerBool, _popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp,
_popupParcel.kiwi_userPreferences.autoOffTimerValue, _popupParcel.kiwi_userPreferences.autoOffTimerType,
_popupParcel.kiwi_userPreferences.researchModeOnOff)
_popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp = _autoOffAtUTCmilliTimestamp
firefoxStorage.storage.kiwi_userPreferences = _popupParcel.kiwi_userPreferences
firefoxStorage.storage.kiwi_servicesInfo = _popupParcel.kiwi_servicesInfo
if updateToView?
parcel = {}
_popupParcel['view'] = updateToView
popupParcel = _popupParcel
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = _popupParcel
sendParcel(parcel)
#console.log 'in _save_from_popupParcel _popupParcel.forUrl ' + _popupParcel.forUrl
#console.log 'in _save_from_popupParcel tabUrl ' + tabUrl
if _popupParcel.forUrl == tabUrl
if formerResearchModeValue? and formerResearchModeValue == 'off' and
_popupParcel.kiwi_userPreferences? and _popupParcel.kiwi_userPreferences.researchModeOnOff == 'on'
initIfNewURL(true); return 0
else if formerKiwi_servicesInfo?
# so if user turns on a service and saves - it will immediately begin new query
formerActiveServicesList = _.pluck(formerKiwi_servicesInfo, 'active')
newActiveServicesList = _.pluck(_popupParcel.kiwi_servicesInfo, 'active')
#console.log 'formerActiveServicesList = _.pluck(formerKiwi_servicesInfo)'
#console.debug formerActiveServicesList
#console.log 'newActiveServicesList = _.pluck(_popupParcel.kiwi_servicesInfo)'
#console.debug newActiveServicesList
if !_.isEqual(formerActiveServicesList, newActiveServicesList)
initIfNewURL(true); return 0
else
refreshBadge(_popupParcel.kiwi_servicesInfo, _popupParcel.allPreppedResults); return 0
else
refreshBadge(_popupParcel.kiwi_servicesInfo, _popupParcel.allPreppedResults); return 0
setAutoOffTimer = (resetTimerBool, autoOffAtUTCmilliTimestamp, autoOffTimerValue, autoOffTimerType, researchModeOnOff) ->
#console.log 'trying setAutoOffTimer 43234'
if resetTimerBool and kiwi_autoOffClearInterval?
#console.log 'clearing timout'
clearTimeout(kiwi_autoOffClearInterval)
kiwi_autoOffClearInterval = null
currentTime = Date.now()
new_autoOffAtUTCmilliTimestamp = null
if researchModeOnOff == 'on'
if autoOffAtUTCmilliTimestamp == null || resetTimerBool
if autoOffTimerType == '20'
new_autoOffAtUTCmilliTimestamp = currentTime + 20 * 60 * 1000
else if autoOffTimerType == '60'
new_autoOffAtUTCmilliTimestamp = currentTime + 60 * 60 * 1000
else if autoOffTimerType == 'always'
new_autoOffAtUTCmilliTimestamp = null
else if autoOffTimerType == 'custom'
new_autoOffAtUTCmilliTimestamp = currentTime + parseInt(autoOffTimerValue) * 60 * 1000
#console.log 'setting custom new_autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
else
new_autoOffAtUTCmilliTimestamp = autoOffAtUTCmilliTimestamp
if !kiwi_autoOffClearInterval? and autoOffAtUTCmilliTimestamp > currentTime
#console.log 'resetting timer timeout'
kiwi_autoOffClearInterval = setTimeout( ->
turnResearchModeOff()
, new_autoOffAtUTCmilliTimestamp - currentTime )
#console.log ' setting 123 autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
return new_autoOffAtUTCmilliTimestamp
else
# it's already off - no need for timer
new_autoOffAtUTCmilliTimestamp = null
#console.log 'researchModeOnOff is off - resetting autoOff timestamp and clearInterval'
if kiwi_autoOffClearInterval?
clearTimeout(kiwi_autoOffClearInterval)
kiwi_autoOffClearInterval = null
#console.log ' setting 000 autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
if new_autoOffAtUTCmilliTimestamp != null
#console.log 'setting timer timeout'
kiwi_autoOffClearInterval = setTimeout( ->
turnResearchModeOff()
, new_autoOffAtUTCmilliTimestamp - currentTime )
return new_autoOffAtUTCmilliTimestamp
turnResearchModeOff = ->
#console.log 'turning off research mode - in turnResearchModeOff'
# chrome.storage.sync.get(null, (allItemsInSyncedStorage) -> )
if kiwi_urlsResultsCache[tabUrl]?
urlResults = kiwi_urlsResultsCache[tabUrl]
else
urlResults = {}
if firefoxStorage.storage.kiwi_userPreferences?
firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff = 'off'
firefoxStorage.storage['kiwi_userPreferences'] = firefoxStorage.storage.kiwi_userPreferences
_set_popupParcel(urlResults, tabUrl, true)
if firefoxStorage.storage.kiwi_servicesInfo?
refreshBadge(firefoxStorage.storage.kiwi_servicesInfo, urlResults)
else
defaultUserPreferences.researchModeOnOff = 'off'
firefoxStorage.storage['kiwi_userPreferences'] = defaultUserPreferences
_set_popupParcel(urlResults, tabUrl, true)
if firefoxStorage.storage.kiwi_servicesInfo?
refreshBadge(firefoxStorage.storage.kiwi_servicesInfo, urlResults)
autoOffTimerExpired_orResearchModeOff_withoutURLoverride = (currentTime, overrideResearchModeOff, tabUrl, kiwi_urlsResultsCache) ->
if firefoxStorage.storage.kiwi_userPreferences?
if firefoxStorage.storage.kiwi_userPreferences.autoOffAtUTCmilliTimestamp?
if currentTime > firefoxStorage.storage.kiwi_userPreferences.autoOffAtUTCmilliTimestamp
#console.log 'timer is past due - turning off - in initifnewurl'
firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff = 'off'
if firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff is 'off' and overrideResearchModeOff == false
updateBadgeText('') # off
return true
return false
proceedWithPreInitCheck = (overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen) ->
if firefoxStorage.storage['kiwi_userPreferences']? and overrideResearchModeOff is false
# overrideResearchModeOff = is_url_whitelisted(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_whitelists, tabUrl)
isUrlWhitelistedBool = is_url_whitelisted(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_whitelists, tabUrl)
# provided that the user isn't specifically researching a URL, if it's whitelisted, then that acts as override
overrideResearchModeOff = isUrlWhitelistedBool
if autoOffTimerExpired_orResearchModeOff_withoutURLoverride(currentTime, overrideResearchModeOff, tabUrl, kiwi_urlsResultsCache) is true
# show cached responses, if present
#console.log 'if tabUrl == tempResponsesStore.forUrl'
#console.log tabUrl
#console.log tempResponsesStore.forUrl
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl],tabUrl,false);
if firefoxStorage.storage['kiwi_servicesInfo']?
refreshBadge(firefoxStorage.storage['kiwi_servicesInfo'], kiwi_urlsResultsCache[tabUrl])
else
_set_popupParcel({},tabUrl,true);
else
periodicCleanup(tabUrl, (tabUrl) ->
#console.log 'in initialize callback'
if !firefoxStorage.storage['kiwi_userPreferences']?
# defaultUserPreferences
#console.log "#console.debug allItemsInSyncedStorage['kiwi_userPreferences']"
#console.debug allItemsInSyncedStorage['kiwi_userPreferences']
_autoOffAtUTCmilliTimestamp = setAutoOffTimer(false, defaultUserPreferences.autoOffAtUTCmilliTimestamp,
defaultUserPreferences.autoOffTimerValue, defaultUserPreferences.autoOffTimerType, defaultUserPreferences.researchModeOnOff)
defaultUserPreferences.autoOffAtUTCmilliTimestamp = _autoOffAtUTCmilliTimestamp
# setObj =
# kiwi_servicesInfo: defaultServicesInfo
# kiwi_userPreferences: defaultUserPreferences
firefoxStorage.storage.kiwi_servicesInfo = defaultServicesInfo
firefoxStorage.storage.kiwi_userPreferences = defaultUserPreferences
# chrome.storage.sync.set(setObj, -> )
isUrlBlocked = is_url_blocked(defaultUserPreferences.urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true and overrideResearchModeOff == false
# user is not interested in results for this url
updateBadgeText('block')
#console.log '# user is not interested in results for this url: ' + tabUrl
_set_popupParcel({}, tabUrl, true) # trying to send, because options page
return 0 # we return before initializing script
initialize(tabUrl)
else
#console.log "allItemsInSyncedStorage['kiwi_userPreferences'].urlSubstring_blacklists"
#console.debug allItemsInSyncedStorage['kiwi_userPreferences'].urlSubstring_blacklists
isUrlBlocked = is_url_blocked(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true and overrideResearchModeOff == false
# user is not interested in results for this url
updateBadgeText('block')
#console.log '# user is not interested in results for this url: ' + tabUrl
_set_popupParcel({}, tabUrl, true) # trying to send, because options page
return 0 # we return/cease before initializing script
initialize(tabUrl)
)
checkForNewDefaultUserPreferenceAttributes_thenProceedWithInitCheck = (overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen) ->
# ^^ checks if newly added default user preference attributes exist (so new features don't break current installs)
setObj = {}
newUserPrefsAttribute = false
newServicesInfoAttribute = false
newServicesInfo = []
newUserPreferences = {}
if firefoxStorage.storage['kiwi_userPreferences']?
newUserPreferences = _.extend {}, firefoxStorage.storage['kiwi_userPreferences']
for keyName, value of defaultUserPreferences
if typeof firefoxStorage.storage['kiwi_userPreferences'][keyName] is 'undefined'
# console.log 'the following is a new keyName '
# console.log keyName
newUserPrefsAttribute = true
newUserPreferences[keyName] = value
if firefoxStorage.storage['kiwi_servicesInfo']?
# needs to handle entirely new services as well as simplly new attributes
newServicesInfo = _.extend [], firefoxStorage.storage['kiwi_servicesInfo']
for service_default, index in defaultServicesInfo
matchingService = _.find(firefoxStorage.storage['kiwi_servicesInfo'], (service_info) ->
if service_info.name is service_default.name
return true
else
return false
)
if matchingService?
newServiceObj = _.extend {}, matchingService
for keyName, value of service_default
# console.log keyName
if typeof matchingService[keyName] is 'undefined'
newServicesInfoAttribute = true
newServiceObj[keyName] = value
indexOfServiceToReplace = _.indexOf(newServicesInfo, matchingService)
newServicesInfo[indexOfServiceToReplace] = newServiceObj
else
# supports adding an entirely new service
newServicesInfoAttribute = true
# users that don't download with a specific service will need to opt-in to the new one
if service_default.active?
service_default.active = 'off'
newServicesInfo.push service_default
if newUserPrefsAttribute or newServicesInfoAttribute
if newUserPrefsAttribute
setObj['kiwi_userPreferences'] = newUserPreferences
if newServicesInfoAttribute
setObj['kiwi_servicesInfo'] = newServicesInfo
# this reminds me of the frog DNA injection from jurassic park
if newUserPrefsAttribute
firefoxStorage.storage['kiwi_userPreferences'] = newUserPreferences
if newServicesInfoAttribute
firefoxStorage.storage['kiwi_servicesInfo'] = newServicesInfo
# console.log 'console.debug allItemsInSyncedStorage'
# console.debug allItemsInSyncedStorage
proceedWithPreInitCheck(overrideSameURLCheck_popupOpen, overrideResearchModeOff,
sameURLCheck, tabUrl, currentTime, popupOpen)
else
proceedWithPreInitCheck(overrideSameURLCheck_popupOpen, overrideResearchModeOff,
sameURLCheck, tabUrl, currentTime, popupOpen)
# a wise coder once told me "try to keep functions to 10 lines or less." yea, welcome to initIfNewURL! let me find my cowboy hat :D
initIfNewURL = (overrideSameURLCheck_popupOpen = false, overrideResearchModeOff = false) ->
# console.log 'yoyoyo'
# if firefoxStorage.storage['kiwi_userPreferences']?
# console.log 'nothing 0 '
# console.log firefoxStorage.storage['kiwi_userPreferences'].researchModeOnOff
# # console.debug firefoxStorage.storage['kiwi_userPreferences']
# else
# console.log 'nothing'
if typeof overrideSameURLCheck_popupOpen != 'boolean'
# ^^ because the Chrome api tab listening functions were exec-ing callback with an integer argument
# that has since been negated by nesting the callback, but why not leave the check here?
overrideSameURLCheck_popupOpen = false
# #console.log 'wtf 1 kiwi_urlsResultsCache ' + overrideSameURLCheck_popupOpen
if overrideSameURLCheck_popupOpen # for when a user turns researchModeOnOff "on" or refreshes results from popup
popupOpen = true
else
popupOpen = false
currentTime = Date.now()
# chrome.tabs.getSelected(null,(tab) ->
# chrome.tabs.query({ currentWindow: true, active: true }, (tabs) ->
if tabs.activeTab.url?
# console.log 'if tabs.activeTab.url?'
# console.log tabs.activeTab.url
# console.log tabs.activeTab
if tabs.activeTab.url.indexOf('chrome-devtools://') != 0
tabUrl = tabs.activeTab.url
# console.log 'tabUrl = tabs.activeTab.url'
# console.log tabUrl
# we care about the title, because it's the best way to search google news
if tabs.activeTab.readyState == 'complete'
title = tabs.activeTab.title
# a little custom title formatting for sites that begin their tab titles with "(<number>)" like twitter.com
if title.length > 3 and title[0] == "(" and isNaN(title[1]) == false and title.indexOf(')') != -1 and
title.indexOf(')') != title.length - 1
title = title.slice(title.indexOf(')') + 1 , title.length).trim()
tabTitleObject =
tabTitle: title
forUrl: tabUrl
else
tabTitleObject =
tabTitle: null
forUrl: tabUrl
else
_set_popupParcel({}, tabUrl, false)
#console.log 'chrome-devtools:// has been the only url visited so far'
return 0
tabUrl_hash = toSHA512(tabUrl)
sameURLCheck = true
# firefox's toSHA512 function usually returned a string ending in "=="
tabUrl_hash = tabUrl_hash.substring(0, tabUrl_hash.length - 2);
historyString = reduceHashByHalf(tabUrl_hash)
updateBadgeText('')
if !firefoxStorage.storage.persistentUrlHash?
firefoxStorage.storage.persistentUrlHash = ''
if overrideSameURLCheck_popupOpen == false and firefoxStorage.storage['kiwi_historyBlob']? and
firefoxStorage.storage['kiwi_historyBlob'].indexOf(historyString) != -1 and
(!kiwi_urlsResultsCache? or !kiwi_urlsResultsCache[tabUrl]?)
# console.log ' trying to set as old 123412341241234 '
updateBadgeText('old')
sameURLCheck = true
_set_popupParcel({}, tabUrl, false, null, true)
else if (overrideSameURLCheck_popupOpen == false and !firefoxStorage.storage.persistentUrlHash?) or
firefoxStorage.storage.persistentUrlHash? and firefoxStorage.storage.persistentUrlHash != tabUrl_hash
sameURLCheck = false
else if overrideSameURLCheck_popupOpen == true
sameURLCheck = false
#useful for switching window contexts
# chrome.storage.local.set({'persistentUrlHash': tabUrl_hash}, ->)
firefoxStorage.storage['persistentUrlHash'] = tabUrl_hash
if sameURLCheck == false
updateBadgeText('')
checkForNewDefaultUserPreferenceAttributes_thenProceedWithInitCheck(overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen)
tabs.on 'ready', (tab) ->
# console.log('tab is loaded', tab.title, tab.url)
initIfNewURL()
tabs.on('activate', ->
# console.log('active: ' + tabs.activeTab.url);
initIfNewURL()
)
# intial startup
if tabTitleObject == null
initIfNewURL(true)
| true |
self = require('sdk/self')
tabs = require("sdk/tabs")
base64 = require("sdk/base64")
firefoxStorage = require("sdk/simple-storage")
Panel = require("sdk/panel").Panel # <-> same thing, but one is clearer # { Panel } = require("sdk/panel")
IconButton = require("sdk/ui/button/action").ActionButton
{ setTimeout, clearTimeout } = require("sdk/timers")
{ Cc, Ci } = require('chrome')
# kiwi_popup = require('./KiwiPopup')
Request = require("sdk/request").Request
_ = require('./data/vendor/underscore-min')
tabUrl = ''
tabTitleObject = null
popupOpen = false
checkForUrlHourInterval = 16
checkForUrl_Persistent_ChromeNotification_HourInterval = 3 # (max of 5 notification items)
last_periodicCleanup = 0 # timestamp
CLEANUP_INTERVAL = 3 * 3600000 # three hours
queryThrottleSeconds = 3 # to respect the no-more-than 30/min stiplation for Reddit's api
serviceQueryTimestamps = {}
maxUrlResultsStoredInLocalStorage = 800 # they're deleted after they've expired anyway - so this likely won't be reached by user
popupParcel = {}
# proactively set if each services' preppedResults are ready.
# will be set with available results if queried by popup.
# {
# forUrl:
# allPreppedResults:
# kiwi_servicesInfo:
# kiwi_customSearchResults:
# kiwi_alerts:
# kiwi_userPreferences:
# }
kiwi_userMessages = {
"redditDown":
"baseValue":"reddit's API is unavailable, so results may not appear from this service for some time"
"name":"redditDown"
"sentAndAcknowledgedInstanceObjects": []
# {
# "sentTimestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"productHuntDown":
"name":"productHuntDown"
"baseValue":"Product Hunt's API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
"productHuntDown__customSearch":
"name":"productHuntDown__customSearch"
"baseValue":"Product Hunt's custom search API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"hackerNewsDown":
"name":"hackerNewsDown"
"baseValue":"Hacker News' API has not been consistently available, so results may not reliably appear from this service."
"sentAndAcknowledgedInstanceObjects": []
# {
# "timestamp"
# "userAcknowledged": <timestamp>
# "urgencyLevel"
# } ...
"generalConnectionFailure":
"name":"generalConnectionFailure"
"baseValue":"There has been a network connection issue. Check your internet connection / try again in a few minutes :)"
"sentAndAcknowledgedInstanceObjects": []
}
kiwi_urlsResultsCache = {}
# < url >:
# < serviceName >: {
# forUrl: url
# timestamp:
# service_PreppedResults:
# urlBlocked:
# }
kiwi_customSearchResults = {} # stores temporarily so if they close popup, they'll still have results
# maybe it won't clear until new result -- "see last search"
# queryString
# servicesSearchesRequested = responsePackage.servicesToSearch
# servicesSearched
# <serviceName>
# results
kiwi_autoOffClearInterval = null
kiwi_reddit_token_refresh_interval = null
# timestamp:
# intervalId:
kiwi_productHunt_token_refresh_interval = null
# timestamp:
# intervalId:
tempResponsesStore = {}
# forUrl: < url >
# results:
# < serviceName > :
# timestamp:
# service_PreppedResults:
# forUrl: url
getRandom = (min, max) ->
return min + Math.floor(Math.random() * (max - min + 1))
randomishDeviceId = -> # to be held in localStorage
randomClientLength = getRandom(21,29)
characterCounter = 0
randomString = ""
while characterCounter <= randomClientLength
characterCounter++
randomASCIIcharcode = getRandom(33,125)
#console.log randomASCIIcharcode
randomString += String.fromCharCode(randomASCIIcharcode)
return randomString
temp__kiwi_reddit_oauth =
token: null
token_type: null
token_lifespan_timestamp: null
client_id: "" # your client id here
device_id: randomishDeviceId()
temp__kiwi_productHunt_oauth =
token: null
token_type: null
token_lifespan_timestamp: null
client_id: "" # your client id here
client_secret: "" # your secret id here
defaultUserPreferences = {
fontSize: .8 # not yet implemented
researchModeOnOff: 'off' # or 'on'
autoOffAtUTCmilliTimestamp: null
autoOffTimerType: 'always' # 'custom','always','20','60'
autoOffTimerValue: null
sortByPref: 'attention' # 'recency' # "attention" means 'comments' if story, 'points' if comment, 'clusterUrl' if news
installedTime: Date.now()
urlSubstring_whitelists:
anyMatch: []
beginsWith: []
endingIn: []
unless: [
# ['twitter.com/','/status/'] # unless /status/
]
# suggested values to all users -- any can be overriden with the "Research this URL" button
# unfortunately, because of Chrome's discouragement of storing sensitive
# user info with chrome.storage, blacklists are fixed for now . see: https://news.ycombinator.com/item?id=9993030
urlSubstring_blacklists:
anyMatch: [
'facebook.com'
'news.ycombinator.com'
'reddit.com'
'imgur.com'
'www.google.com'
'docs.google'
'drive.google'
'accounts.google'
'.slack.com/'
'//t.co'
'//bit.ly'
'//goo.gl'
'//mail.google'
'//mail.yahoo.com'
'hotmail.com'
'outlook.com'
'chrome-extension://'
'chrome-devtools://' # hardcoded block
# "about:blank"
# "about:newtab"
]
beginsWith: [
"about:"
'chrome://'
]
endingIn: [
#future - ending in:
'youtube.com' # /
]
unless: [
#unless
['twitter.com/','/status/'] # unless /status/
# ,
# 'twitter.com'
]
}
defaultServicesInfo = [
name:"hackerNews"
title: "Hacker News"
abbreviation: "H"
queryApi:"https://hn.algolia.com/api/v1/search?restrictSearchableAttributes=url&query="
broughtToYouByTitle:"Algolia Hacker News API"
broughtToYouByURL:"https://hn.algolia.com/api"
brandingImage: null
brandingSlogan: null
permalinkBase: 'https://news.ycombinator.com/item?id='
userPageBaselink: 'https://news.ycombinator.com/user?id='
submitTitle: 'Be the first to submit on Hacker News!'
submitUrl: 'https://news.ycombinator.com/submit'
active: 'on'
notableConditions:
hoursSincePosted: 4 # an exact match is less than 5 hours old
num_comments: 10 # an exact match has 10 comments
updateBadgeOnlyWithExactMatch: true
customSearchApi: "https://hn.algolia.com/api/v1/search?query="
customSearchTags__convention: {'string':'&tags=','delimeter':','}
customSearchTags:
story:
title: "stories"
string: "story"
include: true
commentPolls:
title: "comments or polls"
string:"(comment,poll,pollopt)"
include: false
showHnAskHn:
title: "Show HN or Ask HN"
string:"(show_hn,ask_hn)"
include: false
# customSearch
# queryApi https://hn.algolia.com/api/v1/search?query=
# tags= filter on a specific tag. Available tags:
# story
# comment
# poll
# pollopt
# show_hn
# ask_hn
# front_page
# author_:USERNAME
# story_:ID
# author_pg,(story,poll) filters on author=pg AND (type=story OR type=poll).
customSearchBroughtToYouByURL: null
customSearchBroughtToYouByTitle: null
conversationSite: true
,
name:"reddit"
title: "reddit"
abbreviation: "R"
queryApi:"https://www.reddit.com/submit.json?url="
broughtToYouByTitle:"Reddit API"
broughtToYouByURL:"https://github.com/reddit/reddit/wiki/API"
brandingImage: null
brandingSlogan: null
permalinkBase: 'https://www.reddit.com'
userPageBaselink: 'https://www.reddit.com/user/'
submitTitle: 'Be the first to submit on Reddit!'
submitUrl: 'https://www.reddit.com/submit'
active: 'on'
notableConditions:
hoursSincePosted: 1 # an exact match is less than 5 hours old
num_comments: 30 # an exact match has 30 comments
updateBadgeOnlyWithExactMatch: true
customSearchApi: "https://www.reddit.com/search.json?q="
customSearchTags: {}
customSearchBroughtToYouByURL: null
customSearchBroughtToYouByTitle: null
conversationSite: true
,
name:"productHunt"
title: "Product Hunt"
abbreviation: "P"
queryApi:"https://api.producthunt.com/v1/posts/all?search[url]="
broughtToYouByTitle:"Product Hunt API"
broughtToYouByURL:"https://api.producthunt.com/v1/docs"
permalinkBase: 'https://producthunt.com/'
userPageBaselink: 'https://www.producthunt.com/@'
brandingImage: "product-hunt-logo-orange-240.png"
brandingSlogan: null
submitTitle: 'Be the first to submit to Product Hunt!'
submitUrl: 'https://www.producthunt.com/tech/new'
active: 'on'
notableConditions:
hoursSincePosted: 4 # an exact match is less than 5 hours old
num_comments: 10 # an exact match has 30 comments
# 'featured'
updateBadgeOnlyWithExactMatch: true
# uses Algolia index, not a typical rest api
customSearchApi: ""
customSearchTags: {}
customSearchBroughtToYouByURL: 'https://www.algolia.com/doc/javascript'
customSearchBroughtToYouByTitle: "Algolia's Search API"
conversationSite: true
# {
# so many great communities out there! ping me @spencenow if an API surfaces for yours!
# 2015-8-13 - producthunt has been implemented! holy crap this is cool! :D
# working on Slashdot...!
# },
]
send_kiwi_userMessage = (messageName, urgencyLevel, extraNote = null) ->
currentTime = Date.now()
sendMessageBool = true
# messageName
# if the same message has been sent in last five minutes, don't worry.
messageObj = kiwi_userMessages[messageName]
for sentInstance in messageObj.sentAndAcknowledgedInstanceObjects
if sentInstance.userAcknowledged? and (currentTime - sentInstance.userAcknowledged < 1000 * 60 * 20)
sendMessageBool = false
else if !sentInstance.userAcknowledged?
sendMessageBool = false
if sendMessageBool is true
kiwi_userMessages[messageName].sentAndAcknowledgedInstanceObjects.push {
"sentTimestamp": currentTime
"userAcknowledged": null # <timestamp>
}
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else if tempResponsesStore? and tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
shuffle_array = (array) ->
currentIndex = array.length;
# // While there remain elements to shuffle...
while (0 != currentIndex)
# // Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
# // And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
return array
randomizeDefaultConversationSiteOrder = ->
conversationSiteServices = []
nonConversationSiteServices = []
for service in defaultServicesInfo
if service.conversationSite
conversationSiteServices.push service
else
nonConversationSiteServices.push service
newDefaultServices = []
conversationSiteServices = shuffle_array(conversationSiteServices)
defaultServicesInfo = conversationSiteServices.concat(nonConversationSiteServices)
randomizeDefaultConversationSiteOrder()
# ~~~ starting out with negotiating oAuth tokens and initializing necessary api objects ~~~ #
reduceHashByHalf = (hash, reducedByAFactorOf = 1) ->
reduceStringByHalf = (_string_) ->
newShortenedString = ''
for char, index in _string_
if index % 2 is 0 and (_string_.length - 1 > index + 1)
char = if char > _string_[index + 1] then char else _string_[index + 1]
newShortenedString += char
return newShortenedString
finalHash = ''
counter = 0
while counter < reducedByAFactorOf
hash = reduceStringByHalf(hash)
counter++
return hash
kiwi_iconButton = IconButton {
id: "kiwi-button",
label: "Kiwi Conversations",
badge: '',
badgeColor: "#00AAAA",
icon: {
"16": "./kiwiFavico16.png",
"32": "./kiwiFavico32.png",
"64": "./kiwiFavico64.png"
},
onClick: (iconButtonState) ->
# console.log("button '" + iconButtonState.label + "' was clicked")
iconButtonClicked(iconButtonState)
}
iconButtonClicked = (iconButtonState) ->
# kiwi_iconButton.badge = iconButtonState.badge + 1
if (iconButtonState.checked)
kiwi_iconButton.badgeColor = "#AA00AA"
else
kiwi_iconButton.badgeColor = "#00AAAA"
kiwiPP_request_popupParcel()
kiwi_panel.show({'position':kiwi_iconButton})
# <link rel="stylesheet" href="vendor/bootstrap-3.3.5-dist/css/bootstrap.min.css"></link>
# <link rel="stylesheet" href="vendor/bootstrap-3.3.5-dist/css/bootstrap-theme.min.css"></link>
# <link rel="stylesheet" href="vendor/behigh-bootstrap_dropdown_enhancement/css/dropdowns-enhancement.min.css"></link>
# <script src="vendor/jquery-2.1.4.min.js" ></script>
# <script src="vendor/Underscore1-8-3.js"></script>
# <script src="vendor/bootstrap-3.3.5-dist/js/bootstrap.min.js"></script>
# <script src=""></script>
kiwiPP_request_popupParcel = (dataFromPopup = {}) ->
# console.log 'kiwiPP_request_popupParcel = (dataFromPopup = {}) ->'
popupOpen = true
preppedResponsesInPopupParcel = 0
if popupParcel? and popupParcel.allPreppedResults?
#console.log 'popupParcel.allPreppedResults? '
#console.debug popupParcel.allPreppedResults
for serviceName, service of popupParcel.allPreppedResults
if service.service_PreppedResults?
preppedResponsesInPopupParcel += service.service_PreppedResults.length
preppedResponsesInTempResponsesStore = 0
if tempResponsesStore? and tempResponsesStore.services?
for serviceName, service of tempResponsesStore.services
preppedResponsesInTempResponsesStore += service.service_PreppedResults.length
newResultsBool = false
if tempResponsesStore.forUrl == tabUrl and preppedResponsesInTempResponsesStore != preppedResponsesInPopupParcel
newResultsBool = true
if popupParcel? and popupParcel.forUrl is tabUrl and newResultsBool == false
#console.log "popup parcel ready"
parcel = {}
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = popupParcel
sendParcel(parcel)
else
if !tempResponsesStore.services? or tempResponsesStore.forUrl != tabUrl
_set_popupParcel({}, tabUrl, true)
else
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
kiwi_panel = Panel({
width: 500,
height: 640,
# contentURL: "https://en.wikipedia.org/w/index.php?title=Jetpack&useformat=mobile",
contentURL: "./popup.html",
contentStyleFile: ["./bootstrap-3.3.5-dist/css/bootstrap.min.css",
"./bootstrap-3.3.5-dist/css/bootstrap-theme.min.css",
"./behigh-bootstrap_dropdown_enhancement/css/dropdowns-enhancement.min.css"
],
contentScriptFile: ["./vendor/jquery-2.1.4.min.js",
"./vendor/underscore-min.js",
"./behigh-bootstrap_dropdown_enhancement/js/dropdowns-enhancement.js",
"./vendor/algoliasearch.min.js",
"./KiwiPopup.js"]
})
updateBadgeText = (newBadgeText) ->
kiwi_iconButton.badge = newBadgeText
setTimeout_forRedditRefresh = (token_timestamp, kiwi_reddit_oauth, ignoreTimeoutDelayComparison = false) ->
currentTime = Date.now()
timeoutDelay = token_timestamp - currentTime
if kiwi_reddit_token_refresh_interval? and kiwi_reddit_token_refresh_interval.timestamp? and ignoreTimeoutDelayComparison is false
if timeoutDelay > kiwi_reddit_token_refresh_interval.timestamp - currentTime
# console.log 'patience, we will be trying again soon'
return 0
if kiwi_reddit_token_refresh_interval? and kiwi_reddit_token_refresh_interval.timestamp?
clearTimeout(kiwi_reddit_token_refresh_interval.intervalId)
timeoutIntervalId = setTimeout( ->
requestRedditOathToken(kiwi_reddit_oauth)
, timeoutDelay )
kiwi_reddit_token_refresh_interval =
timestamp: token_timestamp
intervalId: timeoutIntervalId
requestRedditOathToken = (kiwi_reddit_oauth) ->
currentTime = Date.now()
Request({
url: 'https://www.reddit.com/api/v1/access_token',
headers: {
'Authorization': 'Basic ' + base64.encode(kiwi_reddit_oauth.client_id + ":")
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
},
content: {
grant_type: "https://oauth.reddit.com/grants/installed_client"
device_id: kiwi_reddit_oauth.device_id
},
onComplete: (response) ->
if(response.status == 0 or response.status == 504 or response.status == 503 or
response.status == 502 or response.status == 401)
tryAgainTimestamp = currentTime + (1000 * 60 * 3)
setTimeout_forRedditRefresh(tryAgainTimestamp, kiwi_reddit_oauth)
send_kiwi_userMessage("redditDown")
# console.log('unavailable!2')
else
if response.json.access_token? and response.json.expires_in? and response.json.token_type == "bearer"
#console.log 'response from reddit!'
token_lifespan_timestamp = currentTime + response.json.expires_in * 1000
setObj =
token: response.json.access_token
token_type: 'bearer'
token_lifespan_timestamp: token_lifespan_timestamp
client_id: kiwi_reddit_oauth.client_id
device_id: kiwi_reddit_oauth.device_id
firefoxStorage.storage.kiwi_reddit_oauth = setObj
setTimeout_forRedditRefresh(token_lifespan_timestamp, setObj)
}).post()
setTimeout_forProductHuntRefresh = (token_timestamp, kiwi_productHunt_oauth, ignoreTimeoutDelayComparison = false) ->
currentTime = Date.now()
timeoutDelay = token_timestamp - currentTime
if kiwi_productHunt_token_refresh_interval? and kiwi_productHunt_token_refresh_interval.timestamp? and ignoreTimeoutDelayComparison is false
if timeoutDelay > kiwi_productHunt_token_refresh_interval.timestamp - currentTime
# console.log 'patience, we will be trying again soon'
return 0
if kiwi_productHunt_token_refresh_interval? and kiwi_productHunt_token_refresh_interval.timestamp?
clearTimeout(kiwi_productHunt_token_refresh_interval.intervalId)
timeoutIntervalId = setTimeout( ->
requestProductHuntOauthToken(kiwi_productHunt_oauth)
, timeoutDelay )
kiwi_productHunt_token_refresh_interval =
timestamp: token_timestamp
intervalId: timeoutIntervalId
requestProductHuntOauthToken = (kiwi_productHunt_oauth) ->
currentTime = Date.now()
Request({
content: {
"client_id": kiwi_productHunt_oauth.client_id
"client_secret": kiwi_productHunt_oauth.client_secret
"grant_type" : "client_credentials"
}
url: 'https://api.producthunt.com/v1/oauth/token'
headers: {}
onComplete: (response) ->
if(response.status == 0 or response.status == 504 or response.status == 503 or
response.status == 502 or response.status == 401)
# // do connection timeout handling
tryAgainTimestamp = currentTime + (1000 * 60 * 3)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, kiwi_productHunt_oauth)
send_kiwi_userMessage("productHuntDown")
# console.log('unavailable!3')
else
# console.log 'check this'
# console.log response.json
if response.json? and response.json.access_token? and response.json.expires_in? and response.json.token_type == "bearer"
token_lifespan_timestamp = currentTime + response.json.expires_in * 1000
setObj = {}
setObj =
token: response.json.access_token
scope: "public"
token_type: 'bearer'
token_lifespan_timestamp: token_lifespan_timestamp
client_id: kiwi_productHunt_oauth.client_id
client_secret: kiwi_productHunt_oauth.client_secret
firefoxStorage.storage.kiwi_productHunt_oauth = setObj
setTimeout_forProductHuntRefresh(token_lifespan_timestamp, setObj)
}).post()
negotiateOauthTokens = ->
currentTime = Date.now()
if !firefoxStorage.storage.kiwi_productHunt_oauth? or !firefoxStorage.storage.kiwi_productHunt_oauth.token?
# console.log 'ph oauth does not exist in firefox storage'
requestProductHuntOauthToken(temp__kiwi_productHunt_oauth)
if !firefoxStorage.storage.kiwi_productHunt_oauth? or !firefoxStorage.storage.kiwi_productHunt_oauth.token?
# do nothing
else if (firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp? and
currentTime > firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp) or
!firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp?
#console.log "3 setObj['kiwi_productHunt_oauth'] ="
requestProductHuntOauthToken(temp__kiwi_productHunt_oauth)
else if firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp? and firefoxStorage.storage.kiwi_productHunt_oauth?
#console.log "4 setObj['kiwi_productHunt_oauth'] ="
token_timestamp = firefoxStorage.storage.kiwi_productHunt_oauth.token_lifespan_timestamp
if !kiwi_productHunt_token_refresh_interval? or kiwi_productHunt_token_refresh_interval.timestamp != token_timestamp
setTimeout_forProductHuntRefresh(token_timestamp, firefoxStorage.storage.kiwi_productHunt_oauth)
if !firefoxStorage.storage.kiwi_reddit_oauth? or !firefoxStorage.storage.kiwi_reddit_oauth.token?
requestRedditOathToken(temp__kiwi_reddit_oauth)
if !firefoxStorage.storage.kiwi_reddit_oauth? or !firefoxStorage.storage.kiwi_reddit_oauth.token?
# do nothing
else if (firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp? and
currentTime > firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp) or
!firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp?
#console.log "3 setObj['kiwi_reddit_oauth'] ="
requestRedditOathToken(temp__kiwi_reddit_oauth)
else if firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp? and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log "4 setObj['kiwi_reddit_oauth'] ="
token_timestamp = firefoxStorage.storage.kiwi_reddit_oauth.token_lifespan_timestamp
if !kiwi_reddit_token_refresh_interval? or kiwi_reddit_token_refresh_interval.timestamp != token_timestamp
setTimeout_forRedditRefresh(token_timestamp, firefoxStorage.storage.kiwi_reddit_oauth)
negotiateOauthTokens()
is_url_blocked = (blockedLists, url) ->
return doesURLmatchSubstringLists(blockedLists, url)
is_url_whitelisted = (whiteLists, url) ->
return doesURLmatchSubstringLists(whiteLists, url)
doesURLmatchSubstringLists = (urlSubstringLists, url) ->
if urlSubstringLists.anyMatch?
for urlSubstring in urlSubstringLists.anyMatch
if url.indexOf(urlSubstring) != -1
return true
if urlSubstringLists.beginsWith?
for urlSubstring in urlSubstringLists.beginsWith
if url.indexOf(urlSubstring) == 0
return true
if urlSubstringLists.endingIn?
for urlSubstring in urlSubstringLists.endingIn
if url.indexOf(urlSubstring) == url.length - urlSubstring.length
return true
urlSubstring += '/'
if url.indexOf(urlSubstring) == url.length - urlSubstring.length
return true
if urlSubstringLists.unless?
for urlSubstringArray in urlSubstringLists.unless
if url.indexOf(urlSubstringArray[0]) != -1
if url.indexOf(urlSubstringArray[1]) == -1
return true
return false
returnNumberOfActiveServices = (servicesInfo) ->
numberOfActiveServices = 0
for service in servicesInfo
if service.active == 'on'
numberOfActiveServices++
return numberOfActiveServices
sendParcel = (parcel) ->
if !parcel.msg? or !parcel.forUrl?
return false
switch parcel.msg
when 'kiwiPP_popupParcel_ready'
kiwi_panel.port.emit('kiwi_fromBackgroundToPopup', parcel)
_save_a_la_carte = (parcel) ->
firefoxStorage.storage[parcel.keyName] = parcel.newValue
if !tempResponsesStore? or !tempResponsesStore.services?
tempResponsesStoreServices = {}
else
tempResponsesStoreServices = tempResponsesStore.services
if parcel.refreshView?
_set_popupParcel(tempResponsesStoreServices, tabUrl, true, parcel.refreshView)
else
_set_popupParcel(tempResponsesStoreServices, tabUrl, false)
kiwi_panel.port.on("kiwiPP_acknowledgeMessage", (dataFromPopup) ->
popupOpen = true
currentTime = Date.now()
for sentInstance, index in kiwi_userMessages[dataFromPopup.messageToAcknowledge].sentAndAcknowledgedInstanceObjects
if !sentInstance.userAcknowledged?
kiwi_userMessages[dataFromPopup.messageToAcknowledge].sentAndAcknowledgedInstanceObjects[index] = currentTime
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else if tempResponsesStore? and tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
)
kiwi_panel.port.on("kiwiPP_post_customSearch", (dataFromPopup) ->
popupOpen = true
if dataFromPopup.customSearchRequest? and dataFromPopup.customSearchRequest.queryString? and
dataFromPopup.customSearchRequest.queryString != ''
if firefoxStorage.storage['kiwi_servicesInfo']?
# #console.log 'when kiwiPP_post_customSearch3'
for serviceInfoObject in firefoxStorage.storage['kiwi_servicesInfo']
#console.log 'when kiwiPP_post_customSearch4 for ' + serviceInfoObject.name
if dataFromPopup.customSearchRequest.servicesToSearch[serviceInfoObject.name]?
# console.log 'trying custom search PH'
# console.log dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults
if serviceInfoObject.name is 'productHunt' and dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults?
responsePackage = {
servicesInfo: firefoxStorage.storage['kiwi_servicesInfo']
servicesToSearch: dataFromPopup.customSearchRequest.servicesToSearch
customSearchQuery: dataFromPopup.customSearchRequest.queryString
serviceName: serviceInfoObject.name
queryResult: dataFromPopup.customSearchRequest.servicesToSearch.productHunt.rawResults
}
setPreppedServiceResults__customSearch(responsePackage, firefoxStorage.storage['kiwi_servicesInfo'])
else
if serviceInfoObject.customSearchApi? and serviceInfoObject.customSearchApi != ''
dispatchQuery__customSearch(dataFromPopup.customSearchRequest.queryString, dataFromPopup.customSearchRequest.servicesToSearch, serviceInfoObject, firefoxStorage.storage['kiwi_servicesInfo'])
)
kiwi_panel.port.on "kiwiPP_researchUrlOverrideButton", (dataFromPopup) ->
popupOpen = true
initIfNewURL(true,true)
kiwi_panel.port.on "kiwiPP_clearAllURLresults", (dataFromPopup) ->
popupOpen = true
updateBadgeText('')
kiwi_urlsResultsCache = {}
tempResponsesStore = {}
_set_popupParcel({}, tabUrl, true)
kiwi_panel.port.on "kiwiPP_refreshSearchQuery", (dataFromPopup) ->
popupOpen = true
kiwi_customSearchResults = {}
if tempResponsesStore.forUrl == tabUrl
_set_popupParcel(tempResponsesStore.services, tabUrl, true)
else if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
kiwi_panel.port.on "kiwiPP_refreshURLresults", (dataFromPopup) ->
popupOpen = true
if kiwi_urlsResultsCache? and kiwi_urlsResultsCache[tabUrl]?
delete kiwi_urlsResultsCache[tabUrl]
tempResponsesStore = {}
initIfNewURL(true)
kiwi_panel.port.on "kiwiPP_reset_timer", (dataFromPopup) ->
popupOpen = true
dataFromPopup.kiwi_userPreferences['autoOffAtUTCmilliTimestamp'] = setAutoOffTimer(true,
dataFromPopup.kiwi_userPreferences.autoOffAtUTCmilliTimestamp,
dataFromPopup.kiwi_userPreferences.autoOffTimerValue,
dataFromPopup.kiwi_userPreferences.autoOffTimerType,
dataFromPopup.kiwi_userPreferences.researchModeOnOff
)
parcel =
refreshView: 'userPreferences'
keyName: 'PI:KEY:<KEY>END_PI'
newValue: dataFromPopup.kiwi_userPreferences
localOrSync: 'sync'
_save_a_la_carte(parcel)
kiwi_panel.port.on "kiwiPP_post_save_a_la_carte", (dataFromPopup) ->
popupOpen = true
_save_a_la_carte(dataFromPopup)
kiwi_panel.port.on "kiwiPP_post_savePopupParcel", (dataFromPopup) ->
popupOpen = true
_save_from_popupParcel(dataFromPopup.newPopupParcel, tabUrl, dataFromPopup.refreshView)
if kiwi_urlsResultsCache[tabUrl]?
refreshBadge(dataFromPopup.newPopupParcel.kiwi_servicesInfo, kiwi_urlsResultsCache[tabUrl])
kiwi_panel.port.on "kiwiPP_request_popupParcel", (dataFromPopup) ->
kiwiPP_request_popupParcel(dataFromPopup)
initialize = (currentUrl) ->
if !firefoxStorage.storage.kiwi_servicesInfo?
firefoxStorage.storage.kiwi_servicesInfo = defaultServicesInfo
getUrlResults_to_refreshBadgeIcon(defaultServicesInfo, currentUrl)
else
getUrlResults_to_refreshBadgeIcon(firefoxStorage.storage['kiwi_servicesInfo'], currentUrl)
getUrlResults_to_refreshBadgeIcon = (servicesInfo, currentUrl) ->
currentTime = Date.now()
if Object.keys(kiwi_urlsResultsCache).length > 0
# to prevent repeated api requests - we check to see if we have up-to-date request results in local storage
if kiwi_urlsResultsCache[currentUrl]?
# start off by instantly updating UI with what we know
refreshBadge(servicesInfo, kiwi_urlsResultsCache[currentUrl])
for service in servicesInfo
if kiwi_urlsResultsCache[currentUrl][service.name]?
if (currentTime - kiwi_urlsResultsCache[currentUrl][service.name].timestamp) > checkForUrlHourInterval * 3600000
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
return 0
else
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
return 0
# for urls that are being visited a second time,
# all recent results present kiwi_urlsResultsCache (for all services)
# we set tempResponsesStore before setting popupParcel
tempResponsesStore.forUrl = currentUrl
tempResponsesStore.services = kiwi_urlsResultsCache[currentUrl]
#console.log '#console.debug tempResponsesStore.services'
#console.debug tempResponsesStore.services
_set_popupParcel(tempResponsesStore.services, currentUrl, true)
else
# this url has not been checked
#console.log '# this url has not been checked'
check_updateServiceResults(servicesInfo, currentUrl, kiwi_urlsResultsCache)
else
#console.log '# no urls have been checked'
check_updateServiceResults(servicesInfo, currentUrl, null)
_save_url_results = (servicesInfo, tempResponsesStore, _urlsResultsCache) ->
#console.log 'yolo 3'
urlsResultsCache = _.extend {}, _urlsResultsCache
previousUrl = tempResponsesStore.forUrl
if urlsResultsCache[previousUrl]?
# these will always be at least as recent as what's in the store.
for service in servicesInfo
if tempResponsesStore.services[service.name]?
urlsResultsCache[previousUrl][service.name] =
forUrl: previousUrl
timestamp: tempResponsesStore.services[service.name].timestamp
service_PreppedResults: tempResponsesStore.services[service.name].service_PreppedResults
else
urlsResultsCache[previousUrl] = {}
urlsResultsCache[previousUrl] = tempResponsesStore.services
return urlsResultsCache
__randomishStringPadding = ->
randomPaddingLength = getRandom(1,3)
characterCounter = 0
paddingString = ""
while characterCounter <= randomPaddingLength
randomLatinKeycode = getRandom(33,121)
String.fromCharCode(randomLatinKeycode)
paddingString += String.fromCharCode(randomLatinKeycode)
characterCounter++
return paddingString
toSHA512 = (str) ->
# // Convert string to an array of bytes
array = Array.prototype.slice.call(str)
# // Create SHA512 hash
hashEngine = Cc["@mozilla.org/security/hash;1"].createInstance(Ci.nsICryptoHash)
hashEngine.init(hashEngine.MD5)
hashEngine.update(array, array.length)
return hashEngine.finish(true)
_save_historyBlob = (kiwi_urlsResultsCache, tabUrl) ->
tabUrl_hash = toSHA512(tabUrl)
# firefox's toSHA512 function usually returned a string ending in "=="
tabUrl_hash = tabUrl_hash.substring(0, tabUrl_hash.length - 2);
historyString = reduceHashByHalf(tabUrl_hash)
paddedHistoryString = __randomishStringPadding() + historyString + __randomishStringPadding()
if firefoxStorage.storage.kiwi_historyBlob? and typeof firefoxStorage.storage.kiwi_historyBlob == 'string' and
firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) < 15000 and firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) != -1
#console.log '# already exists in history blob ' + allItemsInLocalStorage.kiwi_historyBlob.indexOf(historyString)
return 0
else
if firefoxStorage.storage['kiwi_historyBlob']?
newKiwi_historyBlob = paddedHistoryString + firefoxStorage.storage['kiwi_historyBlob']
else
newKiwi_historyBlob = paddedHistoryString
# we cap the size of the history blob at 17000 characters
if firefoxStorage.storage.kiwi_historyBlob? and firefoxStorage.storage.kiwi_historyBlob.indexOf(historyString) > 17000
newKiwi_historyBlob = newKiwi_historyBlob.substring(0,15500)
firefoxStorage.storage.kiwi_historyBlob = newKiwi_historyBlob
check_updateServiceResults = (servicesInfo, currentUrl, urlsResultsCache = null) ->
#console.log 'yolo 4'
# if any results from previous tab have not been set, set them.
if urlsResultsCache? and Object.keys(tempResponsesStore).length > 0
previousResponsesStore = _.extend {}, tempResponsesStore
_urlsResultsCache = _.extend {}, urlsResultsCache
kiwi_urlsResultsCache = _save_url_results(servicesInfo, previousResponsesStore, _urlsResultsCache)
_save_historyBlob(kiwi_urlsResultsCache, previousResponsesStore.forUrl)
# refresh tempResponsesStore for new url
tempResponsesStore.forUrl = currentUrl
tempResponsesStore.services = {}
currentTime = Date.now()
if !urlsResultsCache?
urlsResultsCache = {}
if !urlsResultsCache[currentUrl]?
urlsResultsCache[currentUrl] = {}
# #console.log 'about to check for dispatch query'
# #console.debug urlsResultsCache[currentUrl]
# check on a service-by-service basis (so we don't requery all services just b/c one api/service is down)
for service in servicesInfo
# #console.log 'for service in servicesInfo'
# #console.debug service
if service.active == 'on'
if urlsResultsCache[currentUrl][service.name]?
if (currentTime - urlsResultsCache[currentUrl][service.name].timestamp) > checkForUrlHourInterval * 3600000
dispatchQuery(service, currentUrl, servicesInfo)
else
dispatchQuery(service, currentUrl, servicesInfo)
dispatchQuery = (service_info, currentUrl, servicesInfo) ->
# console.log 'yolo 5 ~ for ' + service_info.name
currentTime = Date.now()
# self imposed rate limiting per api
if !serviceQueryTimestamps[service_info.name]?
serviceQueryTimestamps[service_info.name] = currentTime
else
if (currentTime - serviceQueryTimestamps[service_info.name]) < queryThrottleSeconds * 1000
#wait a couple seconds before querying service
#console.log 'too soon on dispatch, waiting a couple seconds'
setTimeout(->
dispatchQuery(service_info, currentUrl, servicesInfo)
, 2000
)
return 0
else
serviceQueryTimestamps[service_info.name] = currentTime
queryObj = {
url: service_info.queryApi + encodeURIComponent(currentUrl),
onComplete: (queryResult) ->
if queryResult.status == 401
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated4');
setPreppedServiceResults(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
if service_info.name is 'productHunt'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
else if service_info.name is 'reddit'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
else if (queryResult.status == 0 or queryResult.status == 504 or queryResult.status == 503 or
queryResult.status == 502)
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated4');
setPreppedServiceResults(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
else
# console.log 'back with'
# for key, val of queryResult
# console.log key + ' : ' + val
responsePackage =
forUrl: currentUrl
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: queryResult.json
setPreppedServiceResults(responsePackage, servicesInfo)
}
headers = {}
if service_info.name is 'reddit' and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log 'we are trying with oauth!'
#console.debug allItemsInLocalStorage.kiwi_reddit_oauth
queryObj.headers =
'Authorization': "'bearer " + firefoxStorage.storage.kiwi_reddit_oauth.token + "'"
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
else if service_info.name is 'reddit' and !firefoxStorage.storage.kiwi_reddit_oauth?
# console.log 'adfaeaefae'
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated5');
setPreppedServiceResults(responsePackage, servicesInfo)
# if kiwi_userMessages[service_info.name + "Down"]?
# send_kiwi_userMessage(service_info.name + "Down")
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
return 0
# console.log firefoxStorage.storage.kiwi_productHunt_oauth.token
if service_info.name is 'productHunt' and firefoxStorage.storage.kiwi_productHunt_oauth?
# console.log 'trying PH with'
# console.debug allItemsInLocalStorage.kiwi_productHunt_oauth
queryObj.headers =
'Authorization': "Bearer " + firefoxStorage.storage.kiwi_productHunt_oauth.token
'Accept': 'application/json'
'Content-Type': 'application/json'
else if service_info.name is 'productHunt' and !firefoxStorage.storage.kiwi_productHunt_oauth?
# console.log 'asdfasdfasdfdas'
# call out and to a reset / refresh timer thingy
responsePackage = {
forUrl: currentUrl,
servicesInfo: servicesInfo,
serviceName: service_info.name,
queryResult: null
};
# console.log('unauthenticated5');
setPreppedServiceResults(responsePackage, servicesInfo)
# if kiwi_userMessages[service_info.name + "Down"]?
# send_kiwi_userMessage(service_info.name + "Down")
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
return 0
Request(queryObj).get()
dispatchQuery__customSearch = (customSearchQuery, servicesToSearch, service_info, servicesInfo) ->
#console.log 'yolo 5 ~ for CUSTOM ' + service_info.name
#console.debug servicesToSearch
currentTime = Date.now()
# self imposed rate limiting per api
if !serviceQueryTimestamps[service_info.name]?
serviceQueryTimestamps[service_info.name] = currentTime
else
if (currentTime - serviceQueryTimestamps[service_info.name]) < queryThrottleSeconds * 1000
#wait a couple seconds before querying service
#console.log 'too soon on dispatch, waiting a couple seconds'
setTimeout(->
dispatchQuery__customSearch(customSearchQuery, servicesToSearch, service_info, servicesInfo)
, 2000
)
return 0
else
serviceQueryTimestamps[service_info.name] = currentTime
queryUrl = service_info.customSearchApi + encodeURIComponent(customSearchQuery)
if servicesToSearch[service_info.name].customSearchTags? and Object.keys(servicesToSearch[service_info.name].customSearchTags).length > 0
for tagIdentifier, tagObject of servicesToSearch[service_info.name].customSearchTags
queryUrl = queryUrl + service_info.customSearchTags__convention.string + service_info.customSearchTags[tagIdentifier].string
#console.log 'asd;lfkjaewo;ifjae; '
# console.log 'for tagIdentifier, tagObject of servicesToSearch[service_info.name].customSearchTags'
# console.log queryUrl
# tagObject might one day accept special parameters like author name, etc
queryObj = {
url: queryUrl,
onComplete: (queryResult) ->
if queryResult.status == 401
responsePackage = {
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: null
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
};
# console.log('unauthenticated1');
setPreppedServiceResults__customSearch(responsePackage, servicesInfo);
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
if service_info.name is 'productHunt'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forProductHuntRefresh(tryAgainTimestamp, temp__kiwi_productHunt_oauth)
else if service_info.name is 'reddit'
tryAgainTimestamp = currentTime + (1000 * 60 * 2)
setTimeout_forRedditRefresh(tryAgainTimestamp, temp__kiwi_reddit_oauth)
else if (queryResult.status == 0 or queryResult.status == 504 or queryResult.status == 503 or
queryResult.status == 502)
responsePackage = {
servicesInfo: servicesInfo
serviceName: service_info.name
queryResult: null
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
};
# console.log('Fail!1');
if kiwi_userMessages[service_info.name + "Down"]?
send_kiwi_userMessage(service_info.name + "Down")
setPreppedServiceResults__customSearch(responsePackage, servicesInfo);
else
# console.log 'onComplete: (queryResult) ->'
# console.log queryResult.json
responsePackage = {
# forUrl: currentUrl
servicesInfo: servicesInfo
servicesToSearch: servicesToSearch
customSearchQuery: customSearchQuery
serviceName: service_info.name
queryResult: queryResult.json
}
setPreppedServiceResults__customSearch(responsePackage, servicesInfo)
}
headers = {}
if service_info.name is 'reddit' and firefoxStorage.storage.kiwi_reddit_oauth?
#console.log 'we are trying with oauth!'
#console.debug allItemsInLocalStorage.kiwi_reddit_oauth
queryObj.headers =
'Authorization': "'bearer " + firefoxStorage.storage.kiwi_reddit_oauth.token + "'"
'Content-Type': 'application/x-www-form-urlencoded'
'X-Requested-With': 'csrf suck it ' + getRandom(1,10000000) # not that the random # matters
# console.log 'console.log queryObj monkeybutt'
# console.log queryObj
Request(queryObj).get()
# proactively set if all service_PreppedResults are ready.
# will be set with available results if queried by popup.
# the popup should always have enough to render with a properly set popupParcel.
setPreppedServiceResults__customSearch = (responsePackage, servicesInfo) ->
# console.log 'yolo 6'
currentTime = Date.now()
for serviceObj in servicesInfo
if serviceObj.name == responsePackage.serviceName
serviceInfo = serviceObj
# responsePackage =
# servicesInfo: servicesInfo
# serviceName: service_info.name
# queryResult: queryResult
# servicesToSearch: servicesToSearch
# customSearchQuery: customSearchQuery
# kiwi_customSearchResults = {} # stores temporarily so if they close popup, they'll still have results
# maybe it won't clear until new result -- "see last search"
# queryString
# servicesSearchesRequested = responsePackage.servicesToSearch
# servicesSearched
# <serviceName>
# results
# even if there are zero matches returned, that counts as a proper query response
service_PreppedResults = parseResults[responsePackage.serviceName](responsePackage.queryResult, responsePackage.customSearchQuery, serviceInfo, true)
if kiwi_customSearchResults? and kiwi_customSearchResults.queryString? and
kiwi_customSearchResults.queryString == responsePackage.customSearchQuery
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName] = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName].results = service_PreppedResults
else
kiwi_customSearchResults = {}
kiwi_customSearchResults.queryString = responsePackage.customSearchQuery
kiwi_customSearchResults.servicesSearchesRequested = responsePackage.servicesToSearch
kiwi_customSearchResults.servicesSearched = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName] = {}
kiwi_customSearchResults.servicesSearched[responsePackage.serviceName].results = service_PreppedResults
# console.log 'yolo 6 results service_PreppedResults'
# console.debug service_PreppedResults
#console.log 'numberOfActiveServices'
#console.debug returnNumberOfActiveServices(servicesInfo)
numberOfActiveServices = Object.keys(responsePackage.servicesToSearch).length
completedQueryServicesArray = []
#number of completed responses
if kiwi_customSearchResults.queryString == responsePackage.customSearchQuery
for serviceName, service of kiwi_customSearchResults.servicesSearched
completedQueryServicesArray.push(serviceName)
completedQueryServicesArray = _.uniq(completedQueryServicesArray)
#console.log 'completedQueryServicesArray.length '
#console.log completedQueryServicesArray.length
if completedQueryServicesArray.length is numberOfActiveServices and numberOfActiveServices != 0
# NO LONGER STORING URL CACHE IN LOCALSTORAGE - BECAUSE : INFORMATION LEAKAGE / BROKEN EXTENSION SECURITY MODEL
# get a fresh copy of urls results and reset with updated info
# chrome.storage.local.get(null, (allItemsInLocalStorage) ->
# #console.log 'trying to save all'
# if !allItemsInLocalStorage['kiwi_urlsResultsCache']?
# allItemsInLocalStorage['kiwi_urlsResultsCache'] = {}
# console.log 'yolo 6 _save_ results(servicesInfo, tempRes -- for ' + serviceInfo.name
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
else
_set_popupParcel({}, tabUrl, true)
# else
# #console.log 'yolo 6 not finished ' + serviceInfo.name
# _set_popupParcel(tempResponsesStore.services, responsePackage.forUrl, false)
_set_popupParcel = (setWith_urlResults = {}, forUrl, sendPopupParcel, renderView = null, oldUrl = false) ->
# console.log 'monkey butt _set_popupParcel = (setWith_urlResults, forUrl, sendPopupParcel, '
#console.log 'trying to set popupParcel, forUrl tabUrl' + forUrl + tabUrl
# tabUrl
if setWith_urlResults != {}
if forUrl != tabUrl
#console.log "_set_popupParcel request for old url"
return false
setObj_popupParcel = {}
setObj_popupParcel.forUrl = tabUrl
if !firefoxStorage.storage['kiwi_userPreferences']?
setObj_popupParcel.kiwi_userPreferences = defaultUserPreferences
else
setObj_popupParcel.kiwi_userPreferences = firefoxStorage.storage['kiwi_userPreferences']
if !firefoxStorage.storage['kiwi_servicesInfo']?
setObj_popupParcel.kiwi_servicesInfo = defaultServicesInfo
else
setObj_popupParcel.kiwi_servicesInfo = firefoxStorage.storage['kiwi_servicesInfo']
if renderView != null
setObj_popupParcel.view = renderView
if !firefoxStorage.storage['kiwi_alerts']?
setObj_popupParcel.kiwi_alerts = []
else
setObj_popupParcel.kiwi_alerts = firefoxStorage.storage['kiwi_alerts']
setObj_popupParcel.kiwi_customSearchResults = kiwi_customSearchResults
if !setWith_urlResults?
#console.log '_set_popupParcel called with undefined responses (not supposed to happen, ever)'
return 0
else
setObj_popupParcel.allPreppedResults = setWith_urlResults
if tabUrl == forUrl
setObj_popupParcel.tabInfo = {}
setObj_popupParcel.tabInfo.tabUrl = tabUrl
setObj_popupParcel.tabInfo.tabTitle = tabTitleObject.tabTitle
else
setObj_popupParcel.tabInfo = null
setObj_popupParcel.urlBlocked = false
isUrlBlocked = is_url_blocked(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true
setObj_popupParcel.urlBlocked = true
if oldUrl is true
setObj_popupParcel.oldUrl = true
else
setObj_popupParcel.oldUrl = false
setObj_popupParcel.kiwi_userMessages = []
for messageName, messageObj of kiwi_userMessages
for sentInstance in messageObj.sentAndAcknowledgedInstanceObjects
if sentInstance.userAcknowledged is null
setObj_popupParcel.kiwi_userMessages.push messageObj
popupParcel = setObj_popupParcel
if sendPopupParcel
parcel = {}
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = setObj_popupParcel
sendParcel(parcel)
setPreppedServiceResults = (responsePackage, servicesInfo) ->
currentTime = Date.now()
# if tabUrl == responsePackage.forUrl # if false, then do nothing (user's probably switched to new tab)
for serviceObj in servicesInfo
if serviceObj.name == responsePackage.serviceName
serviceInfo = serviceObj
# serviceInfo = servicesInfo[responsePackage.serviceName]
# even if there are zero matches returned, that counts as a proper query response
service_PreppedResults = parseResults[responsePackage.serviceName](responsePackage.queryResult, tabUrl, serviceInfo)
if !tempResponsesStore.services?
tempResponsesStore = {}
tempResponsesStore.services = {}
tempResponsesStore.services[responsePackage.serviceName] =
timestamp: currentTime
service_PreppedResults: service_PreppedResults
forUrl: tabUrl
#console.log 'yolo 6 results service_PreppedResults'
#console.debug service_PreppedResults
#console.log 'numberOfActiveServices'
#console.debug returnNumberOfActiveServices(servicesInfo)
numberOfActiveServices = returnNumberOfActiveServices(servicesInfo)
completedQueryServicesArray = []
#number of completed responses
if tempResponsesStore.forUrl == tabUrl
for serviceName, service of tempResponsesStore.services
completedQueryServicesArray.push(serviceName)
if kiwi_urlsResultsCache[tabUrl]?
for serviceName, service of kiwi_urlsResultsCache[tabUrl]
completedQueryServicesArray.push(serviceName)
completedQueryServicesArray = _.uniq(completedQueryServicesArray)
if completedQueryServicesArray.length is numberOfActiveServices and numberOfActiveServices != 0
# NO LONGER STORING URL CACHE IN LOCALSTORAGE - BECAUSE 1.) INFORMATION LEAKAGE, 2.) SLOWER
# get a fresh copy of urls results and reset with updated info
# chrome.storage.local.get(null, (allItemsInLocalStorage) ->
# #console.log 'trying to save all'
# if !allItemsInLocalStorage['kiwi_urlsResultsCache']?
# allItemsInLocalStorage['kiwi_urlsResultsCache'] = {}
#console.log 'yolo 6 _save_url_results(servicesInfo, tempRes -- for ' + serviceInfo.name
kiwi_urlsResultsCache = _save_url_results(servicesInfo, tempResponsesStore, kiwi_urlsResultsCache)
_save_historyBlob(kiwi_urlsResultsCache, tabUrl)
_set_popupParcel(kiwi_urlsResultsCache[tabUrl], tabUrl, true)
refreshBadge(servicesInfo, kiwi_urlsResultsCache[tabUrl])
else
#console.log 'yolo 6 not finished ' + serviceInfo.name
_set_popupParcel(tempResponsesStore.services, tabUrl, false)
refreshBadge(servicesInfo, tempResponsesStore.services)
#returns an array of 'preppedResults' for url - just the keys we care about from the query-response
parseResults =
productHunt: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
# console.log 'resultsObj'
# console.log 'for: ' + searchQueryString
# console.debug resultsObj
# console.log 'customSearchBool ' + customSearchBool
# console.log resultsObj.posts
matchedListings = [];
if ( resultsObj == null )
return matchedListings;
if customSearchBool is false # so, normal URL-based queries
# created_at: "2014-08-18T06:40:47.000-07:00"
# discussion_url: "http://www.producthunt.com/tech/product-hunt-api-beta"
# comments_count: 13
# votes_count: 514
# name: "Product Hunt API (beta)"
# featured: true
# id: 6970
# maker_inside: true
# tagline: "Make stuff with us. Signup for early access to the PH API :)"
# user:
# headline: "Tech at Product Hunt 💃"
# profile_url: "http://www.producthunt.com/@andreasklinger"
# name: "PI:NAME:<NAME>END_PI"
# username: "andreasklinger"
# website_url: "http://klinger.io"
if resultsObj.posts? and _.isArray(resultsObj.posts) is true
for post in resultsObj.posts
listingKeys = [
'created_at','discussion_url','comments_count','redirect_url','votes_count','name',
'featured','id','user','screenshot_url','tagline','maker_inside','makers'
]
preppedResult = _.pick(post, listingKeys)
preppedResult.kiwi_created_at = Date.parse(preppedResult.created_at)
preppedResult.kiwi_discussion_url = preppedResult.discussion_url
if preppedResult.user? and preppedResult.user.name?
preppedResult.kiwi_author_name = preppedResult.user.name.trim()
else
preppedResult.kiwi_author_name = ""
if preppedResult.user? and preppedResult.user.username?
preppedResult.kiwi_author_username = preppedResult.user.username
else
preppedResult.kiwi_author_username = ""
if preppedResult.user? and preppedResult.user.headline?
preppedResult.kiwi_author_headline = preppedResult.user.headline.trim()
else
preppedResult.kiwi_author_headline = ""
preppedResult.kiwi_makers = []
for maker, index in post.makers
makerObj = {}
makerObj.headline = maker.headline
makerObj.name = maker.name
makerObj.username = maker.username
makerObj.profile_url = maker.profile_url
makerObj.website_url = maker.website_url
preppedResult.kiwi_makers.push makerObj
preppedResult.kiwi_exact_match = true # PH won't return fuzzy matches
preppedResult.kiwi_score = preppedResult.votes_count
preppedResult.kiwi_num_comments = preppedResult.comments_count
preppedResult.kiwi_permaId = preppedResult.permalink
matchedListings.push preppedResult
else # custom string queries
# comment_count
# vote_count
# name
# url #
# tagline
# category
# tech
# product_makers
# headline
# name
# username
# is_maker
# console.log ' else # custom string queries ' + _.isArray(resultsObj) #
if resultsObj? and _.isArray(resultsObj)
# console.log ' yoyoyoy1 '
for searchMatch in resultsObj
listingKeys = [
'author'
'url',
'tagline',
'product_makers'
'comment_count',
'vote_count',
'name',
'id',
'user',
'screenshot_url',
]
preppedResult = _.pick(searchMatch, listingKeys)
preppedResult.kiwi_created_at = null # algolia doesn't provide created at value :<
preppedResult.kiwi_discussion_url = "http://www.producthunt.com/" + preppedResult.url
if preppedResult.author? and preppedResult.author.name?
preppedResult.kiwi_author_name = preppedResult.author.name.trim()
else
preppedResult.kiwi_author_name = ""
if preppedResult.author? and preppedResult.author.username?
preppedResult.kiwi_author_username = preppedResult.author.username
else
preppedResult.kiwi_author_username = ""
if preppedResult.author? and preppedResult.author.headline?
preppedResult.kiwi_author_headline = preppedResult.author.headline.trim()
else
preppedResult.kiwi_author_headline = ""
preppedResult.kiwi_makers = []
for maker, index in searchMatch.product_makers
makerObj = {}
makerObj.headline = maker.headline
makerObj.name = maker.name
makerObj.username = maker.username
makerObj.profile_url = maker.profile_url
makerObj.website_url = maker.website_url
preppedResult.kiwi_makers.push makerObj
preppedResult.kiwi_exact_match = true # PH won't return fuzzy matches
preppedResult.kiwi_score = preppedResult.vote_count
preppedResult.kiwi_num_comments = preppedResult.comment_count
preppedResult.kiwi_permaId = preppedResult.permalink
matchedListings.push preppedResult
return matchedListings
reddit: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
matchedListings = []
if ( resultsObj == null )
return matchedListings
# console.log 'reddit: (resultsObj) ->'
# console.debug resultsObj
# occasionally Reddit will decide to return an array instead of an object, so...
# in response to user's feedback, see: https://news.ycombinator.com/item?id=9994202
forEachQueryObject = (resultsObj, _matchedListings) ->
if resultsObj.kind? and resultsObj.kind == "Listing" and resultsObj.data? and
resultsObj.data.children? and resultsObj.data.children.length > 0
for child in resultsObj.data.children
if child.data? and child.kind? and child.kind == "t3"
listingKeys = ["subreddit",'url',"score",'domain','gilded',"over_18","author","hidden","downs","permalink","created","title","created_utc","ups","num_comments"]
preppedResult = _.pick(child.data, listingKeys)
preppedResult.kiwi_created_at = preppedResult.created_utc * 1000 # to normalize to JS's Date.now() millisecond UTC timestamp
if customSearchBool is false
preppedResult.kiwi_exact_match = _exact_match_url_check(searchQueryString, preppedResult.url)
else
preppedResult.kiwi_exact_match = true
preppedResult.kiwi_score = preppedResult.score
preppedResult.kiwi_permaId = preppedResult.permalink
_matchedListings.push preppedResult
return _matchedListings
if _.isArray(resultsObj)
for result in resultsObj
matchedListings = forEachQueryObject(result, matchedListings)
else
matchedListings = forEachQueryObject(resultsObj, matchedListings)
return matchedListings
hackerNews: (resultsObj, searchQueryString, serviceInfo, customSearchBool = false) ->
matchedListings = []
if ( resultsObj == null )
return matchedListings
#console.log ' hacker news #console.debug resultsObj'
#console.debug resultsObj
# if resultsObj.nbHits? and resultsObj.nbHits > 0 and resultsObj.hits? and resultsObj.hits.length is resultsObj.nbHits
if resultsObj? and resultsObj.hits?
for hit in resultsObj.hits
listingKeys = ["points","num_comments","objectID","author","created_at","title","url","created_at_i"
"story_text","comment_text","story_id","story_title","story_url"
]
preppedResult = _.pick(hit, listingKeys)
preppedResult.kiwi_created_at = preppedResult.created_at_i * 1000 # to normalize to JS's Date.now() millisecond UTC timestamp
if customSearchBool is false
preppedResult.kiwi_exact_match = _exact_match_url_check(searchQueryString, preppedResult.url)
else
preppedResult.kiwi_exact_match = true
preppedResult.kiwi_score = preppedResult.points
preppedResult.kiwi_permaId = preppedResult.objectID
matchedListings.push preppedResult
return matchedListings
_exact_match_url_check = (forUrl, preppedResultUrl) ->
# warning:: one of the worst algo-s i've ever written... please don't use as reference
kiwi_exact_match = false
modifications = [
name: 'trailingSlash'
modify: (tOrF, forUrl) ->
if tOrF is 't'
if forUrl[forUrl.length - 1] != '/'
trailingSlashURL = forUrl + '/'
else
trailingSlashURL = forUrl
return trailingSlashURL
else
if forUrl[forUrl.length - 1] == '/'
noTrailingSlashURL = forUrl.substr(0,forUrl.length - 1)
else
noTrailingSlashURL = forUrl
return noTrailingSlashURL
# if forUrl[forUrl.length - 1] == '/'
# noTrailingSlashURL = forUrl.substr(0,forUrl.length - 1)
existsTest: (forUrl) ->
if forUrl[forUrl.length - 1] == '/'
return 't'
else
return 'f'
,
name: 'www'
modify: (tOrF, forUrl) ->
if tOrF is 't'
protocolSplitUrlArray = forUrl.split('://')
if protocolSplitUrlArray.length > 1
if protocolSplitUrlArray[1].indexOf('www.') != 0
protocolSplitUrlArray[1] = 'www.' + protocolSplitUrlArray[1]
WWWurl = protocolSplitUrlArray.join('://')
else
WWWurl = forUrl
return WWWurl
else
if protocolSplitUrlArray[0].indexOf('www.') != 0
protocolSplitUrlArray[0] = 'www.' + protocolSplitUrlArray[1]
WWWurl = protocolSplitUrlArray.join('://')
else
WWWurl = forUrl
return WWWurl
else
wwwSplitUrlArray = forUrl.split('www.')
if wwwSplitUrlArray.length is 2
noWWWurl = wwwSplitUrlArray.join('')
else if wwwSplitUrlArray.length > 2
noWWWurl = wwwSplitUrlArray.shift()
noWWWurl += wwwSplitUrlArray.shift()
noWWWurl += wwwSplitUrlArray.join('www.')
else
noWWWurl = forUrl
return noWWWurl
existsTest: (forUrl) ->
if forUrl.split('//www.').length > 0
return 't'
else
return 'f'
,
name:'http'
existsTest: (forUrl) ->
if forUrl.indexOf('http://') is 0
return 't'
else
return 'f'
modify: (tOrF, forUrl) ->
if tOrF is 't'
if forUrl.indexOf('https://') == 0
HTTPurl = 'http://' + forUrl.substr(8, forUrl.length - 1)
else
HTTPurl = forUrl
else
if forUrl.indexOf('http://') == 0
HTTPSurl = 'https://' + forUrl.substr(7, forUrl.length - 1)
else
HTTPSurl = forUrl
]
modPermutations = {}
forUrlUnmodded = ''
for mod in modifications
forUrlUnmodded += mod.existsTest(forUrl)
modPermutations[forUrlUnmodded] = forUrl
existStates = ['t','f']
for existState in existStates
for mod, index in modifications
checkArray = []
for m in modifications
checkArray.push existState
forUrl_ = modifications[index].modify(existState, forUrl)
for existState_ in existStates
checkArray[index] = existState_
for mod_, index_ in modifications
if index != index_
for existState__ in existStates
checkArray[index_] = existState__
checkString = checkArray.join('')
if !modPermutations[checkString]?
altUrl = forUrl_
for existState_Char, cSindex in checkString
altUrl = modifications[cSindex].modify(existState_Char, altUrl)
modPermutations[checkString] = altUrl
kiwi_exact_match = false
if preppedResultUrl == forUrl
kiwi_exact_match = true
for modKey, moddedUrl of modPermutations
if preppedResultUrl == moddedUrl
kiwi_exact_match = true
return kiwi_exact_match
refreshBadge = (servicesInfo, resultsObjForCurrentUrl) ->
# #console.log 'yolo 8'
# #console.debug resultsObjForCurrentUrl
# #console.debug servicesInfo
# icon badges typically only have room for 5 characters
currentTime = Date.now()
abbreviationLettersArray = []
for service, index in servicesInfo
# if resultsObjForCurrentUrl[service.name]
if resultsObjForCurrentUrl[service.name]? and resultsObjForCurrentUrl[service.name].service_PreppedResults.length > 0
exactMatch = false
noteworthy = false
for listing in resultsObjForCurrentUrl[service.name].service_PreppedResults
if listing.kiwi_exact_match
exactMatch = true
if listing.num_comments? and listing.num_comments >= service.notableConditions.num_comments
noteworthy = true
break
if (currentTime - listing.kiwi_created_at) < service.notableConditions.hoursSincePosted * 3600000
noteworthy = true
break
if service.updateBadgeOnlyWithExactMatch and exactMatch = false
break
#console.log service.name + ' noteworthy ' + noteworthy
if noteworthy
abbreviationLettersArray.push service.abbreviation
else
abbreviationLettersArray.push service.abbreviation.toLowerCase()
#console.debug abbreviationLettersArray
badgeText = ''
if abbreviationLettersArray.length == 0
if firefoxStorage.storage.kiwi_userPreferences? and firefoxStorage.storage['kiwi_userPreferences'].researchModeOnOff == 'off'
badgeText = ''
else if defaultUserPreferences.researchModeOnOff == 'off'
badgeText = ''
else
badgeText = ''
else
badgeText = abbreviationLettersArray.join(" ")
#console.log 'yolo 8 ' + badgeText
updateBadgeText(badgeText)
periodicCleanup = (tab, initialize_callback) ->
#console.log 'wtf a'
currentTime = Date.now()
if(last_periodicCleanup < (currentTime - CLEANUP_INTERVAL))
last_periodicCleanup = currentTime
#console.log 'wtf b'
# delete any results older than checkForUrlHourInterval
if Object.keys(kiwi_urlsResultsCache).length is 0
#console.log 'wtf ba'
# nothing to (potentially) clean up!
initialize_callback(tab)
else
#console.log 'wtf bb'
# allItemsInLocalStorage.kiwi_urlsResultsCache
cull_kiwi_urlsResultsCache = _.extend {}, kiwi_urlsResultsCache
for url, urlServiceResults of cull_kiwi_urlsResultsCache
for serviceKey, serviceResults of urlServiceResults
if currentTime - serviceResults.timestamp > checkForUrlHourInterval
delete kiwi_urlsResultsCache[url]
if Object.keys(kiwi_urlsResultsCache).length > maxUrlResultsStoredInLocalStorage
# you've been surfing! wow
num_results_to_delete = Object.keys(kiwi_urlsResultsCache).length - maxUrlResultsStoredInLocalStorage
deletedCount = 0
cull_kiwi_urlsResultsCache = _.extend {}, kiwi_urlsResultsCache
for url, urlServiceResults of cull_kiwi_urlsResultsCache
if deleteCount >= num_results_to_delete
break
if url != tab.url
delete kiwi_urlsResultsCache[url]
deletedCount++
# chrome.storage.local.set({'kiwi_urlsResultsCache':kiwi_urlsResultsCache}, ->
initialize_callback(tab)
# )
else
initialize_callback(tab)
else
#console.log 'wtf c'
initialize_callback(tab)
_save_from_popupParcel = (_popupParcel, forUrl, updateToView) ->
formerResearchModeValue = null
formerKiwi_servicesInfo = null
former_autoOffTimerType = null
former_autoOffTimerValue = null
# #console.log '#console.debug popupParcel
# #console.debug _popupParcel'
# #console.debug popupParcel
# #console.debug _popupParcel
if popupParcel? and popupParcel.kiwi_userPreferences? and popupParcel.kiwi_servicesInfo
formerResearchModeValue = popupParcel.kiwi_userPreferences.researchModeOnOff
formerKiwi_servicesInfo = popupParcel.kiwi_servicesInfo
former_autoOffTimerType = popupParcel.kiwi_userPreferences.autoOffTimerType
former_autoOffTimerValue = popupParcel.kiwi_userPreferences.autoOffTimerValue
popupParcel = {}
# #console.log ' asdfasdfasd formerKiwi_autoOffTimerType'
# #console.log former_autoOffTimerType
# #console.log _popupParcel.kiwi_userPreferences.autoOffTimerType
# #console.log ' a;woeifjaw;ef formerKiwi_autoOffTimerValue'
# #console.log former_autoOffTimerValue
# #console.log _popupParcel.kiwi_userPreferences.autoOffTimerValue
if formerResearchModeValue? and formerResearchModeValue == 'off' and
_popupParcel.kiwi_userPreferences? and _popupParcel.kiwi_userPreferences.researchModeOnOff == 'on' or
(former_autoOffTimerType != _popupParcel.kiwi_userPreferences.autoOffTimerType or
former_autoOffTimerValue != _popupParcel.kiwi_userPreferences.autoOffTimerValue)
resetTimerBool = true
else
resetTimerBool = false
_autoOffAtUTCmilliTimestamp = setAutoOffTimer(resetTimerBool, _popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp,
_popupParcel.kiwi_userPreferences.autoOffTimerValue, _popupParcel.kiwi_userPreferences.autoOffTimerType,
_popupParcel.kiwi_userPreferences.researchModeOnOff)
_popupParcel.kiwi_userPreferences.autoOffAtUTCmilliTimestamp = _autoOffAtUTCmilliTimestamp
firefoxStorage.storage.kiwi_userPreferences = _popupParcel.kiwi_userPreferences
firefoxStorage.storage.kiwi_servicesInfo = _popupParcel.kiwi_servicesInfo
if updateToView?
parcel = {}
_popupParcel['view'] = updateToView
popupParcel = _popupParcel
parcel.msg = 'kiwiPP_popupParcel_ready'
parcel.forUrl = tabUrl
parcel.popupParcel = _popupParcel
sendParcel(parcel)
#console.log 'in _save_from_popupParcel _popupParcel.forUrl ' + _popupParcel.forUrl
#console.log 'in _save_from_popupParcel tabUrl ' + tabUrl
if _popupParcel.forUrl == tabUrl
if formerResearchModeValue? and formerResearchModeValue == 'off' and
_popupParcel.kiwi_userPreferences? and _popupParcel.kiwi_userPreferences.researchModeOnOff == 'on'
initIfNewURL(true); return 0
else if formerKiwi_servicesInfo?
# so if user turns on a service and saves - it will immediately begin new query
formerActiveServicesList = _.pluck(formerKiwi_servicesInfo, 'active')
newActiveServicesList = _.pluck(_popupParcel.kiwi_servicesInfo, 'active')
#console.log 'formerActiveServicesList = _.pluck(formerKiwi_servicesInfo)'
#console.debug formerActiveServicesList
#console.log 'newActiveServicesList = _.pluck(_popupParcel.kiwi_servicesInfo)'
#console.debug newActiveServicesList
if !_.isEqual(formerActiveServicesList, newActiveServicesList)
initIfNewURL(true); return 0
else
refreshBadge(_popupParcel.kiwi_servicesInfo, _popupParcel.allPreppedResults); return 0
else
refreshBadge(_popupParcel.kiwi_servicesInfo, _popupParcel.allPreppedResults); return 0
setAutoOffTimer = (resetTimerBool, autoOffAtUTCmilliTimestamp, autoOffTimerValue, autoOffTimerType, researchModeOnOff) ->
#console.log 'trying setAutoOffTimer 43234'
if resetTimerBool and kiwi_autoOffClearInterval?
#console.log 'clearing timout'
clearTimeout(kiwi_autoOffClearInterval)
kiwi_autoOffClearInterval = null
currentTime = Date.now()
new_autoOffAtUTCmilliTimestamp = null
if researchModeOnOff == 'on'
if autoOffAtUTCmilliTimestamp == null || resetTimerBool
if autoOffTimerType == '20'
new_autoOffAtUTCmilliTimestamp = currentTime + 20 * 60 * 1000
else if autoOffTimerType == '60'
new_autoOffAtUTCmilliTimestamp = currentTime + 60 * 60 * 1000
else if autoOffTimerType == 'always'
new_autoOffAtUTCmilliTimestamp = null
else if autoOffTimerType == 'custom'
new_autoOffAtUTCmilliTimestamp = currentTime + parseInt(autoOffTimerValue) * 60 * 1000
#console.log 'setting custom new_autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
else
new_autoOffAtUTCmilliTimestamp = autoOffAtUTCmilliTimestamp
if !kiwi_autoOffClearInterval? and autoOffAtUTCmilliTimestamp > currentTime
#console.log 'resetting timer timeout'
kiwi_autoOffClearInterval = setTimeout( ->
turnResearchModeOff()
, new_autoOffAtUTCmilliTimestamp - currentTime )
#console.log ' setting 123 autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
return new_autoOffAtUTCmilliTimestamp
else
# it's already off - no need for timer
new_autoOffAtUTCmilliTimestamp = null
#console.log 'researchModeOnOff is off - resetting autoOff timestamp and clearInterval'
if kiwi_autoOffClearInterval?
clearTimeout(kiwi_autoOffClearInterval)
kiwi_autoOffClearInterval = null
#console.log ' setting 000 autoOffAtUTCmilliTimestamp ' + new_autoOffAtUTCmilliTimestamp
if new_autoOffAtUTCmilliTimestamp != null
#console.log 'setting timer timeout'
kiwi_autoOffClearInterval = setTimeout( ->
turnResearchModeOff()
, new_autoOffAtUTCmilliTimestamp - currentTime )
return new_autoOffAtUTCmilliTimestamp
turnResearchModeOff = ->
#console.log 'turning off research mode - in turnResearchModeOff'
# chrome.storage.sync.get(null, (allItemsInSyncedStorage) -> )
if kiwi_urlsResultsCache[tabUrl]?
urlResults = kiwi_urlsResultsCache[tabUrl]
else
urlResults = {}
if firefoxStorage.storage.kiwi_userPreferences?
firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff = 'off'
firefoxStorage.storage['kiwi_userPreferences'] = firefoxStorage.storage.kiwi_userPreferences
_set_popupParcel(urlResults, tabUrl, true)
if firefoxStorage.storage.kiwi_servicesInfo?
refreshBadge(firefoxStorage.storage.kiwi_servicesInfo, urlResults)
else
defaultUserPreferences.researchModeOnOff = 'off'
firefoxStorage.storage['kiwi_userPreferences'] = defaultUserPreferences
_set_popupParcel(urlResults, tabUrl, true)
if firefoxStorage.storage.kiwi_servicesInfo?
refreshBadge(firefoxStorage.storage.kiwi_servicesInfo, urlResults)
autoOffTimerExpired_orResearchModeOff_withoutURLoverride = (currentTime, overrideResearchModeOff, tabUrl, kiwi_urlsResultsCache) ->
if firefoxStorage.storage.kiwi_userPreferences?
if firefoxStorage.storage.kiwi_userPreferences.autoOffAtUTCmilliTimestamp?
if currentTime > firefoxStorage.storage.kiwi_userPreferences.autoOffAtUTCmilliTimestamp
#console.log 'timer is past due - turning off - in initifnewurl'
firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff = 'off'
if firefoxStorage.storage.kiwi_userPreferences.researchModeOnOff is 'off' and overrideResearchModeOff == false
updateBadgeText('') # off
return true
return false
proceedWithPreInitCheck = (overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen) ->
if firefoxStorage.storage['kiwi_userPreferences']? and overrideResearchModeOff is false
# overrideResearchModeOff = is_url_whitelisted(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_whitelists, tabUrl)
isUrlWhitelistedBool = is_url_whitelisted(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_whitelists, tabUrl)
# provided that the user isn't specifically researching a URL, if it's whitelisted, then that acts as override
overrideResearchModeOff = isUrlWhitelistedBool
if autoOffTimerExpired_orResearchModeOff_withoutURLoverride(currentTime, overrideResearchModeOff, tabUrl, kiwi_urlsResultsCache) is true
# show cached responses, if present
#console.log 'if tabUrl == tempResponsesStore.forUrl'
#console.log tabUrl
#console.log tempResponsesStore.forUrl
if kiwi_urlsResultsCache[tabUrl]?
_set_popupParcel(kiwi_urlsResultsCache[tabUrl],tabUrl,false);
if firefoxStorage.storage['kiwi_servicesInfo']?
refreshBadge(firefoxStorage.storage['kiwi_servicesInfo'], kiwi_urlsResultsCache[tabUrl])
else
_set_popupParcel({},tabUrl,true);
else
periodicCleanup(tabUrl, (tabUrl) ->
#console.log 'in initialize callback'
if !firefoxStorage.storage['kiwi_userPreferences']?
# defaultUserPreferences
#console.log "#console.debug allItemsInSyncedStorage['kiwi_userPreferences']"
#console.debug allItemsInSyncedStorage['kiwi_userPreferences']
_autoOffAtUTCmilliTimestamp = setAutoOffTimer(false, defaultUserPreferences.autoOffAtUTCmilliTimestamp,
defaultUserPreferences.autoOffTimerValue, defaultUserPreferences.autoOffTimerType, defaultUserPreferences.researchModeOnOff)
defaultUserPreferences.autoOffAtUTCmilliTimestamp = _autoOffAtUTCmilliTimestamp
# setObj =
# kiwi_servicesInfo: defaultServicesInfo
# kiwi_userPreferences: defaultUserPreferences
firefoxStorage.storage.kiwi_servicesInfo = defaultServicesInfo
firefoxStorage.storage.kiwi_userPreferences = defaultUserPreferences
# chrome.storage.sync.set(setObj, -> )
isUrlBlocked = is_url_blocked(defaultUserPreferences.urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true and overrideResearchModeOff == false
# user is not interested in results for this url
updateBadgeText('block')
#console.log '# user is not interested in results for this url: ' + tabUrl
_set_popupParcel({}, tabUrl, true) # trying to send, because options page
return 0 # we return before initializing script
initialize(tabUrl)
else
#console.log "allItemsInSyncedStorage['kiwi_userPreferences'].urlSubstring_blacklists"
#console.debug allItemsInSyncedStorage['kiwi_userPreferences'].urlSubstring_blacklists
isUrlBlocked = is_url_blocked(firefoxStorage.storage['kiwi_userPreferences'].urlSubstring_blacklists, tabUrl)
if isUrlBlocked == true and overrideResearchModeOff == false
# user is not interested in results for this url
updateBadgeText('block')
#console.log '# user is not interested in results for this url: ' + tabUrl
_set_popupParcel({}, tabUrl, true) # trying to send, because options page
return 0 # we return/cease before initializing script
initialize(tabUrl)
)
checkForNewDefaultUserPreferenceAttributes_thenProceedWithInitCheck = (overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen) ->
# ^^ checks if newly added default user preference attributes exist (so new features don't break current installs)
setObj = {}
newUserPrefsAttribute = false
newServicesInfoAttribute = false
newServicesInfo = []
newUserPreferences = {}
if firefoxStorage.storage['kiwi_userPreferences']?
newUserPreferences = _.extend {}, firefoxStorage.storage['kiwi_userPreferences']
for keyName, value of defaultUserPreferences
if typeof firefoxStorage.storage['kiwi_userPreferences'][keyName] is 'undefined'
# console.log 'the following is a new keyName '
# console.log keyName
newUserPrefsAttribute = true
newUserPreferences[keyName] = value
if firefoxStorage.storage['kiwi_servicesInfo']?
# needs to handle entirely new services as well as simplly new attributes
newServicesInfo = _.extend [], firefoxStorage.storage['kiwi_servicesInfo']
for service_default, index in defaultServicesInfo
matchingService = _.find(firefoxStorage.storage['kiwi_servicesInfo'], (service_info) ->
if service_info.name is service_default.name
return true
else
return false
)
if matchingService?
newServiceObj = _.extend {}, matchingService
for keyName, value of service_default
# console.log keyName
if typeof matchingService[keyName] is 'undefined'
newServicesInfoAttribute = true
newServiceObj[keyName] = value
indexOfServiceToReplace = _.indexOf(newServicesInfo, matchingService)
newServicesInfo[indexOfServiceToReplace] = newServiceObj
else
# supports adding an entirely new service
newServicesInfoAttribute = true
# users that don't download with a specific service will need to opt-in to the new one
if service_default.active?
service_default.active = 'off'
newServicesInfo.push service_default
if newUserPrefsAttribute or newServicesInfoAttribute
if newUserPrefsAttribute
setObj['kiwi_userPreferences'] = newUserPreferences
if newServicesInfoAttribute
setObj['kiwi_servicesInfo'] = newServicesInfo
# this reminds me of the frog DNA injection from jurassic park
if newUserPrefsAttribute
firefoxStorage.storage['kiwi_userPreferences'] = newUserPreferences
if newServicesInfoAttribute
firefoxStorage.storage['kiwi_servicesInfo'] = newServicesInfo
# console.log 'console.debug allItemsInSyncedStorage'
# console.debug allItemsInSyncedStorage
proceedWithPreInitCheck(overrideSameURLCheck_popupOpen, overrideResearchModeOff,
sameURLCheck, tabUrl, currentTime, popupOpen)
else
proceedWithPreInitCheck(overrideSameURLCheck_popupOpen, overrideResearchModeOff,
sameURLCheck, tabUrl, currentTime, popupOpen)
# a wise coder once told me "try to keep functions to 10 lines or less." yea, welcome to initIfNewURL! let me find my cowboy hat :D
initIfNewURL = (overrideSameURLCheck_popupOpen = false, overrideResearchModeOff = false) ->
# console.log 'yoyoyo'
# if firefoxStorage.storage['kiwi_userPreferences']?
# console.log 'nothing 0 '
# console.log firefoxStorage.storage['kiwi_userPreferences'].researchModeOnOff
# # console.debug firefoxStorage.storage['kiwi_userPreferences']
# else
# console.log 'nothing'
if typeof overrideSameURLCheck_popupOpen != 'boolean'
# ^^ because the Chrome api tab listening functions were exec-ing callback with an integer argument
# that has since been negated by nesting the callback, but why not leave the check here?
overrideSameURLCheck_popupOpen = false
# #console.log 'wtf 1 kiwi_urlsResultsCache ' + overrideSameURLCheck_popupOpen
if overrideSameURLCheck_popupOpen # for when a user turns researchModeOnOff "on" or refreshes results from popup
popupOpen = true
else
popupOpen = false
currentTime = Date.now()
# chrome.tabs.getSelected(null,(tab) ->
# chrome.tabs.query({ currentWindow: true, active: true }, (tabs) ->
if tabs.activeTab.url?
# console.log 'if tabs.activeTab.url?'
# console.log tabs.activeTab.url
# console.log tabs.activeTab
if tabs.activeTab.url.indexOf('chrome-devtools://') != 0
tabUrl = tabs.activeTab.url
# console.log 'tabUrl = tabs.activeTab.url'
# console.log tabUrl
# we care about the title, because it's the best way to search google news
if tabs.activeTab.readyState == 'complete'
title = tabs.activeTab.title
# a little custom title formatting for sites that begin their tab titles with "(<number>)" like twitter.com
if title.length > 3 and title[0] == "(" and isNaN(title[1]) == false and title.indexOf(')') != -1 and
title.indexOf(')') != title.length - 1
title = title.slice(title.indexOf(')') + 1 , title.length).trim()
tabTitleObject =
tabTitle: title
forUrl: tabUrl
else
tabTitleObject =
tabTitle: null
forUrl: tabUrl
else
_set_popupParcel({}, tabUrl, false)
#console.log 'chrome-devtools:// has been the only url visited so far'
return 0
tabUrl_hash = toSHA512(tabUrl)
sameURLCheck = true
# firefox's toSHA512 function usually returned a string ending in "=="
tabUrl_hash = tabUrl_hash.substring(0, tabUrl_hash.length - 2);
historyString = reduceHashByHalf(tabUrl_hash)
updateBadgeText('')
if !firefoxStorage.storage.persistentUrlHash?
firefoxStorage.storage.persistentUrlHash = ''
if overrideSameURLCheck_popupOpen == false and firefoxStorage.storage['kiwi_historyBlob']? and
firefoxStorage.storage['kiwi_historyBlob'].indexOf(historyString) != -1 and
(!kiwi_urlsResultsCache? or !kiwi_urlsResultsCache[tabUrl]?)
# console.log ' trying to set as old 123412341241234 '
updateBadgeText('old')
sameURLCheck = true
_set_popupParcel({}, tabUrl, false, null, true)
else if (overrideSameURLCheck_popupOpen == false and !firefoxStorage.storage.persistentUrlHash?) or
firefoxStorage.storage.persistentUrlHash? and firefoxStorage.storage.persistentUrlHash != tabUrl_hash
sameURLCheck = false
else if overrideSameURLCheck_popupOpen == true
sameURLCheck = false
#useful for switching window contexts
# chrome.storage.local.set({'persistentUrlHash': tabUrl_hash}, ->)
firefoxStorage.storage['persistentUrlHash'] = tabUrl_hash
if sameURLCheck == false
updateBadgeText('')
checkForNewDefaultUserPreferenceAttributes_thenProceedWithInitCheck(overrideSameURLCheck_popupOpen,
overrideResearchModeOff, sameURLCheck, tabUrl, currentTime, popupOpen)
tabs.on 'ready', (tab) ->
# console.log('tab is loaded', tab.title, tab.url)
initIfNewURL()
tabs.on('activate', ->
# console.log('active: ' + tabs.activeTab.url);
initIfNewURL()
)
# intial startup
if tabTitleObject == null
initIfNewURL(true)
|
[
{
"context": "esult',\n title: 'The Friendship and Flight of Andy Warhol, Philip Pearlstein, and ...',\n htmlTitle: 'T",
"end": 330,
"score": 0.9892533421516418,
"start": 319,
"tag": "NAME",
"value": "Andy Warhol"
},
{
"context": " title: 'The Friendship and Flight of Andy Warhol, Philip Pearlstein, and ...',\n htmlTitle: 'The Friendship and F",
"end": 349,
"score": 0.9926463961601257,
"start": 332,
"tag": "NAME",
"value": "Philip Pearlstein"
},
{
"context": " htmlTitle: 'The Friendship and Flight of <b>Andy Warhol</b>, Philip Pearlstein, and <b>...</b>',\n li",
"end": 422,
"score": 0.9870905876159668,
"start": 411,
"tag": "NAME",
"value": "Andy Warhol"
},
{
"context": " 'The Friendship and Flight of <b>Andy Warhol</b>, Philip Pearlstein, and <b>...</b>',\n link: 'https://www.artsy.",
"end": 445,
"score": 0.9941650032997131,
"start": 428,
"tag": "NAME",
"value": "Philip Pearlstein"
},
{
"context": "cle',\n display: 'The Friendship and Flight of Andy Warhol, Philip Pearlstein, and ...',\n image_url: 'h",
"end": 1007,
"score": 0.9862430095672607,
"start": 996,
"tag": "NAME",
"value": "Andy Warhol"
},
{
"context": "isplay: 'The Friendship and Flight of Andy Warhol, Philip Pearlstein, and ...',\n image_url: 'https://encrypted-tb",
"end": 1026,
"score": 0.9952437877655029,
"start": 1009,
"tag": "NAME",
"value": "Philip Pearlstein"
},
{
"context": "17, 2015 ... In 1949, two young, aspiring artists, Philip Pearlstein and Andy Warhol, bought \\nbus tickets out of Pitt",
"end": 1385,
"score": 0.9981316924095154,
"start": 1368,
"tag": "NAME",
"value": "Philip Pearlstein"
},
{
"context": "two young, aspiring artists, Philip Pearlstein and Andy Warhol, bought \\nbus tickets out of Pittsburgh. They arr",
"end": 1401,
"score": 0.9976394772529602,
"start": 1390,
"tag": "NAME",
"value": "Andy Warhol"
}
] | mobile/components/search_results/test/template.coffee | craigspaeth/_force-merge | 1 | fs = require 'fs'
jade = require 'jade'
path = require 'path'
fixtures = require '../../../test/helpers/fixtures'
GooogleSearchResult = require '../../../models/google_search_result'
describe 'result.jade', ->
before ->
@fixture = {
kind: 'customsearch#result',
title: 'The Friendship and Flight of Andy Warhol, Philip Pearlstein, and ...',
htmlTitle: 'The Friendship and Flight of <b>Andy Warhol</b>, Philip Pearlstein, and <b>...</b>',
link: 'https://www.artsy.net/article/artsy-editorial-from-pittsburgh-to-promise-the-friendship-and-flight',
displayLink: 'www.artsy.net',
snippet: '',
cacheId: '8b2RC8ZkxYUJ',
formattedUrl: 'https://www.artsy.net/.../artsy-editorial-from-pittsburgh-to-promise-the- friendship-and-flight',
htmlFormattedUrl: 'https://www.artsy.net/.../artsy-editorial-from-pittsburgh-to-promise-the- friendship-and-flight',
pagemap: { },
ogType: 'article',
display: 'The Friendship and Flight of Andy Warhol, Philip Pearlstein, and ...',
image_url: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSlZL9Q-fcFKGOvBsHCfxI6JpcJr5-hUMACOlhD-1j2l-rOahjx-ZUKmAg',
display_model: 'article',
location: '/article/artsy-editorial-from-pittsburgh-to-promise-the-friendship-and-flight',
about: 'Jun 17, 2015 ... In 1949, two young, aspiring artists, Philip Pearlstein and Andy Warhol, bought \nbus tickets out of Pittsburgh. They arrived in New York with a few ...'
}
filename = path.resolve __dirname, "../result.jade"
@render = jade.compile(fs.readFileSync(filename), { filename: filename })
it 'doesnt allow unsafe xss-ey html', ->
@fixture.about = '<script>alert(1)</script>'
@render(result: new GooogleSearchResult @fixture).should.not
.containEql '<script>'
| 76914 | fs = require 'fs'
jade = require 'jade'
path = require 'path'
fixtures = require '../../../test/helpers/fixtures'
GooogleSearchResult = require '../../../models/google_search_result'
describe 'result.jade', ->
before ->
@fixture = {
kind: 'customsearch#result',
title: 'The Friendship and Flight of <NAME>, <NAME>, and ...',
htmlTitle: 'The Friendship and Flight of <b><NAME></b>, <NAME>, and <b>...</b>',
link: 'https://www.artsy.net/article/artsy-editorial-from-pittsburgh-to-promise-the-friendship-and-flight',
displayLink: 'www.artsy.net',
snippet: '',
cacheId: '8b2RC8ZkxYUJ',
formattedUrl: 'https://www.artsy.net/.../artsy-editorial-from-pittsburgh-to-promise-the- friendship-and-flight',
htmlFormattedUrl: 'https://www.artsy.net/.../artsy-editorial-from-pittsburgh-to-promise-the- friendship-and-flight',
pagemap: { },
ogType: 'article',
display: 'The Friendship and Flight of <NAME>, <NAME>, and ...',
image_url: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSlZL9Q-fcFKGOvBsHCfxI6JpcJr5-hUMACOlhD-1j2l-rOahjx-ZUKmAg',
display_model: 'article',
location: '/article/artsy-editorial-from-pittsburgh-to-promise-the-friendship-and-flight',
about: 'Jun 17, 2015 ... In 1949, two young, aspiring artists, <NAME> and <NAME>, bought \nbus tickets out of Pittsburgh. They arrived in New York with a few ...'
}
filename = path.resolve __dirname, "../result.jade"
@render = jade.compile(fs.readFileSync(filename), { filename: filename })
it 'doesnt allow unsafe xss-ey html', ->
@fixture.about = '<script>alert(1)</script>'
@render(result: new GooogleSearchResult @fixture).should.not
.containEql '<script>'
| true | fs = require 'fs'
jade = require 'jade'
path = require 'path'
fixtures = require '../../../test/helpers/fixtures'
GooogleSearchResult = require '../../../models/google_search_result'
describe 'result.jade', ->
before ->
@fixture = {
kind: 'customsearch#result',
title: 'The Friendship and Flight of PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and ...',
htmlTitle: 'The Friendship and Flight of <b>PI:NAME:<NAME>END_PI</b>, PI:NAME:<NAME>END_PI, and <b>...</b>',
link: 'https://www.artsy.net/article/artsy-editorial-from-pittsburgh-to-promise-the-friendship-and-flight',
displayLink: 'www.artsy.net',
snippet: '',
cacheId: '8b2RC8ZkxYUJ',
formattedUrl: 'https://www.artsy.net/.../artsy-editorial-from-pittsburgh-to-promise-the- friendship-and-flight',
htmlFormattedUrl: 'https://www.artsy.net/.../artsy-editorial-from-pittsburgh-to-promise-the- friendship-and-flight',
pagemap: { },
ogType: 'article',
display: 'The Friendship and Flight of PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and ...',
image_url: 'https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSlZL9Q-fcFKGOvBsHCfxI6JpcJr5-hUMACOlhD-1j2l-rOahjx-ZUKmAg',
display_model: 'article',
location: '/article/artsy-editorial-from-pittsburgh-to-promise-the-friendship-and-flight',
about: 'Jun 17, 2015 ... In 1949, two young, aspiring artists, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI, bought \nbus tickets out of Pittsburgh. They arrived in New York with a few ...'
}
filename = path.resolve __dirname, "../result.jade"
@render = jade.compile(fs.readFileSync(filename), { filename: filename })
it 'doesnt allow unsafe xss-ey html', ->
@fixture.about = '<script>alert(1)</script>'
@render(result: new GooogleSearchResult @fixture).should.not
.containEql '<script>'
|
[
{
"context": "^$]+$\"\n overwrite_wd: true\n }\n {\n key: \"bt\"\n config:\n commands: []\n }\n]\n",
"end": 148,
"score": 0.7459266781806946,
"start": 146,
"tag": "KEY",
"value": "bt"
}
] | .build-tools.cson | exCSS/configurator | 0 | providers: [
{
key: "makefile"
config:
file: "Makefile"
regex: "^[A-Za-z][^$]+$"
overwrite_wd: true
}
{
key: "bt"
config:
commands: []
}
]
| 163849 | providers: [
{
key: "makefile"
config:
file: "Makefile"
regex: "^[A-Za-z][^$]+$"
overwrite_wd: true
}
{
key: "<KEY>"
config:
commands: []
}
]
| true | providers: [
{
key: "makefile"
config:
file: "Makefile"
regex: "^[A-Za-z][^$]+$"
overwrite_wd: true
}
{
key: "PI:KEY:<KEY>END_PI"
config:
commands: []
}
]
|
[
{
"context": "{\n\t\"$schema\": \"https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json\",\n\t\"name\": \"sca",
"end": 59,
"score": 0.9996702671051025,
"start": 49,
"tag": "USERNAME",
"value": "martinring"
},
{
"context": "ing/tmlanguage/master/tmlanguage.json\",\n\t\"name\": \"scarpet\",\n\t\"patterns\": [{\n\t\t\t\"include\": \"#expression",
"end": 108,
"score": 0.482473760843277,
"start": 106,
"tag": "NAME",
"value": "sc"
},
{
"context": "g/tmlanguage/master/tmlanguage.json\",\n\t\"name\": \"scarpet\",\n\t\"patterns\": [{\n\t\t\t\"include\": \"#expression\"\n\t\t}",
"end": 113,
"score": 0.474473237991333,
"start": 108,
"tag": "USERNAME",
"value": "arpet"
}
] | grammars/scarpet.cson | Aras14HD/language-scarpet | 0 | {
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
"name": "scarpet",
"patterns": [{
"include": "#expression"
},
{
"include": "#statements"
}
],
"repository": {
"expression": {
"patterns": [{
"include": "#keywords"
},
{
"include": "#strings"
},
{
"include": "#paren-expression"
}
]
},
"statements": {
"patterns": [{
"include": "#variables"
},
{
"include": "#comments"
}
]
},
"keywords": {
"patterns": [{
"match": "[^\\w]?(if|return|exit|try|call|import|outer|break|continue|for|c_for|while|loop|vars?|undef)[^\\w]",
"captures": {
"1": {
"name": "keyword.control"
}
}
},
{
"match": "[^\\w]?(copy|type|bool|number|str|player)[^\\w]",
"captures": {
"1": {
"name": "support.type"
}
}
},
{
"name": "keyword.operator.next",
"match": "\\;"
},
{
"name": "keyword.operator.definition",
"match": "\\->"
},
{
"name": "keyword.operator.accessor",
"match": "\\:"
},
{
"name": "keyword.operator.matching",
"match": "\\~"
},
{
"name": "keyword.operator.arithmetic",
"match": "\\b(\\+|\\-|\\*\\/)\\b"
},
{
"name": "keyword.operator.comparison",
"match": "(==|\\!=|<|>|<=|>=)"
},
{
"name": "keyword.operator.logical",
"match": "(&&|\\|\\|)"
},
{
"name": "keyword.operator.assignment",
"match": "(=|<>|\\+=)"
},
{
"name": "keyword.operator.negation",
"match": "\\!"
},
{
"name": "keyword.operator.comma",
"match": "\\,"
}
]
},
"variables": {
"patterns": [{
"match": "[^\\w]?(null|true|false)|(pi|euler)[^\\w]",
"captures": {
"1": {
"name": "constant.language"
},
"2": {
"name": "constant.numeric.constant"
}
}
},
{
"name": "constant.numeric",
"patterns": [{
"name": "constant.numeric.exponential",
"match": "\\-?\\d+e\\-?\\d+"
},
{
"name": "constant.numeric.decimal",
"match": "\\-?\\d+(.\\d+)?"
},
{
"name": "constant.numeric.hexadecimal",
"match": "0x\\h+"
}
]
},
{
"match": "(\\w+)(\\([^\\)]*\\))",
"captures": {
"1": {
"name": "entity.name.function"
},
"2": {
"patterns": [{
"include": "#paren-expression"
}]
}
}
},
{
"name": "variable.name",
"match": "(\\w+)"
}
]
},
"comments": {
"name": "comment.line",
"patterns": [{
"name": "comment.line.double-slash",
"match": "\\/\\/.*\\n"
}]
},
"strings": {
"name": "string.quoted",
"patterns": [{
"name": "string.quoted.single",
"begin": "'",
"end": "'",
"patterns": [{
"name": "constant.character.escape.scarpet",
"match": "\\\\."
}]
}]
},
"paren-expression": {
"begin": "\\(",
"end": "\\)",
"beginCaptures": {
"0": {
"name": "punctuation.paren.open"
}
},
"endCaptures": {
"0": {
"name": "punctuation.paren.close"
}
},
"name": "expression.group",
"patterns": [{
"include": "#expression"
},
{
"include": "#statements"
}
]
}
},
"scopeName": "source.sc"
}
| 122307 | {
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
"name": "<NAME>arpet",
"patterns": [{
"include": "#expression"
},
{
"include": "#statements"
}
],
"repository": {
"expression": {
"patterns": [{
"include": "#keywords"
},
{
"include": "#strings"
},
{
"include": "#paren-expression"
}
]
},
"statements": {
"patterns": [{
"include": "#variables"
},
{
"include": "#comments"
}
]
},
"keywords": {
"patterns": [{
"match": "[^\\w]?(if|return|exit|try|call|import|outer|break|continue|for|c_for|while|loop|vars?|undef)[^\\w]",
"captures": {
"1": {
"name": "keyword.control"
}
}
},
{
"match": "[^\\w]?(copy|type|bool|number|str|player)[^\\w]",
"captures": {
"1": {
"name": "support.type"
}
}
},
{
"name": "keyword.operator.next",
"match": "\\;"
},
{
"name": "keyword.operator.definition",
"match": "\\->"
},
{
"name": "keyword.operator.accessor",
"match": "\\:"
},
{
"name": "keyword.operator.matching",
"match": "\\~"
},
{
"name": "keyword.operator.arithmetic",
"match": "\\b(\\+|\\-|\\*\\/)\\b"
},
{
"name": "keyword.operator.comparison",
"match": "(==|\\!=|<|>|<=|>=)"
},
{
"name": "keyword.operator.logical",
"match": "(&&|\\|\\|)"
},
{
"name": "keyword.operator.assignment",
"match": "(=|<>|\\+=)"
},
{
"name": "keyword.operator.negation",
"match": "\\!"
},
{
"name": "keyword.operator.comma",
"match": "\\,"
}
]
},
"variables": {
"patterns": [{
"match": "[^\\w]?(null|true|false)|(pi|euler)[^\\w]",
"captures": {
"1": {
"name": "constant.language"
},
"2": {
"name": "constant.numeric.constant"
}
}
},
{
"name": "constant.numeric",
"patterns": [{
"name": "constant.numeric.exponential",
"match": "\\-?\\d+e\\-?\\d+"
},
{
"name": "constant.numeric.decimal",
"match": "\\-?\\d+(.\\d+)?"
},
{
"name": "constant.numeric.hexadecimal",
"match": "0x\\h+"
}
]
},
{
"match": "(\\w+)(\\([^\\)]*\\))",
"captures": {
"1": {
"name": "entity.name.function"
},
"2": {
"patterns": [{
"include": "#paren-expression"
}]
}
}
},
{
"name": "variable.name",
"match": "(\\w+)"
}
]
},
"comments": {
"name": "comment.line",
"patterns": [{
"name": "comment.line.double-slash",
"match": "\\/\\/.*\\n"
}]
},
"strings": {
"name": "string.quoted",
"patterns": [{
"name": "string.quoted.single",
"begin": "'",
"end": "'",
"patterns": [{
"name": "constant.character.escape.scarpet",
"match": "\\\\."
}]
}]
},
"paren-expression": {
"begin": "\\(",
"end": "\\)",
"beginCaptures": {
"0": {
"name": "punctuation.paren.open"
}
},
"endCaptures": {
"0": {
"name": "punctuation.paren.close"
}
},
"name": "expression.group",
"patterns": [{
"include": "#expression"
},
{
"include": "#statements"
}
]
}
},
"scopeName": "source.sc"
}
| true | {
"$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
"name": "PI:NAME:<NAME>END_PIarpet",
"patterns": [{
"include": "#expression"
},
{
"include": "#statements"
}
],
"repository": {
"expression": {
"patterns": [{
"include": "#keywords"
},
{
"include": "#strings"
},
{
"include": "#paren-expression"
}
]
},
"statements": {
"patterns": [{
"include": "#variables"
},
{
"include": "#comments"
}
]
},
"keywords": {
"patterns": [{
"match": "[^\\w]?(if|return|exit|try|call|import|outer|break|continue|for|c_for|while|loop|vars?|undef)[^\\w]",
"captures": {
"1": {
"name": "keyword.control"
}
}
},
{
"match": "[^\\w]?(copy|type|bool|number|str|player)[^\\w]",
"captures": {
"1": {
"name": "support.type"
}
}
},
{
"name": "keyword.operator.next",
"match": "\\;"
},
{
"name": "keyword.operator.definition",
"match": "\\->"
},
{
"name": "keyword.operator.accessor",
"match": "\\:"
},
{
"name": "keyword.operator.matching",
"match": "\\~"
},
{
"name": "keyword.operator.arithmetic",
"match": "\\b(\\+|\\-|\\*\\/)\\b"
},
{
"name": "keyword.operator.comparison",
"match": "(==|\\!=|<|>|<=|>=)"
},
{
"name": "keyword.operator.logical",
"match": "(&&|\\|\\|)"
},
{
"name": "keyword.operator.assignment",
"match": "(=|<>|\\+=)"
},
{
"name": "keyword.operator.negation",
"match": "\\!"
},
{
"name": "keyword.operator.comma",
"match": "\\,"
}
]
},
"variables": {
"patterns": [{
"match": "[^\\w]?(null|true|false)|(pi|euler)[^\\w]",
"captures": {
"1": {
"name": "constant.language"
},
"2": {
"name": "constant.numeric.constant"
}
}
},
{
"name": "constant.numeric",
"patterns": [{
"name": "constant.numeric.exponential",
"match": "\\-?\\d+e\\-?\\d+"
},
{
"name": "constant.numeric.decimal",
"match": "\\-?\\d+(.\\d+)?"
},
{
"name": "constant.numeric.hexadecimal",
"match": "0x\\h+"
}
]
},
{
"match": "(\\w+)(\\([^\\)]*\\))",
"captures": {
"1": {
"name": "entity.name.function"
},
"2": {
"patterns": [{
"include": "#paren-expression"
}]
}
}
},
{
"name": "variable.name",
"match": "(\\w+)"
}
]
},
"comments": {
"name": "comment.line",
"patterns": [{
"name": "comment.line.double-slash",
"match": "\\/\\/.*\\n"
}]
},
"strings": {
"name": "string.quoted",
"patterns": [{
"name": "string.quoted.single",
"begin": "'",
"end": "'",
"patterns": [{
"name": "constant.character.escape.scarpet",
"match": "\\\\."
}]
}]
},
"paren-expression": {
"begin": "\\(",
"end": "\\)",
"beginCaptures": {
"0": {
"name": "punctuation.paren.open"
}
},
"endCaptures": {
"0": {
"name": "punctuation.paren.close"
}
},
"name": "expression.group",
"patterns": [{
"include": "#expression"
},
{
"include": "#statements"
}
]
}
},
"scopeName": "source.sc"
}
|
[
{
"context": "utton \"Lokaal (alt)\", !->\n\t\t\t\tApp.openUrl 'http://192.168.178.11'\n\t\t\tUi.button \"Extern\", !->\n\t\t\t\tApp.openUrl 'http",
"end": 268,
"score": 0.9997238516807556,
"start": 254,
"tag": "IP_ADDRESS",
"value": "192.168.178.11"
},
{
"context": "\t\tUi.button \"Extern\", !->\n\t\t\t\tApp.openUrl 'http://83.84.36.201'\n",
"end": 333,
"score": 0.9996089935302734,
"start": 321,
"tag": "IP_ADDRESS",
"value": "83.84.36.201"
}
] | client.coffee | erwinrietveld/pinohappening | 0 |
exports.render = !->
# your client code here
Ui.card !->
Dom.h2 "Links naar PINO"
Dom.text "Alleen maar liefde."
Dom.div !->
Ui.button "Lokaal", !->
App.openUrl 'http://pino.local'
Ui.button "Lokaal (alt)", !->
App.openUrl 'http://192.168.178.11'
Ui.button "Extern", !->
App.openUrl 'http://83.84.36.201'
| 139669 |
exports.render = !->
# your client code here
Ui.card !->
Dom.h2 "Links naar PINO"
Dom.text "Alleen maar liefde."
Dom.div !->
Ui.button "Lokaal", !->
App.openUrl 'http://pino.local'
Ui.button "Lokaal (alt)", !->
App.openUrl 'http://192.168.178.11'
Ui.button "Extern", !->
App.openUrl 'http://192.168.3.11'
| true |
exports.render = !->
# your client code here
Ui.card !->
Dom.h2 "Links naar PINO"
Dom.text "Alleen maar liefde."
Dom.div !->
Ui.button "Lokaal", !->
App.openUrl 'http://pino.local'
Ui.button "Lokaal (alt)", !->
App.openUrl 'http://192.168.178.11'
Ui.button "Extern", !->
App.openUrl 'http://PI:IP_ADDRESS:192.168.3.11END_PI'
|
[
{
"context": "odels.user\n .findOne()\n .where username: username\n .exec (err, user) ->\n if err then re",
"end": 305,
"score": 0.891613781452179,
"start": 297,
"tag": "USERNAME",
"value": "username"
},
{
"context": "n callback null, false\n if password != user.password then callback null, false\n else callback n",
"end": 459,
"score": 0.7382757067680359,
"start": 451,
"tag": "PASSWORD",
"value": "password"
}
] | src/modules/controllers/auth.controller.coffee | Soundscape/sublime-oauth2 | 0 | passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy
BearerStrategy = require('passport-http-bearer').Strategy
module.exports = (ctx) ->
passport.use new BasicStrategy (username, password, callback) ->
ctx.models.user
.findOne()
.where username: username
.exec (err, user) ->
if err then return callback err
if !user then return callback null, false
if password != user.password then callback null, false
else callback null, user
passport.use 'client-basic', new BasicStrategy (name, secret, callback) ->
ctx.models.client
.findOne()
.where name: name
.exec (err, client) ->
if err then return callback err
if !client || client.secret != secret then callback null, false
else callback null, client
passport.use new BearerStrategy (accessToken, callback) ->
ctx.models.token
.findOne()
.where value: accessToken
.exec (err, token) ->
if err then return callback err
if !token then return callback null, false
ctx.models.user
.findOne()
.where id: token.userId
.exec (err, user) ->
if err then return callback err
if !user then callback null, false
else callback null, user, scope: '*'
return {
isAuthenticated: passport.authenticate ['basic', 'bearer'], session: false
isClientAuthenticated: passport.authenticate 'client-basic', session: false
isBearerAuthenticated: passport.authenticate 'bearer', session: false
}
| 212386 | passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy
BearerStrategy = require('passport-http-bearer').Strategy
module.exports = (ctx) ->
passport.use new BasicStrategy (username, password, callback) ->
ctx.models.user
.findOne()
.where username: username
.exec (err, user) ->
if err then return callback err
if !user then return callback null, false
if password != user.<PASSWORD> then callback null, false
else callback null, user
passport.use 'client-basic', new BasicStrategy (name, secret, callback) ->
ctx.models.client
.findOne()
.where name: name
.exec (err, client) ->
if err then return callback err
if !client || client.secret != secret then callback null, false
else callback null, client
passport.use new BearerStrategy (accessToken, callback) ->
ctx.models.token
.findOne()
.where value: accessToken
.exec (err, token) ->
if err then return callback err
if !token then return callback null, false
ctx.models.user
.findOne()
.where id: token.userId
.exec (err, user) ->
if err then return callback err
if !user then callback null, false
else callback null, user, scope: '*'
return {
isAuthenticated: passport.authenticate ['basic', 'bearer'], session: false
isClientAuthenticated: passport.authenticate 'client-basic', session: false
isBearerAuthenticated: passport.authenticate 'bearer', session: false
}
| true | passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy
BearerStrategy = require('passport-http-bearer').Strategy
module.exports = (ctx) ->
passport.use new BasicStrategy (username, password, callback) ->
ctx.models.user
.findOne()
.where username: username
.exec (err, user) ->
if err then return callback err
if !user then return callback null, false
if password != user.PI:PASSWORD:<PASSWORD>END_PI then callback null, false
else callback null, user
passport.use 'client-basic', new BasicStrategy (name, secret, callback) ->
ctx.models.client
.findOne()
.where name: name
.exec (err, client) ->
if err then return callback err
if !client || client.secret != secret then callback null, false
else callback null, client
passport.use new BearerStrategy (accessToken, callback) ->
ctx.models.token
.findOne()
.where value: accessToken
.exec (err, token) ->
if err then return callback err
if !token then return callback null, false
ctx.models.user
.findOne()
.where id: token.userId
.exec (err, user) ->
if err then return callback err
if !user then callback null, false
else callback null, user, scope: '*'
return {
isAuthenticated: passport.authenticate ['basic', 'bearer'], session: false
isClientAuthenticated: passport.authenticate 'client-basic', session: false
isBearerAuthenticated: passport.authenticate 'bearer', session: false
}
|
[
{
"context": " express.basicAuth (user, pass) -> \n password = process.env.PG_BASIC_PASS\n user = process.env.PG_BASIC_USER || 'pguser'\n",
"end": 125,
"score": 0.8150537014007568,
"start": 100,
"tag": "PASSWORD",
"value": "process.env.PG_BASIC_PASS"
},
{
"context": "SIC_PASS\n user = process.env.PG_BASIC_USER || 'pguser'\n if (password == null || password == undefine",
"end": 173,
"score": 0.9854637980461121,
"start": 167,
"tag": "USERNAME",
"value": "pguser"
},
{
"context": " return false;\n return user == user && pass == password\n\n",
"end": 353,
"score": 0.8775938153266907,
"start": 345,
"tag": "PASSWORD",
"value": "password"
}
] | lib/basic_auth.coffee | letsface/postgresql-http-server | 13 | express = require('express')
exports.secureAPI = express.basicAuth (user, pass) ->
password = process.env.PG_BASIC_PASS
user = process.env.PG_BASIC_USER || 'pguser'
if (password == null || password == undefined)
console.log("PG_BASIC_PASS env variable is missing....")
return false;
return user == user && pass == password
| 92580 | express = require('express')
exports.secureAPI = express.basicAuth (user, pass) ->
password = <PASSWORD>
user = process.env.PG_BASIC_USER || 'pguser'
if (password == null || password == undefined)
console.log("PG_BASIC_PASS env variable is missing....")
return false;
return user == user && pass == <PASSWORD>
| true | express = require('express')
exports.secureAPI = express.basicAuth (user, pass) ->
password = PI:PASSWORD:<PASSWORD>END_PI
user = process.env.PG_BASIC_USER || 'pguser'
if (password == null || password == undefined)
console.log("PG_BASIC_PASS env variable is missing....")
return false;
return user == user && pass == PI:PASSWORD:<PASSWORD>END_PI
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 74,
"score": 0.9998917579650879,
"start": 61,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 96,
"score": 0.9999338388442993,
"start": 76,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
},
{
"context": "in entry point of a ConsoleApplication\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass Application extend",
"end": 505,
"score": 0.9998962879180908,
"start": 492,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "f a ConsoleApplication\n#\n# @author Jessym Reziga <jessym@konsserto.com>\n#\nclass Application extends ConsoleApplication\n\n",
"end": 527,
"score": 0.9999334216117859,
"start": 507,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Component/Console/Application.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Jessym Reziga <jessym@konsserto.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Bundle = use('@Konsserto/Component/Bundle/Bundle')
ConsoleApplication = use('@Konsserto/Component/Console/ConsoleApplication')
Kernel = use('@Konsserto/Component/HttpKernel/Kernel')
#
# Application is the main entry point of a ConsoleApplication
#
# @author Jessym Reziga <jessym@konsserto.com>
#
class Application extends ConsoleApplication
constructor:(@kernel) ->
@commandsRegistered = false
super 'Konsserto',Kernel.VERSION
# @return [String] returns ///
getKernel:() ->
return @kernel
run:(input) ->
@kernel.boot()
@container = @kernel.container
if !@commandsRegistered
@registerCommands()
@commandsRegistered = true
for k,command of @commands
command.setContainer(@container)
return super input
registerCommands:() ->
bundles = @container.get('Application').getBundles()
for bundleName,bundle of bundles
if bundle instanceof Bundle
bundle.registerCommands(this)
module.exports = Application
| 172604 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Bundle = use('@Konsserto/Component/Bundle/Bundle')
ConsoleApplication = use('@Konsserto/Component/Console/ConsoleApplication')
Kernel = use('@Konsserto/Component/HttpKernel/Kernel')
#
# Application is the main entry point of a ConsoleApplication
#
# @author <NAME> <<EMAIL>>
#
class Application extends ConsoleApplication
constructor:(@kernel) ->
@commandsRegistered = false
super 'Konsserto',Kernel.VERSION
# @return [String] returns ///
getKernel:() ->
return @kernel
run:(input) ->
@kernel.boot()
@container = @kernel.container
if !@commandsRegistered
@registerCommands()
@commandsRegistered = true
for k,command of @commands
command.setContainer(@container)
return super input
registerCommands:() ->
bundles = @container.get('Application').getBundles()
for bundleName,bundle of bundles
if bundle instanceof Bundle
bundle.registerCommands(this)
module.exports = Application
| true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
Bundle = use('@Konsserto/Component/Bundle/Bundle')
ConsoleApplication = use('@Konsserto/Component/Console/ConsoleApplication')
Kernel = use('@Konsserto/Component/HttpKernel/Kernel')
#
# Application is the main entry point of a ConsoleApplication
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
class Application extends ConsoleApplication
constructor:(@kernel) ->
@commandsRegistered = false
super 'Konsserto',Kernel.VERSION
# @return [String] returns ///
getKernel:() ->
return @kernel
run:(input) ->
@kernel.boot()
@container = @kernel.container
if !@commandsRegistered
@registerCommands()
@commandsRegistered = true
for k,command of @commands
command.setContainer(@container)
return super input
registerCommands:() ->
bundles = @container.get('Application').getBundles()
for bundleName,bundle of bundles
if bundle instanceof Bundle
bundle.registerCommands(this)
module.exports = Application
|
[
{
"context": "ew Enforce aria role attribute is valid.\n# @author Ethan Cohen\n###\n\n# ------------------------------------------",
"end": 104,
"score": 0.9998776912689209,
"start": 93,
"tag": "NAME",
"value": "Ethan Cohen"
}
] | src/tests/rules/aria-role.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce aria role attribute is valid.
# @author Ethan Cohen
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{roles} = require 'aria-query'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/aria-role'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
message: 'Elements with ARIA roles must use a valid, non-abstract ARIA role.'
type: 'JSXAttribute'
roleKeys = [...roles.keys()]
validRoles = roleKeys.filter (role) -> roles.get(role).abstract is no
invalidRoles = roleKeys.filter (role) -> roles.get(role).abstract is yes
createTests = (roleNames) ->
roleNames.map (role) ->
code: "<div role=\"#{role.toLowerCase()}\" />"
validTests = createTests validRoles
invalidTests = createTests(invalidRoles).map (test) ->
invalidTest = {...test}
invalidTest.errors = [errorMessage]
invalidTest
ignoreNonDOMSchema = [ignoreNonDOM: yes]
ruleTester.run 'aria-role', rule,
valid:
[
# Variables should pass, as we are only testing literals.
code: '<div />'
,
code: '<div></div>'
,
code: '<div role={role} />'
,
code: '<div role={role || "button"} />'
,
code: '<div role={role || "foobar"} />'
,
code: '<div role="tabpanel row" />'
,
code: '<div role="switch" />'
,
code: '<div role="doc-abstract" />'
,
code: '<div role="doc-appendix doc-bibliography" />'
,
code: '<Bar baz />'
,
code: '<Foo role="bar" />', options: ignoreNonDOMSchema
,
code: '<fakeDOM role="bar" />', options: ignoreNonDOMSchema
,
code: '<img role="presentation" />', options: ignoreNonDOMSchema
]
.concat validTests
.map parserOptionsMapper
invalid:
[
code: '<div role="foobar" />', errors: [errorMessage]
,
code: '<div role="datepicker"></div>', errors: [errorMessage]
,
code: '<div role="range"></div>', errors: [errorMessage]
,
code: '<div role="Button"></div>', errors: [errorMessage]
,
code: '<div role=""></div>', errors: [errorMessage]
,
code: '<div role="tabpanel row foobar"></div>', errors: [errorMessage]
,
code: '<div role="tabpanel row range"></div>', errors: [errorMessage]
,
code: '<div role="doc-endnotes range"></div>', errors: [errorMessage]
,
code: '<div role />', errors: [errorMessage]
,
code: '<div role={null}></div>', errors: [errorMessage]
,
code: '<Foo role="datepicker" />', errors: [errorMessage]
,
code: '<Foo role="Button" />', errors: [errorMessage]
]
.concat invalidTests
.map parserOptionsMapper
| 97500 | ### eslint-env jest ###
###*
# @fileoverview Enforce aria role attribute is valid.
# @author <NAME>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{roles} = require 'aria-query'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/aria-role'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
message: 'Elements with ARIA roles must use a valid, non-abstract ARIA role.'
type: 'JSXAttribute'
roleKeys = [...roles.keys()]
validRoles = roleKeys.filter (role) -> roles.get(role).abstract is no
invalidRoles = roleKeys.filter (role) -> roles.get(role).abstract is yes
createTests = (roleNames) ->
roleNames.map (role) ->
code: "<div role=\"#{role.toLowerCase()}\" />"
validTests = createTests validRoles
invalidTests = createTests(invalidRoles).map (test) ->
invalidTest = {...test}
invalidTest.errors = [errorMessage]
invalidTest
ignoreNonDOMSchema = [ignoreNonDOM: yes]
ruleTester.run 'aria-role', rule,
valid:
[
# Variables should pass, as we are only testing literals.
code: '<div />'
,
code: '<div></div>'
,
code: '<div role={role} />'
,
code: '<div role={role || "button"} />'
,
code: '<div role={role || "foobar"} />'
,
code: '<div role="tabpanel row" />'
,
code: '<div role="switch" />'
,
code: '<div role="doc-abstract" />'
,
code: '<div role="doc-appendix doc-bibliography" />'
,
code: '<Bar baz />'
,
code: '<Foo role="bar" />', options: ignoreNonDOMSchema
,
code: '<fakeDOM role="bar" />', options: ignoreNonDOMSchema
,
code: '<img role="presentation" />', options: ignoreNonDOMSchema
]
.concat validTests
.map parserOptionsMapper
invalid:
[
code: '<div role="foobar" />', errors: [errorMessage]
,
code: '<div role="datepicker"></div>', errors: [errorMessage]
,
code: '<div role="range"></div>', errors: [errorMessage]
,
code: '<div role="Button"></div>', errors: [errorMessage]
,
code: '<div role=""></div>', errors: [errorMessage]
,
code: '<div role="tabpanel row foobar"></div>', errors: [errorMessage]
,
code: '<div role="tabpanel row range"></div>', errors: [errorMessage]
,
code: '<div role="doc-endnotes range"></div>', errors: [errorMessage]
,
code: '<div role />', errors: [errorMessage]
,
code: '<div role={null}></div>', errors: [errorMessage]
,
code: '<Foo role="datepicker" />', errors: [errorMessage]
,
code: '<Foo role="Button" />', errors: [errorMessage]
]
.concat invalidTests
.map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce aria role attribute is valid.
# @author PI:NAME:<NAME>END_PI
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{roles} = require 'aria-query'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/aria-role'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
errorMessage =
message: 'Elements with ARIA roles must use a valid, non-abstract ARIA role.'
type: 'JSXAttribute'
roleKeys = [...roles.keys()]
validRoles = roleKeys.filter (role) -> roles.get(role).abstract is no
invalidRoles = roleKeys.filter (role) -> roles.get(role).abstract is yes
createTests = (roleNames) ->
roleNames.map (role) ->
code: "<div role=\"#{role.toLowerCase()}\" />"
validTests = createTests validRoles
invalidTests = createTests(invalidRoles).map (test) ->
invalidTest = {...test}
invalidTest.errors = [errorMessage]
invalidTest
ignoreNonDOMSchema = [ignoreNonDOM: yes]
ruleTester.run 'aria-role', rule,
valid:
[
# Variables should pass, as we are only testing literals.
code: '<div />'
,
code: '<div></div>'
,
code: '<div role={role} />'
,
code: '<div role={role || "button"} />'
,
code: '<div role={role || "foobar"} />'
,
code: '<div role="tabpanel row" />'
,
code: '<div role="switch" />'
,
code: '<div role="doc-abstract" />'
,
code: '<div role="doc-appendix doc-bibliography" />'
,
code: '<Bar baz />'
,
code: '<Foo role="bar" />', options: ignoreNonDOMSchema
,
code: '<fakeDOM role="bar" />', options: ignoreNonDOMSchema
,
code: '<img role="presentation" />', options: ignoreNonDOMSchema
]
.concat validTests
.map parserOptionsMapper
invalid:
[
code: '<div role="foobar" />', errors: [errorMessage]
,
code: '<div role="datepicker"></div>', errors: [errorMessage]
,
code: '<div role="range"></div>', errors: [errorMessage]
,
code: '<div role="Button"></div>', errors: [errorMessage]
,
code: '<div role=""></div>', errors: [errorMessage]
,
code: '<div role="tabpanel row foobar"></div>', errors: [errorMessage]
,
code: '<div role="tabpanel row range"></div>', errors: [errorMessage]
,
code: '<div role="doc-endnotes range"></div>', errors: [errorMessage]
,
code: '<div role />', errors: [errorMessage]
,
code: '<div role={null}></div>', errors: [errorMessage]
,
code: '<Foo role="datepicker" />', errors: [errorMessage]
,
code: '<Foo role="Button" />', errors: [errorMessage]
]
.concat invalidTests
.map parserOptionsMapper
|
[
{
"context": "otoall\n ---\n \n Lecture Notes of DL Zero To All, Sung Kim.\n \n Thanks to Sung Kim for the great lecture.\n ",
"end": 343,
"score": 0.9857950806617737,
"start": 335,
"tag": "NAME",
"value": "Sung Kim"
},
{
"context": " Notes of DL Zero To All, Sung Kim.\n \n Thanks to Sung Kim for the great lecture.\n \n [DL Zero To All, Lect",
"end": 368,
"score": 0.9914045333862305,
"start": 360,
"tag": "NAME",
"value": "Sung Kim"
},
{
"context": "All, Lecture note(Notion)](https://www.notion.so/rpblic/78e4b7b172ec48698a9d13a99d4243b8?v=a3bfa41cd3a741",
"end": 464,
"score": 0.5639904737472534,
"start": 459,
"tag": "USERNAME",
"value": "pblic"
}
] | _posts/notes/4a8e7c77-d909-4821-87eb-cc6f3fae08fb.cson | rpblic/rpblic.github.io | 0 | createdAt: "2018-09-02T16:45:02.622Z"
updatedAt: "2018-09-26T23:35:32.883Z"
type: "MARKDOWN_NOTE"
folder: "825d5dcb0e1827af7189"
title: ""
content: '''
---
layout: post
title: DeepLearning Zero To All Lecture note
tags: [DL, ZeroToAll, LectureNote]
category: Deeplearningzerotoall
---
Lecture Notes of DL Zero To All, Sung Kim.
Thanks to Sung Kim for the great lecture.
[DL Zero To All, Lecture note(Notion)](https://www.notion.so/rpblic/78e4b7b172ec48698a9d13a99d4243b8?v=a3bfa41cd3a741c4be0dd03958be97e2)

'''
tags: []
isStarred: false
isTrashed: false
| 24741 | createdAt: "2018-09-02T16:45:02.622Z"
updatedAt: "2018-09-26T23:35:32.883Z"
type: "MARKDOWN_NOTE"
folder: "825d5dcb0e1827af7189"
title: ""
content: '''
---
layout: post
title: DeepLearning Zero To All Lecture note
tags: [DL, ZeroToAll, LectureNote]
category: Deeplearningzerotoall
---
Lecture Notes of DL Zero To All, <NAME>.
Thanks to <NAME> for the great lecture.
[DL Zero To All, Lecture note(Notion)](https://www.notion.so/rpblic/78e4b7b172ec48698a9d13a99d4243b8?v=a3bfa41cd3a741c4be0dd03958be97e2)

'''
tags: []
isStarred: false
isTrashed: false
| true | createdAt: "2018-09-02T16:45:02.622Z"
updatedAt: "2018-09-26T23:35:32.883Z"
type: "MARKDOWN_NOTE"
folder: "825d5dcb0e1827af7189"
title: ""
content: '''
---
layout: post
title: DeepLearning Zero To All Lecture note
tags: [DL, ZeroToAll, LectureNote]
category: Deeplearningzerotoall
---
Lecture Notes of DL Zero To All, PI:NAME:<NAME>END_PI.
Thanks to PI:NAME:<NAME>END_PI for the great lecture.
[DL Zero To All, Lecture note(Notion)](https://www.notion.so/rpblic/78e4b7b172ec48698a9d13a99d4243b8?v=a3bfa41cd3a741c4be0dd03958be97e2)

'''
tags: []
isStarred: false
isTrashed: false
|
[
{
"context": "ber.Controller.extend\n username: null\n password: null\n actions:\n login: ->\n user = @get 'user'",
"end": 104,
"score": 0.9665197730064392,
"start": 100,
"tag": "PASSWORD",
"value": "null"
},
{
"context": ">\n user = @get 'user'\n username = @get 'username'\n password = @get 'password'\n user.set ",
"end": 186,
"score": 0.9951928853988647,
"start": 178,
"tag": "USERNAME",
"value": "username"
},
{
"context": "username = @get 'username'\n password = @get 'password'\n user.set 'username', username\n user.s",
"end": 219,
"score": 0.7589911222457886,
"start": 211,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "sword = @get 'password'\n user.set 'username', username\n user.set 'password', password\n\n base =",
"end": 256,
"score": 0.931557834148407,
"start": 248,
"tag": "USERNAME",
"value": "username"
},
{
"context": "et 'username', username\n user.set 'password', password\n\n base = document.baseURI.replace(\"http://\",",
"end": 292,
"score": 0.9970870614051819,
"start": 284,
"tag": "PASSWORD",
"value": "password"
}
] | mapping-pilot-ui/app/controllers/login.coffee | tenforce/esco-mapping-pilot | 0 | `import Ember from 'ember'`
LoginController = Ember.Controller.extend
username: null
password: null
actions:
login: ->
user = @get 'user'
username = @get 'username'
password = @get 'password'
user.set 'username', username
user.set 'password', password
base = document.baseURI.replace("http://", "http://#{username}:#{password}@")
Ember.$.ajax
url: "#{base}api/flood_status"
type: "POST"
success: =>
@transitionToRoute 'index'
error: (error) =>
if error.status == 401
alert "Could not log in using this combination of username and password"
user.logout()
else
@transitionToRoute 'taxonomies'
`export default LoginController`
| 75830 | `import Ember from 'ember'`
LoginController = Ember.Controller.extend
username: null
password: <PASSWORD>
actions:
login: ->
user = @get 'user'
username = @get 'username'
password = @get '<PASSWORD>'
user.set 'username', username
user.set 'password', <PASSWORD>
base = document.baseURI.replace("http://", "http://#{username}:#{password}@")
Ember.$.ajax
url: "#{base}api/flood_status"
type: "POST"
success: =>
@transitionToRoute 'index'
error: (error) =>
if error.status == 401
alert "Could not log in using this combination of username and password"
user.logout()
else
@transitionToRoute 'taxonomies'
`export default LoginController`
| true | `import Ember from 'ember'`
LoginController = Ember.Controller.extend
username: null
password: PI:PASSWORD:<PASSWORD>END_PI
actions:
login: ->
user = @get 'user'
username = @get 'username'
password = @get 'PI:PASSWORD:<PASSWORD>END_PI'
user.set 'username', username
user.set 'password', PI:PASSWORD:<PASSWORD>END_PI
base = document.baseURI.replace("http://", "http://#{username}:#{password}@")
Ember.$.ajax
url: "#{base}api/flood_status"
type: "POST"
success: =>
@transitionToRoute 'index'
error: (error) =>
if error.status == 401
alert "Could not log in using this combination of username and password"
user.logout()
else
@transitionToRoute 'taxonomies'
`export default LoginController`
|
[
{
"context": "r.users.find().count()==0\n\tnew_user={\n\t\tusername:\"james\"\n\t\temail:\"james@kimatech.com\"\n\t\tpassword:\"ima123\"",
"end": 63,
"score": 0.9995595216751099,
"start": 58,
"tag": "USERNAME",
"value": "james"
},
{
"context": "ount()==0\n\tnew_user={\n\t\tusername:\"james\"\n\t\temail:\"james@kimatech.com\"\n\t\tpassword:\"ima123\"\n\t\troles:[\"internal\",\"useradm",
"end": 92,
"score": 0.9999313354492188,
"start": 74,
"tag": "EMAIL",
"value": "james@kimatech.com"
},
{
"context": ":\"james\"\n\t\temail:\"james@kimatech.com\"\n\t\tpassword:\"ima123\"\n\t\troles:[\"internal\",\"useradmin\",\"systemadmin\"]\n\t",
"end": 112,
"score": 0.9992374777793884,
"start": 106,
"tag": "PASSWORD",
"value": "ima123"
},
{
"context": "\",\"useradmin\",\"systemadmin\"]\n\t\tprofile:{fullname:\"James\"}\n\t}\n\tadmin_id=Accounts.createUser(new_user)\n\tRol",
"end": 187,
"score": 0.7859801054000854,
"start": 182,
"tag": "NAME",
"value": "James"
},
{
"context": "eradmin','systemadmin'])\n\n\tnew_user={\n\t\tusername:\"demo\"\n\t\temail:\"demo@kimatech.com\"\n\t\tpassword:\"demo\"\n\t\t",
"end": 334,
"score": 0.9802871346473694,
"start": 330,
"tag": "USERNAME",
"value": "demo"
},
{
"context": "madmin'])\n\n\tnew_user={\n\t\tusername:\"demo\"\n\t\temail:\"demo@kimatech.com\"\n\t\tpassword:\"demo\"\n\t\troles:[\"internal\",\"useradmin",
"end": 362,
"score": 0.9999328255653381,
"start": 345,
"tag": "EMAIL",
"value": "demo@kimatech.com"
},
{
"context": "me:\"demo\"\n\t\temail:\"demo@kimatech.com\"\n\t\tpassword:\"demo\"\n\t\troles:[\"internal\",\"useradmin\",\"systemadmin\"]\n\t",
"end": 380,
"score": 0.9993807077407837,
"start": 376,
"tag": "PASSWORD",
"value": "demo"
}
] | server/seeds/userinit.coffee | sawima/kimashare | 0 | if Meteor.users.find().count()==0
new_user={
username:"james"
email:"james@kimatech.com"
password:"ima123"
roles:["internal","useradmin","systemadmin"]
profile:{fullname:"James"}
}
admin_id=Accounts.createUser(new_user)
Roles.addUsersToRoles(admin_id,['internal','useradmin','systemadmin'])
new_user={
username:"demo"
email:"demo@kimatech.com"
password:"demo"
roles:["internal","useradmin","systemadmin"]
profile:{fullname:"Demo"}
}
admin_id=Accounts.createUser(new_user)
Roles.addUsersToRoles(admin_id,['internal','useradmin','systemadmin'])
| 101195 | if Meteor.users.find().count()==0
new_user={
username:"james"
email:"<EMAIL>"
password:"<PASSWORD>"
roles:["internal","useradmin","systemadmin"]
profile:{fullname:"<NAME>"}
}
admin_id=Accounts.createUser(new_user)
Roles.addUsersToRoles(admin_id,['internal','useradmin','systemadmin'])
new_user={
username:"demo"
email:"<EMAIL>"
password:"<PASSWORD>"
roles:["internal","useradmin","systemadmin"]
profile:{fullname:"Demo"}
}
admin_id=Accounts.createUser(new_user)
Roles.addUsersToRoles(admin_id,['internal','useradmin','systemadmin'])
| true | if Meteor.users.find().count()==0
new_user={
username:"james"
email:"PI:EMAIL:<EMAIL>END_PI"
password:"PI:PASSWORD:<PASSWORD>END_PI"
roles:["internal","useradmin","systemadmin"]
profile:{fullname:"PI:NAME:<NAME>END_PI"}
}
admin_id=Accounts.createUser(new_user)
Roles.addUsersToRoles(admin_id,['internal','useradmin','systemadmin'])
new_user={
username:"demo"
email:"PI:EMAIL:<EMAIL>END_PI"
password:"PI:PASSWORD:<PASSWORD>END_PI"
roles:["internal","useradmin","systemadmin"]
profile:{fullname:"Demo"}
}
admin_id=Accounts.createUser(new_user)
Roles.addUsersToRoles(admin_id,['internal','useradmin','systemadmin'])
|
[
{
"context": "expect($(\"#my-sel option:selected\").text()).toBe(\"Luccas Marks\")\n )\n )\n\n describe(\"::getValue\", () ->\n i",
"end": 799,
"score": 0.9998281002044678,
"start": 787,
"tag": "NAME",
"value": "Luccas Marks"
}
] | spec/javascripts/core/components/select.spec.coffee | houzelio/houzel | 2 | import SelectCmp from 'javascripts/core/components/select'
describe("Select Component", () ->
beforeEach ->
setFixtures(__html__['my-select.html'])
@mySelect = new SelectCmp(el: '#my-sel')
describe("initializing", () ->
it("shows chosen for select element", () ->
expect($('#my-sel').next()).toBeMatchedBy('.chosen-container')
)
)
it("should trigger a Change event when a value changes", () ->
spy = jasmine.createSpy()
myObject = new Marionette.MnObject
myObject.listenTo(@mySelect, 'select:change', spy)
$('#my-sel').trigger('change')
expect(spy).toHaveBeenCalled()
)
describe("::setValue", () ->
it("changes the value on select", () ->
@mySelect.setValue(4)
expect($("#my-sel option:selected").text()).toBe("Luccas Marks")
)
)
describe("::getValue", () ->
it("gets the value on select", () ->
$("#my-sel").val(2)
expect(@mySelect.getValue()).toBe('2')
)
)
)
| 9251 | import SelectCmp from 'javascripts/core/components/select'
describe("Select Component", () ->
beforeEach ->
setFixtures(__html__['my-select.html'])
@mySelect = new SelectCmp(el: '#my-sel')
describe("initializing", () ->
it("shows chosen for select element", () ->
expect($('#my-sel').next()).toBeMatchedBy('.chosen-container')
)
)
it("should trigger a Change event when a value changes", () ->
spy = jasmine.createSpy()
myObject = new Marionette.MnObject
myObject.listenTo(@mySelect, 'select:change', spy)
$('#my-sel').trigger('change')
expect(spy).toHaveBeenCalled()
)
describe("::setValue", () ->
it("changes the value on select", () ->
@mySelect.setValue(4)
expect($("#my-sel option:selected").text()).toBe("<NAME>")
)
)
describe("::getValue", () ->
it("gets the value on select", () ->
$("#my-sel").val(2)
expect(@mySelect.getValue()).toBe('2')
)
)
)
| true | import SelectCmp from 'javascripts/core/components/select'
describe("Select Component", () ->
beforeEach ->
setFixtures(__html__['my-select.html'])
@mySelect = new SelectCmp(el: '#my-sel')
describe("initializing", () ->
it("shows chosen for select element", () ->
expect($('#my-sel').next()).toBeMatchedBy('.chosen-container')
)
)
it("should trigger a Change event when a value changes", () ->
spy = jasmine.createSpy()
myObject = new Marionette.MnObject
myObject.listenTo(@mySelect, 'select:change', spy)
$('#my-sel').trigger('change')
expect(spy).toHaveBeenCalled()
)
describe("::setValue", () ->
it("changes the value on select", () ->
@mySelect.setValue(4)
expect($("#my-sel option:selected").text()).toBe("PI:NAME:<NAME>END_PI")
)
)
describe("::getValue", () ->
it("gets the value on select", () ->
$("#my-sel").val(2)
expect(@mySelect.getValue()).toBe('2')
)
)
)
|
[
{
"context": "oGLib\n# Module | Stat Methods\n# Author | Sherif Emabrak\n# Description | The neighbor method returns the e",
"end": 163,
"score": 0.9998761415481567,
"start": 149,
"tag": "NAME",
"value": "Sherif Emabrak"
}
] | src/lib/statistics/link/neighbour.coffee | Sherif-Embarak/gp-test | 0 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | Sherif Emabrak
# Description | The neighbor method returns the edges in a nearest-neighbor graph.
# ------------------------------------------------------------------------------
neighbor = () -> | 133134 | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | <NAME>
# Description | The neighbor method returns the edges in a nearest-neighbor graph.
# ------------------------------------------------------------------------------
neighbor = () -> | true | # ------------------------------------------------------------------------------
# Project | GoGLib
# Module | Stat Methods
# Author | PI:NAME:<NAME>END_PI
# Description | The neighbor method returns the edges in a nearest-neighbor graph.
# ------------------------------------------------------------------------------
neighbor = () -> |
[
{
"context": "d: presenceId\n meeting: meetingId\n name: name\n rooms:\n visible: []\n invisibl",
"end": 3753,
"score": 0.9971221685409546,
"start": 3749,
"tag": "NAME",
"value": "name"
}
] | client/Meeting.coffee | diomidov/comingle | 0 | import React, {useState, useEffect, useReducer, useMemo} from 'react'
import {useParams, useLocation, useHistory} from 'react-router-dom'
import {Tooltip, OverlayTrigger} from 'react-bootstrap'
import {Session} from 'meteor/session'
import {useTracker} from 'meteor/react-meteor-data'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faComment, faDoorOpen, faEye, faEyeSlash, faQuestion} from '@fortawesome/free-solid-svg-icons'
import {clipboardLink} from './icons/clipboardLink'
import FlexLayout from './FlexLayout'
import {ArchiveButton} from './ArchiveButton'
import {ChatRoom} from './ChatRoom'
import {RoomList} from './RoomList'
import {Room} from './Room'
import {Rooms} from '/lib/rooms'
import {Welcome} from './Welcome'
import {Presence} from '/lib/presence'
import {validId} from '/lib/id'
import {getPresenceId, getCreator} from './lib/presenceId'
import {useIdMap} from './lib/useIdMap'
import {formatDateTime} from './lib/dates'
export MeetingContext = React.createContext {}
initModel = ->
model = FlexLayout.Model.fromJson
global: Object.assign {}, FlexLayout.defaultGlobal,
borderEnableDrop: false
borders: [
type: 'border'
location: 'left'
selected: 0
children: [
id: 'roomsTab'
type: 'tab'
name: "Meeting Rooms"
component: 'RoomList'
enableClose: false
enableDrag: false
,
id: 'chat'
type: 'tab'
name: "Meeting Chat"
component: 'ChatRoom'
enableClose: false
enableDrag: false
enableRenderOnDemand: false
]
]
layout:
id: 'root'
type: 'row'
weight: 100
children: [
id: 'mainTabset'
type: 'tabset'
children: [
id: 'welcome'
type: 'tab'
name: 'Welcome'
component: 'Welcome'
]
]
model.setOnAllowDrop (dragNode, dropInfo) ->
return false if dropInfo.node.getId() == 'roomsTabSet' and dropInfo.location != FlexLayout.DockLocation.RIGHT
#return false if dropInfo.node.getType() == 'border'
#return false if dragNode.getParent()?.getType() == 'border'
true
model
export Meeting = ->
{meetingId} = useParams()
[model, setModel] = useState initModel
location = useLocation()
history = useHistory()
{loading, rooms} = useTracker ->
sub = Meteor.subscribe 'meeting', meetingId
loading: not sub.ready()
rooms: Rooms.find().fetch()
id2room = useIdMap rooms
useEffect ->
for room in rooms
if model.getNodeById room._id
model.doAction FlexLayout.Actions.updateNodeAttributes room._id,
name: room.title
undefined
, [rooms]
openRoom = useMemo -> (id, focus = true) ->
tabset = FlexLayout.getActiveTabset model
unless model.getNodeById id
tab =
id: id
type: 'tab'
name: Rooms.findOne(id)?.title ? id
component: 'Room'
config: showArchived: false
model.doAction FlexLayout.Actions.addNode tab,
tabset.getId(), FlexLayout.DockLocation.CENTER, -1, focus
else
FlexLayout.forceSelectTab model, id
useEffect ->
if location.hash and validId id = location.hash[1..]
openRoom id
undefined
, [location.hash]
[showArchived, setShowArchived] = useReducer(
(state, {id, value}) ->
if model.getNodeById id
model.doAction FlexLayout.Actions.updateNodeAttributes id,
config: showArchived: value
state[id] = value
state
, {})
presenceId = getPresenceId()
name = useTracker -> Session.get 'name'
updatePresence = ->
return unless name? # wait for tracker to load name
presence =
id: presenceId
meeting: meetingId
name: name
rooms:
visible: []
invisible: []
model.visitNodes (node) ->
if node.getType() == 'tab' and node.getComponent() == 'Room'
if node.isVisible()
presence.rooms.visible.push node.getId()
else
presence.rooms.invisible.push node.getId()
current = Presence.findOne
id: presenceId
meeting: meetingId
unless current? and current.name == presence.name and
current?.rooms?.visible?.toString?() ==
presence.rooms.visible.toString() and
current?.rooms?.invisible?.toString?() ==
presence.rooms.invisible.toString()
Meteor.call 'presenceUpdate', presence
## Send presence when name changes or when we reconnect to server
## (so server may have deleted our presence information).
useEffect updatePresence, [name]
useTracker -> updatePresence() if Meteor.status().connected
onAction = (action) ->
switch action.type
when FlexLayout.Actions.RENAME_TAB
## Sanitize room title and push to other users
action.data.text = action.data.text.trim()
return unless action.data.text # prevent empty title
Meteor.call 'roomEdit',
id: action.data.node
title: action.data.text
updator: getCreator()
action
onModelChange = ->
updatePresence()
## Maintain hash part of URL to point to "current" tab.
tabset = FlexLayout.getActiveTabset model
tab = tabset?.getSelectedNode()
if tab?.getComponent() == 'Room'
unless location.hash == "##{tab.getId()}"
history.replace "/m/#{meetingId}##{tab.getId()}"
Session.set 'currentRoom', tab.getId()
else
if location.hash
history.replace "/m/#{meetingId}"
Session.set 'currentRoom', undefined
factory = (node) -> # eslint-disable-line react/display-name
switch node.getComponent()
when 'RoomList'
<RoomList loading={loading} model={model}/>
when 'ChatRoom'
<ChatRoom channel={meetingId} audience="everyone"
visible={node.isVisible()} extraData={node.getExtraData()}
updateTab={-> FlexLayout.updateNode model, node.getId()}/>
when 'Welcome'
<Welcome/>
when 'Room'
if node.isVisible()
<Room loading={loading} roomId={node.getId()} {...node.getConfig()}/>
else
null # don't render hidden rooms, in particular to cancel all calls
tooltip = (node) -> (props) -> # eslint-disable-line react/display-name
room = id2room[node.getId()]
return <span/> unless room
<Tooltip {...props}>
Room “{room.title}”<br/>
created by {room.creator?.name ? 'unknown'}<br/>
on {formatDateTime room.created}
{if room.archived
<>
<br/>archived by {room.archiver?.name ? 'unknown'}
<br/>on {formatDateTime room.archived}
</>
}
</Tooltip>
iconFactory = (node) -> # eslint-disable-line react/display-name
<OverlayTrigger placement="bottom" overlay={tooltip node}>
{if node.getComponent() == 'ChatRoom'
<FontAwesomeIcon icon={faComment}/>
else if node.getComponent() == 'Welcome'
<FontAwesomeIcon icon={faQuestion}/>
else
<FontAwesomeIcon icon={faDoorOpen}/>
}
</OverlayTrigger>
onRenderTab = (node, renderState) ->
type = if node.getParent().getType() == 'border' then 'border' else 'tab'
buttons = renderState.buttons
if node.getComponent() == 'RoomList'
buttons?.push \
<div key="link"
className="flexlayout__#{type}_button_trailing"
aria-label="Save meeting link to clipboard"
onClick={-> navigator.clipboard.writeText \
Meteor.absoluteUrl "/m/#{meetingId}"}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>Save meeting link to clipboard</Tooltip>
}>
<FontAwesomeIcon icon={clipboardLink}/>
</OverlayTrigger>
</div>
else if node.getComponent() == 'ChatRoom'
return ChatRoom.onRenderTab node, renderState
return if node.getComponent() != 'Room'
room = id2room[node.getId()]
return unless room
className = 'tab-title'
className += ' archived' if room.archived
renderState.content =
<OverlayTrigger placement="bottom" overlay={tooltip node}>
<span className={className}>{renderState.content}</span>
</OverlayTrigger>
if node.isVisible() # special buttons for visible tabs
id = node.getId()
buttons?.push \
<div key="link"
className="flexlayout__#{type}_button_trailing flexlayout__tab_button_link"
aria-label="Save room link to clipboard"
onClick={-> navigator.clipboard.writeText \
Meteor.absoluteUrl "/m/#{meetingId}##{node.getId()}"}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>Save room link to clipboard</Tooltip>
}>
<FontAwesomeIcon icon={clipboardLink}/>
</OverlayTrigger>
</div>
showArchived = node.getConfig()?.showArchived
label =
if showArchived
"Hide Archived Tabs"
else
"Show Archived Tabs"
buttons?.push \
<div key="archived"
className="flexlayout__#{type}_button_trailing"
aria-label={label}
onClick={-> setShowArchived {id, value: not showArchived}}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>
{label}<br/>
<small>Currently {unless showArchived then <b>not</b>} showing archived tabs.</small>
</Tooltip>
}>
<FontAwesomeIcon icon={if showArchived then faEye else faEyeSlash}/>
</OverlayTrigger>
</div>
archiveRoom = ->
Meteor.call 'roomEdit',
id: room._id
archived: not room.archived
updator: getCreator()
if room = id2room[id]
buttons?.push <ArchiveButton key="archive" type={type} noun="room"
archived={room.archived} onClick={archiveRoom}
help="Archived rooms can still be viewed and restored from the list at the bottom."
/>
<MeetingContext.Provider value={{openRoom}}>
<FlexLayout.Layout model={model} factory={factory} iconFactory={iconFactory}
onRenderTab={onRenderTab}
onAction={onAction} onModelChange={-> setTimeout onModelChange, 0}
tabPhrase="room"/>
</MeetingContext.Provider>
Meeting.displayName = 'Meeting'
| 91785 | import React, {useState, useEffect, useReducer, useMemo} from 'react'
import {useParams, useLocation, useHistory} from 'react-router-dom'
import {Tooltip, OverlayTrigger} from 'react-bootstrap'
import {Session} from 'meteor/session'
import {useTracker} from 'meteor/react-meteor-data'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faComment, faDoorOpen, faEye, faEyeSlash, faQuestion} from '@fortawesome/free-solid-svg-icons'
import {clipboardLink} from './icons/clipboardLink'
import FlexLayout from './FlexLayout'
import {ArchiveButton} from './ArchiveButton'
import {ChatRoom} from './ChatRoom'
import {RoomList} from './RoomList'
import {Room} from './Room'
import {Rooms} from '/lib/rooms'
import {Welcome} from './Welcome'
import {Presence} from '/lib/presence'
import {validId} from '/lib/id'
import {getPresenceId, getCreator} from './lib/presenceId'
import {useIdMap} from './lib/useIdMap'
import {formatDateTime} from './lib/dates'
export MeetingContext = React.createContext {}
initModel = ->
model = FlexLayout.Model.fromJson
global: Object.assign {}, FlexLayout.defaultGlobal,
borderEnableDrop: false
borders: [
type: 'border'
location: 'left'
selected: 0
children: [
id: 'roomsTab'
type: 'tab'
name: "Meeting Rooms"
component: 'RoomList'
enableClose: false
enableDrag: false
,
id: 'chat'
type: 'tab'
name: "Meeting Chat"
component: 'ChatRoom'
enableClose: false
enableDrag: false
enableRenderOnDemand: false
]
]
layout:
id: 'root'
type: 'row'
weight: 100
children: [
id: 'mainTabset'
type: 'tabset'
children: [
id: 'welcome'
type: 'tab'
name: 'Welcome'
component: 'Welcome'
]
]
model.setOnAllowDrop (dragNode, dropInfo) ->
return false if dropInfo.node.getId() == 'roomsTabSet' and dropInfo.location != FlexLayout.DockLocation.RIGHT
#return false if dropInfo.node.getType() == 'border'
#return false if dragNode.getParent()?.getType() == 'border'
true
model
export Meeting = ->
{meetingId} = useParams()
[model, setModel] = useState initModel
location = useLocation()
history = useHistory()
{loading, rooms} = useTracker ->
sub = Meteor.subscribe 'meeting', meetingId
loading: not sub.ready()
rooms: Rooms.find().fetch()
id2room = useIdMap rooms
useEffect ->
for room in rooms
if model.getNodeById room._id
model.doAction FlexLayout.Actions.updateNodeAttributes room._id,
name: room.title
undefined
, [rooms]
openRoom = useMemo -> (id, focus = true) ->
tabset = FlexLayout.getActiveTabset model
unless model.getNodeById id
tab =
id: id
type: 'tab'
name: Rooms.findOne(id)?.title ? id
component: 'Room'
config: showArchived: false
model.doAction FlexLayout.Actions.addNode tab,
tabset.getId(), FlexLayout.DockLocation.CENTER, -1, focus
else
FlexLayout.forceSelectTab model, id
useEffect ->
if location.hash and validId id = location.hash[1..]
openRoom id
undefined
, [location.hash]
[showArchived, setShowArchived] = useReducer(
(state, {id, value}) ->
if model.getNodeById id
model.doAction FlexLayout.Actions.updateNodeAttributes id,
config: showArchived: value
state[id] = value
state
, {})
presenceId = getPresenceId()
name = useTracker -> Session.get 'name'
updatePresence = ->
return unless name? # wait for tracker to load name
presence =
id: presenceId
meeting: meetingId
name: <NAME>
rooms:
visible: []
invisible: []
model.visitNodes (node) ->
if node.getType() == 'tab' and node.getComponent() == 'Room'
if node.isVisible()
presence.rooms.visible.push node.getId()
else
presence.rooms.invisible.push node.getId()
current = Presence.findOne
id: presenceId
meeting: meetingId
unless current? and current.name == presence.name and
current?.rooms?.visible?.toString?() ==
presence.rooms.visible.toString() and
current?.rooms?.invisible?.toString?() ==
presence.rooms.invisible.toString()
Meteor.call 'presenceUpdate', presence
## Send presence when name changes or when we reconnect to server
## (so server may have deleted our presence information).
useEffect updatePresence, [name]
useTracker -> updatePresence() if Meteor.status().connected
onAction = (action) ->
switch action.type
when FlexLayout.Actions.RENAME_TAB
## Sanitize room title and push to other users
action.data.text = action.data.text.trim()
return unless action.data.text # prevent empty title
Meteor.call 'roomEdit',
id: action.data.node
title: action.data.text
updator: getCreator()
action
onModelChange = ->
updatePresence()
## Maintain hash part of URL to point to "current" tab.
tabset = FlexLayout.getActiveTabset model
tab = tabset?.getSelectedNode()
if tab?.getComponent() == 'Room'
unless location.hash == "##{tab.getId()}"
history.replace "/m/#{meetingId}##{tab.getId()}"
Session.set 'currentRoom', tab.getId()
else
if location.hash
history.replace "/m/#{meetingId}"
Session.set 'currentRoom', undefined
factory = (node) -> # eslint-disable-line react/display-name
switch node.getComponent()
when 'RoomList'
<RoomList loading={loading} model={model}/>
when 'ChatRoom'
<ChatRoom channel={meetingId} audience="everyone"
visible={node.isVisible()} extraData={node.getExtraData()}
updateTab={-> FlexLayout.updateNode model, node.getId()}/>
when 'Welcome'
<Welcome/>
when 'Room'
if node.isVisible()
<Room loading={loading} roomId={node.getId()} {...node.getConfig()}/>
else
null # don't render hidden rooms, in particular to cancel all calls
tooltip = (node) -> (props) -> # eslint-disable-line react/display-name
room = id2room[node.getId()]
return <span/> unless room
<Tooltip {...props}>
Room “{room.title}”<br/>
created by {room.creator?.name ? 'unknown'}<br/>
on {formatDateTime room.created}
{if room.archived
<>
<br/>archived by {room.archiver?.name ? 'unknown'}
<br/>on {formatDateTime room.archived}
</>
}
</Tooltip>
iconFactory = (node) -> # eslint-disable-line react/display-name
<OverlayTrigger placement="bottom" overlay={tooltip node}>
{if node.getComponent() == 'ChatRoom'
<FontAwesomeIcon icon={faComment}/>
else if node.getComponent() == 'Welcome'
<FontAwesomeIcon icon={faQuestion}/>
else
<FontAwesomeIcon icon={faDoorOpen}/>
}
</OverlayTrigger>
onRenderTab = (node, renderState) ->
type = if node.getParent().getType() == 'border' then 'border' else 'tab'
buttons = renderState.buttons
if node.getComponent() == 'RoomList'
buttons?.push \
<div key="link"
className="flexlayout__#{type}_button_trailing"
aria-label="Save meeting link to clipboard"
onClick={-> navigator.clipboard.writeText \
Meteor.absoluteUrl "/m/#{meetingId}"}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>Save meeting link to clipboard</Tooltip>
}>
<FontAwesomeIcon icon={clipboardLink}/>
</OverlayTrigger>
</div>
else if node.getComponent() == 'ChatRoom'
return ChatRoom.onRenderTab node, renderState
return if node.getComponent() != 'Room'
room = id2room[node.getId()]
return unless room
className = 'tab-title'
className += ' archived' if room.archived
renderState.content =
<OverlayTrigger placement="bottom" overlay={tooltip node}>
<span className={className}>{renderState.content}</span>
</OverlayTrigger>
if node.isVisible() # special buttons for visible tabs
id = node.getId()
buttons?.push \
<div key="link"
className="flexlayout__#{type}_button_trailing flexlayout__tab_button_link"
aria-label="Save room link to clipboard"
onClick={-> navigator.clipboard.writeText \
Meteor.absoluteUrl "/m/#{meetingId}##{node.getId()}"}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>Save room link to clipboard</Tooltip>
}>
<FontAwesomeIcon icon={clipboardLink}/>
</OverlayTrigger>
</div>
showArchived = node.getConfig()?.showArchived
label =
if showArchived
"Hide Archived Tabs"
else
"Show Archived Tabs"
buttons?.push \
<div key="archived"
className="flexlayout__#{type}_button_trailing"
aria-label={label}
onClick={-> setShowArchived {id, value: not showArchived}}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>
{label}<br/>
<small>Currently {unless showArchived then <b>not</b>} showing archived tabs.</small>
</Tooltip>
}>
<FontAwesomeIcon icon={if showArchived then faEye else faEyeSlash}/>
</OverlayTrigger>
</div>
archiveRoom = ->
Meteor.call 'roomEdit',
id: room._id
archived: not room.archived
updator: getCreator()
if room = id2room[id]
buttons?.push <ArchiveButton key="archive" type={type} noun="room"
archived={room.archived} onClick={archiveRoom}
help="Archived rooms can still be viewed and restored from the list at the bottom."
/>
<MeetingContext.Provider value={{openRoom}}>
<FlexLayout.Layout model={model} factory={factory} iconFactory={iconFactory}
onRenderTab={onRenderTab}
onAction={onAction} onModelChange={-> setTimeout onModelChange, 0}
tabPhrase="room"/>
</MeetingContext.Provider>
Meeting.displayName = 'Meeting'
| true | import React, {useState, useEffect, useReducer, useMemo} from 'react'
import {useParams, useLocation, useHistory} from 'react-router-dom'
import {Tooltip, OverlayTrigger} from 'react-bootstrap'
import {Session} from 'meteor/session'
import {useTracker} from 'meteor/react-meteor-data'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faComment, faDoorOpen, faEye, faEyeSlash, faQuestion} from '@fortawesome/free-solid-svg-icons'
import {clipboardLink} from './icons/clipboardLink'
import FlexLayout from './FlexLayout'
import {ArchiveButton} from './ArchiveButton'
import {ChatRoom} from './ChatRoom'
import {RoomList} from './RoomList'
import {Room} from './Room'
import {Rooms} from '/lib/rooms'
import {Welcome} from './Welcome'
import {Presence} from '/lib/presence'
import {validId} from '/lib/id'
import {getPresenceId, getCreator} from './lib/presenceId'
import {useIdMap} from './lib/useIdMap'
import {formatDateTime} from './lib/dates'
export MeetingContext = React.createContext {}
initModel = ->
model = FlexLayout.Model.fromJson
global: Object.assign {}, FlexLayout.defaultGlobal,
borderEnableDrop: false
borders: [
type: 'border'
location: 'left'
selected: 0
children: [
id: 'roomsTab'
type: 'tab'
name: "Meeting Rooms"
component: 'RoomList'
enableClose: false
enableDrag: false
,
id: 'chat'
type: 'tab'
name: "Meeting Chat"
component: 'ChatRoom'
enableClose: false
enableDrag: false
enableRenderOnDemand: false
]
]
layout:
id: 'root'
type: 'row'
weight: 100
children: [
id: 'mainTabset'
type: 'tabset'
children: [
id: 'welcome'
type: 'tab'
name: 'Welcome'
component: 'Welcome'
]
]
model.setOnAllowDrop (dragNode, dropInfo) ->
return false if dropInfo.node.getId() == 'roomsTabSet' and dropInfo.location != FlexLayout.DockLocation.RIGHT
#return false if dropInfo.node.getType() == 'border'
#return false if dragNode.getParent()?.getType() == 'border'
true
model
export Meeting = ->
{meetingId} = useParams()
[model, setModel] = useState initModel
location = useLocation()
history = useHistory()
{loading, rooms} = useTracker ->
sub = Meteor.subscribe 'meeting', meetingId
loading: not sub.ready()
rooms: Rooms.find().fetch()
id2room = useIdMap rooms
useEffect ->
for room in rooms
if model.getNodeById room._id
model.doAction FlexLayout.Actions.updateNodeAttributes room._id,
name: room.title
undefined
, [rooms]
openRoom = useMemo -> (id, focus = true) ->
tabset = FlexLayout.getActiveTabset model
unless model.getNodeById id
tab =
id: id
type: 'tab'
name: Rooms.findOne(id)?.title ? id
component: 'Room'
config: showArchived: false
model.doAction FlexLayout.Actions.addNode tab,
tabset.getId(), FlexLayout.DockLocation.CENTER, -1, focus
else
FlexLayout.forceSelectTab model, id
useEffect ->
if location.hash and validId id = location.hash[1..]
openRoom id
undefined
, [location.hash]
[showArchived, setShowArchived] = useReducer(
(state, {id, value}) ->
if model.getNodeById id
model.doAction FlexLayout.Actions.updateNodeAttributes id,
config: showArchived: value
state[id] = value
state
, {})
presenceId = getPresenceId()
name = useTracker -> Session.get 'name'
updatePresence = ->
return unless name? # wait for tracker to load name
presence =
id: presenceId
meeting: meetingId
name: PI:NAME:<NAME>END_PI
rooms:
visible: []
invisible: []
model.visitNodes (node) ->
if node.getType() == 'tab' and node.getComponent() == 'Room'
if node.isVisible()
presence.rooms.visible.push node.getId()
else
presence.rooms.invisible.push node.getId()
current = Presence.findOne
id: presenceId
meeting: meetingId
unless current? and current.name == presence.name and
current?.rooms?.visible?.toString?() ==
presence.rooms.visible.toString() and
current?.rooms?.invisible?.toString?() ==
presence.rooms.invisible.toString()
Meteor.call 'presenceUpdate', presence
## Send presence when name changes or when we reconnect to server
## (so server may have deleted our presence information).
useEffect updatePresence, [name]
useTracker -> updatePresence() if Meteor.status().connected
onAction = (action) ->
switch action.type
when FlexLayout.Actions.RENAME_TAB
## Sanitize room title and push to other users
action.data.text = action.data.text.trim()
return unless action.data.text # prevent empty title
Meteor.call 'roomEdit',
id: action.data.node
title: action.data.text
updator: getCreator()
action
onModelChange = ->
updatePresence()
## Maintain hash part of URL to point to "current" tab.
tabset = FlexLayout.getActiveTabset model
tab = tabset?.getSelectedNode()
if tab?.getComponent() == 'Room'
unless location.hash == "##{tab.getId()}"
history.replace "/m/#{meetingId}##{tab.getId()}"
Session.set 'currentRoom', tab.getId()
else
if location.hash
history.replace "/m/#{meetingId}"
Session.set 'currentRoom', undefined
factory = (node) -> # eslint-disable-line react/display-name
switch node.getComponent()
when 'RoomList'
<RoomList loading={loading} model={model}/>
when 'ChatRoom'
<ChatRoom channel={meetingId} audience="everyone"
visible={node.isVisible()} extraData={node.getExtraData()}
updateTab={-> FlexLayout.updateNode model, node.getId()}/>
when 'Welcome'
<Welcome/>
when 'Room'
if node.isVisible()
<Room loading={loading} roomId={node.getId()} {...node.getConfig()}/>
else
null # don't render hidden rooms, in particular to cancel all calls
tooltip = (node) -> (props) -> # eslint-disable-line react/display-name
room = id2room[node.getId()]
return <span/> unless room
<Tooltip {...props}>
Room “{room.title}”<br/>
created by {room.creator?.name ? 'unknown'}<br/>
on {formatDateTime room.created}
{if room.archived
<>
<br/>archived by {room.archiver?.name ? 'unknown'}
<br/>on {formatDateTime room.archived}
</>
}
</Tooltip>
iconFactory = (node) -> # eslint-disable-line react/display-name
<OverlayTrigger placement="bottom" overlay={tooltip node}>
{if node.getComponent() == 'ChatRoom'
<FontAwesomeIcon icon={faComment}/>
else if node.getComponent() == 'Welcome'
<FontAwesomeIcon icon={faQuestion}/>
else
<FontAwesomeIcon icon={faDoorOpen}/>
}
</OverlayTrigger>
onRenderTab = (node, renderState) ->
type = if node.getParent().getType() == 'border' then 'border' else 'tab'
buttons = renderState.buttons
if node.getComponent() == 'RoomList'
buttons?.push \
<div key="link"
className="flexlayout__#{type}_button_trailing"
aria-label="Save meeting link to clipboard"
onClick={-> navigator.clipboard.writeText \
Meteor.absoluteUrl "/m/#{meetingId}"}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>Save meeting link to clipboard</Tooltip>
}>
<FontAwesomeIcon icon={clipboardLink}/>
</OverlayTrigger>
</div>
else if node.getComponent() == 'ChatRoom'
return ChatRoom.onRenderTab node, renderState
return if node.getComponent() != 'Room'
room = id2room[node.getId()]
return unless room
className = 'tab-title'
className += ' archived' if room.archived
renderState.content =
<OverlayTrigger placement="bottom" overlay={tooltip node}>
<span className={className}>{renderState.content}</span>
</OverlayTrigger>
if node.isVisible() # special buttons for visible tabs
id = node.getId()
buttons?.push \
<div key="link"
className="flexlayout__#{type}_button_trailing flexlayout__tab_button_link"
aria-label="Save room link to clipboard"
onClick={-> navigator.clipboard.writeText \
Meteor.absoluteUrl "/m/#{meetingId}##{node.getId()}"}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>Save room link to clipboard</Tooltip>
}>
<FontAwesomeIcon icon={clipboardLink}/>
</OverlayTrigger>
</div>
showArchived = node.getConfig()?.showArchived
label =
if showArchived
"Hide Archived Tabs"
else
"Show Archived Tabs"
buttons?.push \
<div key="archived"
className="flexlayout__#{type}_button_trailing"
aria-label={label}
onClick={-> setShowArchived {id, value: not showArchived}}
onMouseDown={(e) -> e.stopPropagation()}
onTouchStart={(e) -> e.stopPropagation()}>
<OverlayTrigger placement="bottom" overlay={(props) ->
<Tooltip {...props}>
{label}<br/>
<small>Currently {unless showArchived then <b>not</b>} showing archived tabs.</small>
</Tooltip>
}>
<FontAwesomeIcon icon={if showArchived then faEye else faEyeSlash}/>
</OverlayTrigger>
</div>
archiveRoom = ->
Meteor.call 'roomEdit',
id: room._id
archived: not room.archived
updator: getCreator()
if room = id2room[id]
buttons?.push <ArchiveButton key="archive" type={type} noun="room"
archived={room.archived} onClick={archiveRoom}
help="Archived rooms can still be viewed and restored from the list at the bottom."
/>
<MeetingContext.Provider value={{openRoom}}>
<FlexLayout.Layout model={model} factory={factory} iconFactory={iconFactory}
onRenderTab={onRenderTab}
onAction={onAction} onModelChange={-> setTimeout onModelChange, 0}
tabPhrase="room"/>
</MeetingContext.Provider>
Meeting.displayName = 'Meeting'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.