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": "# Description:\n# Random sized picture of Kevin Spacey on demand\n#\n# Commands\n# spacey me\n\nsizes = [1",
"end": 55,
"score": 0.985482394695282,
"start": 43,
"tag": "NAME",
"value": "Kevin Spacey"
}
] | src/spacey.coffee | ChrisMissal/hubot-spacey | 0 | # Description:
# Random sized picture of Kevin Spacey on demand
#
# Commands
# spacey me
sizes = [100...500]
module.exports = (robot) ->
robot.respond /spacey me/i, (msg) ->
height = msg.random sizes
width = msg.random sizes
msg.send "http://kevinspacer.com/#{width}/#{height}#.png"
| 65848 | # Description:
# Random sized picture of <NAME> on demand
#
# Commands
# spacey me
sizes = [100...500]
module.exports = (robot) ->
robot.respond /spacey me/i, (msg) ->
height = msg.random sizes
width = msg.random sizes
msg.send "http://kevinspacer.com/#{width}/#{height}#.png"
| true | # Description:
# Random sized picture of PI:NAME:<NAME>END_PI on demand
#
# Commands
# spacey me
sizes = [100...500]
module.exports = (robot) ->
robot.respond /spacey me/i, (msg) ->
height = msg.random sizes
width = msg.random sizes
msg.send "http://kevinspacer.com/#{width}/#{height}#.png"
|
[
{
"context": "LED = 'true'\n process.env.RADBUS_API_KEYS = '1234,4321'\n\n afterEach ->\n delete process.env.RADBU",
"end": 1051,
"score": 0.9964066743850708,
"start": 1042,
"tag": "KEY",
"value": "1234,4321"
},
{
"context": " .get('/routes')\n .headers('API-Key': 'bar-token')\n\n helpers.assert401WithInvalidApiKeyHeader",
"end": 1465,
"score": 0.973353385925293,
"start": 1456,
"tag": "KEY",
"value": "bar-token"
},
{
"context": " .get('/routes')\n .headers('API-Key': '4321')\n .json(true)\n .expect(200)\n ",
"end": 1675,
"score": 0.997978925704956,
"start": 1671,
"tag": "KEY",
"value": "4321"
}
] | test/lib/test-server.coffee | twistedstream/radbus-api | 2 | # coffeelint: disable=max_line_length
chai = require 'chai'
chai.use require 'chai-as-promised'
should = chai.should()
request = require 'super-request'
helpers = require '../api/helpers'
Q = require 'q'
# stub dependencies
routeData =
fetchAll: ->
Q [
{ id: '123', description: 'Route 123' },
{ id: '456', description: 'Route 456' }
]
'@noCallThru': true
# build server
server = helpers.buildServer '../../api/resources/route',
'../../data/route': routeData
describe "lib/server", ->
describe "API key checking disabled", ->
beforeEach ->
process.env.RADBUS_API_KEYS_ENABLED = 'false'
afterEach ->
delete process.env.RADBUS_API_KEYS_ENABLED
it "should return 200 with the expected routes", ->
request(server)
.get('/routes')
.json(true)
.expect(200)
.expect('Content-Type', /json/)
.end()
describe "API key checking enabled", ->
beforeEach ->
process.env.RADBUS_API_KEYS_ENABLED = 'true'
process.env.RADBUS_API_KEYS = '1234,4321'
afterEach ->
delete process.env.RADBUS_API_KEYS_ENABLED
delete process.env.RADBUS_API_KEYS
it "should return 401 if the API key is missing", ->
r = request(server)
.get('/routes')
helpers.assert401WithMissingApiKeyHeader r
it "should return 401 if the API key is invalid", ->
r = request(server)
.get('/routes')
.headers('API-Key': 'bar-token')
helpers.assert401WithInvalidApiKeyHeader r
it "should return 200 with the expected routes if API key is valid", ->
request(server)
.get('/routes')
.headers('API-Key': '4321')
.json(true)
.expect(200)
.expect('Content-Type', /json/)
.end()
| 162598 | # coffeelint: disable=max_line_length
chai = require 'chai'
chai.use require 'chai-as-promised'
should = chai.should()
request = require 'super-request'
helpers = require '../api/helpers'
Q = require 'q'
# stub dependencies
routeData =
fetchAll: ->
Q [
{ id: '123', description: 'Route 123' },
{ id: '456', description: 'Route 456' }
]
'@noCallThru': true
# build server
server = helpers.buildServer '../../api/resources/route',
'../../data/route': routeData
describe "lib/server", ->
describe "API key checking disabled", ->
beforeEach ->
process.env.RADBUS_API_KEYS_ENABLED = 'false'
afterEach ->
delete process.env.RADBUS_API_KEYS_ENABLED
it "should return 200 with the expected routes", ->
request(server)
.get('/routes')
.json(true)
.expect(200)
.expect('Content-Type', /json/)
.end()
describe "API key checking enabled", ->
beforeEach ->
process.env.RADBUS_API_KEYS_ENABLED = 'true'
process.env.RADBUS_API_KEYS = '<KEY>'
afterEach ->
delete process.env.RADBUS_API_KEYS_ENABLED
delete process.env.RADBUS_API_KEYS
it "should return 401 if the API key is missing", ->
r = request(server)
.get('/routes')
helpers.assert401WithMissingApiKeyHeader r
it "should return 401 if the API key is invalid", ->
r = request(server)
.get('/routes')
.headers('API-Key': '<KEY>')
helpers.assert401WithInvalidApiKeyHeader r
it "should return 200 with the expected routes if API key is valid", ->
request(server)
.get('/routes')
.headers('API-Key': '<KEY>')
.json(true)
.expect(200)
.expect('Content-Type', /json/)
.end()
| true | # coffeelint: disable=max_line_length
chai = require 'chai'
chai.use require 'chai-as-promised'
should = chai.should()
request = require 'super-request'
helpers = require '../api/helpers'
Q = require 'q'
# stub dependencies
routeData =
fetchAll: ->
Q [
{ id: '123', description: 'Route 123' },
{ id: '456', description: 'Route 456' }
]
'@noCallThru': true
# build server
server = helpers.buildServer '../../api/resources/route',
'../../data/route': routeData
describe "lib/server", ->
describe "API key checking disabled", ->
beforeEach ->
process.env.RADBUS_API_KEYS_ENABLED = 'false'
afterEach ->
delete process.env.RADBUS_API_KEYS_ENABLED
it "should return 200 with the expected routes", ->
request(server)
.get('/routes')
.json(true)
.expect(200)
.expect('Content-Type', /json/)
.end()
describe "API key checking enabled", ->
beforeEach ->
process.env.RADBUS_API_KEYS_ENABLED = 'true'
process.env.RADBUS_API_KEYS = 'PI:KEY:<KEY>END_PI'
afterEach ->
delete process.env.RADBUS_API_KEYS_ENABLED
delete process.env.RADBUS_API_KEYS
it "should return 401 if the API key is missing", ->
r = request(server)
.get('/routes')
helpers.assert401WithMissingApiKeyHeader r
it "should return 401 if the API key is invalid", ->
r = request(server)
.get('/routes')
.headers('API-Key': 'PI:KEY:<KEY>END_PI')
helpers.assert401WithInvalidApiKeyHeader r
it "should return 200 with the expected routes if API key is valid", ->
request(server)
.get('/routes')
.headers('API-Key': 'PI:KEY:<KEY>END_PI')
.json(true)
.expect(200)
.expect('Content-Type', /json/)
.end()
|
[
{
"context": "NAME = <user name>\n# HUBOT_YOUTRACK_PASSWORD = <password>\n# HUBOT_YOUTRACK_URL = <scheme>://<userna",
"end": 275,
"score": 0.7296018004417419,
"start": 267,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "sponds with a summary of the issue\n#\n# Author:\n# Dusty Burwell, Jeremy Sellars and Jens Jahnke\n\nURL = require \"u",
"end": 561,
"score": 0.999858558177948,
"start": 548,
"tag": "NAME",
"value": "Dusty Burwell"
},
{
"context": "ummary of the issue\n#\n# Author:\n# Dusty Burwell, Jeremy Sellars and Jens Jahnke\n\nURL = require \"url\"\n\nhttp = requ",
"end": 577,
"score": 0.9998570680618286,
"start": 563,
"tag": "NAME",
"value": "Jeremy Sellars"
},
{
"context": "\n#\n# Author:\n# Dusty Burwell, Jeremy Sellars and Jens Jahnke\n\nURL = require \"url\"\n\nhttp = require 'http'\nhttps",
"end": 593,
"score": 0.999852180480957,
"start": 582,
"tag": "NAME",
"value": "Jens Jahnke"
},
{
"context": "e = process.env.HUBOT_YOUTRACK_USERNAME\npassword = process.env.HUBOT_YOUTRACK_PASSWORD\n\nif yt_url?\n url_parts = URL.parse(yt_url)\n sch",
"end": 845,
"score": 0.9730597734451294,
"start": 810,
"tag": "PASSWORD",
"value": "process.env.HUBOT_YOUTRACK_PASSWORD"
},
{
"context": ") ->\n user = msg.message.user.name\n user = 'me' if user = \"Shell\"\n user\n\n askYoutrack = (pat",
"end": 4031,
"score": 0.7809549570083618,
"start": 4029,
"tag": "USERNAME",
"value": "me"
},
{
"context": " msg.message.user.name\n user = 'me' if user = \"Shell\"\n user\n\n askYoutrack = (path, callback) ->\n ",
"end": 4049,
"score": 0.6208385825157166,
"start": 4044,
"tag": "USERNAME",
"value": "Shell"
},
{
"context": " host: host\n path: \"/rest/user/login?login=#{username}&password=#{password}\",\n method: \"POST\"\n ",
"end": 5068,
"score": 0.9950479865074158,
"start": 5060,
"tag": "USERNAME",
"value": "username"
},
{
"context": "h: \"/rest/user/login?login=#{username}&password=#{password}\",\n method: \"POST\"\n }\n options.path = ",
"end": 5089,
"score": 0.9892971515655518,
"start": 5081,
"tag": "PASSWORD",
"value": "password"
}
] | src/scripts/youtrack.coffee | contolini/hubot-scripts | 1,450 | # Description:
# Listens for patterns matching youtrack issues and provides information about
# them
#
# Dependencies:
# url
#
# Configuration:
# HUBOT_YOUTRACK_HOSTNAME = <host:port>
# HUBOT_YOUTRACK_USERNAME = <user name>
# HUBOT_YOUTRACK_PASSWORD = <password>
# HUBOT_YOUTRACK_URL = <scheme>://<username>:<password>@<host:port>/<basepath>
#
# Commands:
# what are my issues? - Show my in progress issues
# what can I work on? - Show open issues
# #project-number - responds with a summary of the issue
#
# Author:
# Dusty Burwell, Jeremy Sellars and Jens Jahnke
URL = require "url"
http = require 'http'
https = require 'https'
yt_url = process.env.HUBOT_YOUTRACK_URL
host = process.env.HUBOT_YOUTRACK_HOSTNAME
username = process.env.HUBOT_YOUTRACK_USERNAME
password = process.env.HUBOT_YOUTRACK_PASSWORD
if yt_url?
url_parts = URL.parse(yt_url)
scheme = url_parts.protocol
username = url_parts.auth.split(":")[0]
password = url_parts.auth.split(":")[1]
host = url_parts.host
path = url_parts.pathname if url_parts.pathname?
else
scheme = 'http://'
# http://en.wikipedia.org/wiki/You_talkin'_to_me%3F
youTalkinToMe = (msg, robot) ->
input = msg.message.text.toLowerCase()
name = robot.name.toLowerCase()
input.indexOf(name) != -1
getProject = (msg) ->
s = msg.message.room.replace /-.*/, ''
module.exports = (robot) ->
robot.hear /what (are )?my issues/i, (msg) ->
msg.send "@#{msg.message.user.name}, you have many issues. Shall I enumerate them? I think not." if Math.random() < .2
robot.hear /what ((are )?my issues|am I (doing|working on|assigned))/i, (msg) ->
return unless youTalkinToMe msg, robot
filter = "for:+#{getUserNameFromMessage(msg)}+state:-Resolved,%20-Completed,%20-Blocked%20,%20-{To%20be%20discussed}"
askYoutrack "/rest/issue?filter=#{filter}&with=summary&with=state", (err, issues) ->
handleIssues err, issues, msg, filter
robot.hear /what (can|might|should)\s+(I|we)\s+(do|work on)/i, (msg) ->
return unless youTalkinToMe msg, robot
filter = "Project%3a%20#{getProject(msg)}%20state:-Resolved,%20-Completed,%20-Blocked%20,%20-{To%20be%20discussed}"
askYoutrack "/rest/issue?filter=#{filter}&with=summary&with=state&max=100", (err, issues) ->
handleIssues err, issues, msg, filter
hashTagYoutrackIssueNumber = /#([^-]+-[\d]+)/i
robot.hear hashTagYoutrackIssueNumber, (msg) ->
issueId = msg.match[1]
askYoutrack "/rest/issue/#{issueId}", (err, issue) ->
return msg.send "I'd love to tell you about it, but there was an error looking up that issue" if err?
if issue.field
summary = field.value for field in issue.field when field.name == 'summary'
msg.send "You're talking about #{scheme}#{host}/issue/#{issueId}\r\nsummary: #{summary}"
else
msg.send "I'd love to tell you about it, but I couldn't find that issue"
handleIssues = (err, issues, msg, filter) ->
msg.send if err?
'Not to whine, but\r\n' + err.toString()
else if not issues.issue.length
"#{msg.message.user.name}, I guess you get to go home because there's nothing to do"
else
topIssues = if issues.issue.length <= 5 then issues.issue else issues.issue.slice 0, 5
resp = "#{msg.message.user.name}, perhaps you will find one of these #{topIssues} #{getProject(msg)} issues to your liking:\r\n"
issueLines = for issue in topIssues
summary = issue.field[0].value
state = issue.field[1].value
issueId = issue.id
verb = (if state.toString() == "Open" then "Start" else "Finish")
"#{verb} \"#{summary}\" (#{scheme}#{host}/issue/#{issueId})"
resp += issueLines.join ',\r\nor maybe '
if topIssues.length != issues.issue.length
url = "#{scheme}#{host}/issues/?q=#{filter}"
resp+= '\r\n' + "or maybe these #{issues.issue.length}: #{url}"
resp
getUserNameFromMessage = (msg) ->
user = msg.message.user.name
user = 'me' if user = "Shell"
user
askYoutrack = (path, callback) ->
login (login_res) ->
cookies = (cookie.split(';')[0] for cookie in login_res.headers['set-cookie'])
ask_options = {
host: host,
path: path,
headers: {
Cookie: cookies,
Accept: 'application/json'
}
}
ask_options.path = path + ask_options.path if path?
ask_res ->
data = ''
ask_res.on 'data', (chunk) ->
data += chunk
ask_res.on 'end', () ->
answer = JSON.parse data
callback null, answer
ask_res.on 'error', (err) ->
callback err ? new Error 'Error getting answer from youtrack'
if scheme == 'https://'
ask_req = https.get ask_options, ask_res
else
ask_req = http.get ask_options, ask_res
ask_req.on 'error', (e) ->
callback e ? new Error 'Error asking youtrack'
login = (handler) ->
options = {
host: host
path: "/rest/user/login?login=#{username}&password=#{password}",
method: "POST"
}
options.path = path + options.path if path?
if scheme == 'https://'
login_req = https.request options, handler
else
login_req = http.request options, handler
login_req.end()
| 179580 | # Description:
# Listens for patterns matching youtrack issues and provides information about
# them
#
# Dependencies:
# url
#
# Configuration:
# HUBOT_YOUTRACK_HOSTNAME = <host:port>
# HUBOT_YOUTRACK_USERNAME = <user name>
# HUBOT_YOUTRACK_PASSWORD = <<PASSWORD>>
# HUBOT_YOUTRACK_URL = <scheme>://<username>:<password>@<host:port>/<basepath>
#
# Commands:
# what are my issues? - Show my in progress issues
# what can I work on? - Show open issues
# #project-number - responds with a summary of the issue
#
# Author:
# <NAME>, <NAME> and <NAME>
URL = require "url"
http = require 'http'
https = require 'https'
yt_url = process.env.HUBOT_YOUTRACK_URL
host = process.env.HUBOT_YOUTRACK_HOSTNAME
username = process.env.HUBOT_YOUTRACK_USERNAME
password = <PASSWORD>
if yt_url?
url_parts = URL.parse(yt_url)
scheme = url_parts.protocol
username = url_parts.auth.split(":")[0]
password = url_parts.auth.split(":")[1]
host = url_parts.host
path = url_parts.pathname if url_parts.pathname?
else
scheme = 'http://'
# http://en.wikipedia.org/wiki/You_talkin'_to_me%3F
youTalkinToMe = (msg, robot) ->
input = msg.message.text.toLowerCase()
name = robot.name.toLowerCase()
input.indexOf(name) != -1
getProject = (msg) ->
s = msg.message.room.replace /-.*/, ''
module.exports = (robot) ->
robot.hear /what (are )?my issues/i, (msg) ->
msg.send "@#{msg.message.user.name}, you have many issues. Shall I enumerate them? I think not." if Math.random() < .2
robot.hear /what ((are )?my issues|am I (doing|working on|assigned))/i, (msg) ->
return unless youTalkinToMe msg, robot
filter = "for:+#{getUserNameFromMessage(msg)}+state:-Resolved,%20-Completed,%20-Blocked%20,%20-{To%20be%20discussed}"
askYoutrack "/rest/issue?filter=#{filter}&with=summary&with=state", (err, issues) ->
handleIssues err, issues, msg, filter
robot.hear /what (can|might|should)\s+(I|we)\s+(do|work on)/i, (msg) ->
return unless youTalkinToMe msg, robot
filter = "Project%3a%20#{getProject(msg)}%20state:-Resolved,%20-Completed,%20-Blocked%20,%20-{To%20be%20discussed}"
askYoutrack "/rest/issue?filter=#{filter}&with=summary&with=state&max=100", (err, issues) ->
handleIssues err, issues, msg, filter
hashTagYoutrackIssueNumber = /#([^-]+-[\d]+)/i
robot.hear hashTagYoutrackIssueNumber, (msg) ->
issueId = msg.match[1]
askYoutrack "/rest/issue/#{issueId}", (err, issue) ->
return msg.send "I'd love to tell you about it, but there was an error looking up that issue" if err?
if issue.field
summary = field.value for field in issue.field when field.name == 'summary'
msg.send "You're talking about #{scheme}#{host}/issue/#{issueId}\r\nsummary: #{summary}"
else
msg.send "I'd love to tell you about it, but I couldn't find that issue"
handleIssues = (err, issues, msg, filter) ->
msg.send if err?
'Not to whine, but\r\n' + err.toString()
else if not issues.issue.length
"#{msg.message.user.name}, I guess you get to go home because there's nothing to do"
else
topIssues = if issues.issue.length <= 5 then issues.issue else issues.issue.slice 0, 5
resp = "#{msg.message.user.name}, perhaps you will find one of these #{topIssues} #{getProject(msg)} issues to your liking:\r\n"
issueLines = for issue in topIssues
summary = issue.field[0].value
state = issue.field[1].value
issueId = issue.id
verb = (if state.toString() == "Open" then "Start" else "Finish")
"#{verb} \"#{summary}\" (#{scheme}#{host}/issue/#{issueId})"
resp += issueLines.join ',\r\nor maybe '
if topIssues.length != issues.issue.length
url = "#{scheme}#{host}/issues/?q=#{filter}"
resp+= '\r\n' + "or maybe these #{issues.issue.length}: #{url}"
resp
getUserNameFromMessage = (msg) ->
user = msg.message.user.name
user = 'me' if user = "Shell"
user
askYoutrack = (path, callback) ->
login (login_res) ->
cookies = (cookie.split(';')[0] for cookie in login_res.headers['set-cookie'])
ask_options = {
host: host,
path: path,
headers: {
Cookie: cookies,
Accept: 'application/json'
}
}
ask_options.path = path + ask_options.path if path?
ask_res ->
data = ''
ask_res.on 'data', (chunk) ->
data += chunk
ask_res.on 'end', () ->
answer = JSON.parse data
callback null, answer
ask_res.on 'error', (err) ->
callback err ? new Error 'Error getting answer from youtrack'
if scheme == 'https://'
ask_req = https.get ask_options, ask_res
else
ask_req = http.get ask_options, ask_res
ask_req.on 'error', (e) ->
callback e ? new Error 'Error asking youtrack'
login = (handler) ->
options = {
host: host
path: "/rest/user/login?login=#{username}&password=#{<PASSWORD>}",
method: "POST"
}
options.path = path + options.path if path?
if scheme == 'https://'
login_req = https.request options, handler
else
login_req = http.request options, handler
login_req.end()
| true | # Description:
# Listens for patterns matching youtrack issues and provides information about
# them
#
# Dependencies:
# url
#
# Configuration:
# HUBOT_YOUTRACK_HOSTNAME = <host:port>
# HUBOT_YOUTRACK_USERNAME = <user name>
# HUBOT_YOUTRACK_PASSWORD = <PI:PASSWORD:<PASSWORD>END_PI>
# HUBOT_YOUTRACK_URL = <scheme>://<username>:<password>@<host:port>/<basepath>
#
# Commands:
# what are my issues? - Show my in progress issues
# what can I work on? - Show open issues
# #project-number - responds with a summary of the issue
#
# Author:
# PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI
URL = require "url"
http = require 'http'
https = require 'https'
yt_url = process.env.HUBOT_YOUTRACK_URL
host = process.env.HUBOT_YOUTRACK_HOSTNAME
username = process.env.HUBOT_YOUTRACK_USERNAME
password = PI:PASSWORD:<PASSWORD>END_PI
if yt_url?
url_parts = URL.parse(yt_url)
scheme = url_parts.protocol
username = url_parts.auth.split(":")[0]
password = url_parts.auth.split(":")[1]
host = url_parts.host
path = url_parts.pathname if url_parts.pathname?
else
scheme = 'http://'
# http://en.wikipedia.org/wiki/You_talkin'_to_me%3F
youTalkinToMe = (msg, robot) ->
input = msg.message.text.toLowerCase()
name = robot.name.toLowerCase()
input.indexOf(name) != -1
getProject = (msg) ->
s = msg.message.room.replace /-.*/, ''
module.exports = (robot) ->
robot.hear /what (are )?my issues/i, (msg) ->
msg.send "@#{msg.message.user.name}, you have many issues. Shall I enumerate them? I think not." if Math.random() < .2
robot.hear /what ((are )?my issues|am I (doing|working on|assigned))/i, (msg) ->
return unless youTalkinToMe msg, robot
filter = "for:+#{getUserNameFromMessage(msg)}+state:-Resolved,%20-Completed,%20-Blocked%20,%20-{To%20be%20discussed}"
askYoutrack "/rest/issue?filter=#{filter}&with=summary&with=state", (err, issues) ->
handleIssues err, issues, msg, filter
robot.hear /what (can|might|should)\s+(I|we)\s+(do|work on)/i, (msg) ->
return unless youTalkinToMe msg, robot
filter = "Project%3a%20#{getProject(msg)}%20state:-Resolved,%20-Completed,%20-Blocked%20,%20-{To%20be%20discussed}"
askYoutrack "/rest/issue?filter=#{filter}&with=summary&with=state&max=100", (err, issues) ->
handleIssues err, issues, msg, filter
hashTagYoutrackIssueNumber = /#([^-]+-[\d]+)/i
robot.hear hashTagYoutrackIssueNumber, (msg) ->
issueId = msg.match[1]
askYoutrack "/rest/issue/#{issueId}", (err, issue) ->
return msg.send "I'd love to tell you about it, but there was an error looking up that issue" if err?
if issue.field
summary = field.value for field in issue.field when field.name == 'summary'
msg.send "You're talking about #{scheme}#{host}/issue/#{issueId}\r\nsummary: #{summary}"
else
msg.send "I'd love to tell you about it, but I couldn't find that issue"
handleIssues = (err, issues, msg, filter) ->
msg.send if err?
'Not to whine, but\r\n' + err.toString()
else if not issues.issue.length
"#{msg.message.user.name}, I guess you get to go home because there's nothing to do"
else
topIssues = if issues.issue.length <= 5 then issues.issue else issues.issue.slice 0, 5
resp = "#{msg.message.user.name}, perhaps you will find one of these #{topIssues} #{getProject(msg)} issues to your liking:\r\n"
issueLines = for issue in topIssues
summary = issue.field[0].value
state = issue.field[1].value
issueId = issue.id
verb = (if state.toString() == "Open" then "Start" else "Finish")
"#{verb} \"#{summary}\" (#{scheme}#{host}/issue/#{issueId})"
resp += issueLines.join ',\r\nor maybe '
if topIssues.length != issues.issue.length
url = "#{scheme}#{host}/issues/?q=#{filter}"
resp+= '\r\n' + "or maybe these #{issues.issue.length}: #{url}"
resp
getUserNameFromMessage = (msg) ->
user = msg.message.user.name
user = 'me' if user = "Shell"
user
askYoutrack = (path, callback) ->
login (login_res) ->
cookies = (cookie.split(';')[0] for cookie in login_res.headers['set-cookie'])
ask_options = {
host: host,
path: path,
headers: {
Cookie: cookies,
Accept: 'application/json'
}
}
ask_options.path = path + ask_options.path if path?
ask_res ->
data = ''
ask_res.on 'data', (chunk) ->
data += chunk
ask_res.on 'end', () ->
answer = JSON.parse data
callback null, answer
ask_res.on 'error', (err) ->
callback err ? new Error 'Error getting answer from youtrack'
if scheme == 'https://'
ask_req = https.get ask_options, ask_res
else
ask_req = http.get ask_options, ask_res
ask_req.on 'error', (e) ->
callback e ? new Error 'Error asking youtrack'
login = (handler) ->
options = {
host: host
path: "/rest/user/login?login=#{username}&password=#{PI:PASSWORD:<PASSWORD>END_PI}",
method: "POST"
}
options.path = path + options.path if path?
if scheme == 'https://'
login_req = https.request options, handler
else
login_req = http.request options, handler
login_req.end()
|
[
{
"context": "maskings:\n parent: 'servers'\n key: 'maskingsnapshots'\n stores: ['snapshots']\n\n bind:\n ",
"end": 245,
"score": 0.9931385517120361,
"start": 229,
"tag": "KEY",
"value": "maskingsnapshots"
}
] | sencha/apps/cloud/coffee/app/Cloud/view/server/ListSnapshots.coffee | liverbool/c.com | 0 | Ext.define 'Magice.Cloud.view.server.ListSnapshots',
extend: 'Ext.window.Window'
xtype: 'server-list-snapshots'
width: 450
height: 300
maximizable: yes
maskings:
parent: 'servers'
key: 'maskingsnapshots'
stores: ['snapshots']
bind:
title: 'Snapshots - {server.name}'
loading: '{maskingsnapshots}'
layout: 'fit'
initComponent: ->
@editing = Ext.create 'Ext.grid.plugin.CellEditing',
listeners: edit: 'on.list.snapshots.edit'
@items =
xtype: 'grid'
reference: 'snapshotlist'
plugins: [@editing]
border: no
selModel:
allowDeselect: yes
bind:
store: '{snapshots}'
reload: '{serverselection}'
setReload: (rec) ->
@store.load parameters: id: rec.get('id')
columns: [
{
flex: 1
text: 'Name'
dataIndex: 'name'
field:
type: 'textfield'
allowBlank: no
}
{
text: 'Distribution'
dataIndex: 'distribution'
}
{
hidden: yes
text: 'Created At'
dataIndex: 'createdAt'
renderer: humanize.datetime
}
{
text: 'Created'
dataIndex: 'createdAt'
renderer: humanize.duration
}
]
# inside grid to disabled on loading
tbar: [
{
text: 'Create'
handler: 'on.action.snapshot'
glyph: Glyph.CREATE
}
{
disabled: yes
text: 'Restore'
bind: disabled: '{!snapshotlist.selection}'
glyph: Glyph.RESTORE
referer: 'snapshotlist'
handler: 'on.action.restore'
}
{
disabled: yes
text: 'Rename'
glyph: Glyph.RENAME
bind:
disabled: '{!snapshotlist.selection}'
record: '{snapshotlist.selection}'
handler: (me) =>
rec = me.getRecord()
return if !rec
@editing.cancelEdit()
@editing.startEdit rec, 0
}
{
disabled: yes
text: 'Destroy'
glyph: Glyph.DESTROY
bind: disabled: '{!snapshotlist.selection}'
referer: 'snapshotlist'
handler: 'on.action.destroyimage'
}
{
text: 'Refresh'
handler: 'on.list.snapshots.refresh'
glyph: Glyph.REFRESH
}
]
@callParent arguments | 90738 | Ext.define 'Magice.Cloud.view.server.ListSnapshots',
extend: 'Ext.window.Window'
xtype: 'server-list-snapshots'
width: 450
height: 300
maximizable: yes
maskings:
parent: 'servers'
key: '<KEY>'
stores: ['snapshots']
bind:
title: 'Snapshots - {server.name}'
loading: '{maskingsnapshots}'
layout: 'fit'
initComponent: ->
@editing = Ext.create 'Ext.grid.plugin.CellEditing',
listeners: edit: 'on.list.snapshots.edit'
@items =
xtype: 'grid'
reference: 'snapshotlist'
plugins: [@editing]
border: no
selModel:
allowDeselect: yes
bind:
store: '{snapshots}'
reload: '{serverselection}'
setReload: (rec) ->
@store.load parameters: id: rec.get('id')
columns: [
{
flex: 1
text: 'Name'
dataIndex: 'name'
field:
type: 'textfield'
allowBlank: no
}
{
text: 'Distribution'
dataIndex: 'distribution'
}
{
hidden: yes
text: 'Created At'
dataIndex: 'createdAt'
renderer: humanize.datetime
}
{
text: 'Created'
dataIndex: 'createdAt'
renderer: humanize.duration
}
]
# inside grid to disabled on loading
tbar: [
{
text: 'Create'
handler: 'on.action.snapshot'
glyph: Glyph.CREATE
}
{
disabled: yes
text: 'Restore'
bind: disabled: '{!snapshotlist.selection}'
glyph: Glyph.RESTORE
referer: 'snapshotlist'
handler: 'on.action.restore'
}
{
disabled: yes
text: 'Rename'
glyph: Glyph.RENAME
bind:
disabled: '{!snapshotlist.selection}'
record: '{snapshotlist.selection}'
handler: (me) =>
rec = me.getRecord()
return if !rec
@editing.cancelEdit()
@editing.startEdit rec, 0
}
{
disabled: yes
text: 'Destroy'
glyph: Glyph.DESTROY
bind: disabled: '{!snapshotlist.selection}'
referer: 'snapshotlist'
handler: 'on.action.destroyimage'
}
{
text: 'Refresh'
handler: 'on.list.snapshots.refresh'
glyph: Glyph.REFRESH
}
]
@callParent arguments | true | Ext.define 'Magice.Cloud.view.server.ListSnapshots',
extend: 'Ext.window.Window'
xtype: 'server-list-snapshots'
width: 450
height: 300
maximizable: yes
maskings:
parent: 'servers'
key: 'PI:KEY:<KEY>END_PI'
stores: ['snapshots']
bind:
title: 'Snapshots - {server.name}'
loading: '{maskingsnapshots}'
layout: 'fit'
initComponent: ->
@editing = Ext.create 'Ext.grid.plugin.CellEditing',
listeners: edit: 'on.list.snapshots.edit'
@items =
xtype: 'grid'
reference: 'snapshotlist'
plugins: [@editing]
border: no
selModel:
allowDeselect: yes
bind:
store: '{snapshots}'
reload: '{serverselection}'
setReload: (rec) ->
@store.load parameters: id: rec.get('id')
columns: [
{
flex: 1
text: 'Name'
dataIndex: 'name'
field:
type: 'textfield'
allowBlank: no
}
{
text: 'Distribution'
dataIndex: 'distribution'
}
{
hidden: yes
text: 'Created At'
dataIndex: 'createdAt'
renderer: humanize.datetime
}
{
text: 'Created'
dataIndex: 'createdAt'
renderer: humanize.duration
}
]
# inside grid to disabled on loading
tbar: [
{
text: 'Create'
handler: 'on.action.snapshot'
glyph: Glyph.CREATE
}
{
disabled: yes
text: 'Restore'
bind: disabled: '{!snapshotlist.selection}'
glyph: Glyph.RESTORE
referer: 'snapshotlist'
handler: 'on.action.restore'
}
{
disabled: yes
text: 'Rename'
glyph: Glyph.RENAME
bind:
disabled: '{!snapshotlist.selection}'
record: '{snapshotlist.selection}'
handler: (me) =>
rec = me.getRecord()
return if !rec
@editing.cancelEdit()
@editing.startEdit rec, 0
}
{
disabled: yes
text: 'Destroy'
glyph: Glyph.DESTROY
bind: disabled: '{!snapshotlist.selection}'
referer: 'snapshotlist'
handler: 'on.action.destroyimage'
}
{
text: 'Refresh'
handler: 'on.list.snapshots.refresh'
glyph: Glyph.REFRESH
}
]
@callParent arguments |
[
{
"context": " config and plays a random, valid move.\n\n Author: Mikolaj Pawlikowski (mikolaj@pawlikowski.pl)\n\n###\n\n\n# this is a very ",
"end": 189,
"score": 0.9998817443847656,
"start": 170,
"tag": "NAME",
"value": "Mikolaj Pawlikowski"
},
{
"context": "ndom, valid move.\n\n Author: Mikolaj Pawlikowski (mikolaj@pawlikowski.pl)\n\n###\n\n\n# this is a very simple bot, it always st",
"end": 213,
"score": 0.9999311566352844,
"start": 191,
"tag": "EMAIL",
"value": "mikolaj@pawlikowski.pl"
}
] | bot.coffee | Ribesg/battleships-bot | 0 | ###
Random bot: an example bot to illustrate how easy it is to write one.
It doesn't do much: starts with a fixed config and plays a random, valid move.
Author: Mikolaj Pawlikowski (mikolaj@pawlikowski.pl)
###
# this is a very simple bot, it always starts the same
config =
2:
point: "00"
orientation: "vertical"
3:
point: "22"
orientation: "vertical"
4:
point: "42"
orientation: "vertical"
5:
point: "37"
orientation: "horizontal"
randomMove = ->
"#{Math.round(Math.random()*7)}#{Math.round(Math.random()*7)}"
# get and parse the state
# it will be called like so:
# coffee bot.coffee "{'cmd':'init'}"
incoming = JSON.parse process.argv.slice(2)
# they want us to set up our ships
if incoming.cmd is 'init'
console.log JSON.stringify config
# otherwise, let's play!
# we should get something like this:
# {
# "cmd": "move",
#
# "moves": ["0001", "1003", "1113"], // an array representing the the sequence of moves and results (see below)
#
# "hit" : ["20", "30"], // the cells shot at and hit
# "missed" : ["44", "01"], // the cells shot at but missed
# "destroyed" : [2] // sizes (2, 3, 4, 5) of destroyed opponent's ships
# }
else
move = randomMove()
while (move in incoming.hit) or (move in incoming.missed)
move = randomMove()
console.log JSON.stringify
move: move
process.exit 0
| 18696 | ###
Random bot: an example bot to illustrate how easy it is to write one.
It doesn't do much: starts with a fixed config and plays a random, valid move.
Author: <NAME> (<EMAIL>)
###
# this is a very simple bot, it always starts the same
config =
2:
point: "00"
orientation: "vertical"
3:
point: "22"
orientation: "vertical"
4:
point: "42"
orientation: "vertical"
5:
point: "37"
orientation: "horizontal"
randomMove = ->
"#{Math.round(Math.random()*7)}#{Math.round(Math.random()*7)}"
# get and parse the state
# it will be called like so:
# coffee bot.coffee "{'cmd':'init'}"
incoming = JSON.parse process.argv.slice(2)
# they want us to set up our ships
if incoming.cmd is 'init'
console.log JSON.stringify config
# otherwise, let's play!
# we should get something like this:
# {
# "cmd": "move",
#
# "moves": ["0001", "1003", "1113"], // an array representing the the sequence of moves and results (see below)
#
# "hit" : ["20", "30"], // the cells shot at and hit
# "missed" : ["44", "01"], // the cells shot at but missed
# "destroyed" : [2] // sizes (2, 3, 4, 5) of destroyed opponent's ships
# }
else
move = randomMove()
while (move in incoming.hit) or (move in incoming.missed)
move = randomMove()
console.log JSON.stringify
move: move
process.exit 0
| true | ###
Random bot: an example bot to illustrate how easy it is to write one.
It doesn't do much: starts with a fixed config and plays a random, valid move.
Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
###
# this is a very simple bot, it always starts the same
config =
2:
point: "00"
orientation: "vertical"
3:
point: "22"
orientation: "vertical"
4:
point: "42"
orientation: "vertical"
5:
point: "37"
orientation: "horizontal"
randomMove = ->
"#{Math.round(Math.random()*7)}#{Math.round(Math.random()*7)}"
# get and parse the state
# it will be called like so:
# coffee bot.coffee "{'cmd':'init'}"
incoming = JSON.parse process.argv.slice(2)
# they want us to set up our ships
if incoming.cmd is 'init'
console.log JSON.stringify config
# otherwise, let's play!
# we should get something like this:
# {
# "cmd": "move",
#
# "moves": ["0001", "1003", "1113"], // an array representing the the sequence of moves and results (see below)
#
# "hit" : ["20", "30"], // the cells shot at and hit
# "missed" : ["44", "01"], // the cells shot at but missed
# "destroyed" : [2] // sizes (2, 3, 4, 5) of destroyed opponent's ships
# }
else
move = randomMove()
while (move in incoming.hit) or (move in incoming.missed)
move = randomMove()
console.log JSON.stringify
move: move
process.exit 0
|
[
{
"context": "credentials = {\n username: ''\n password: ''\n }\n\n $scope.closed = true\n\n $scope.toggl",
"end": 345,
"score": 0.9418572783470154,
"start": 345,
"tag": "PASSWORD",
"value": ""
}
] | app/scripts/controllers/login.coffee | MaximeMorille/BoardGamesCriticsClient | 0 | 'use strict'
###*
# @ngdoc function
# @name boardGamesCriticsClientApp.controller:LoginCtrl
# @description
# # LoginCtrl
# Controller of the boardGamesCriticsClientApp
###
angular.module('boardGamesCriticsClientApp')
.controller('LoginCtrl', ($scope, AuthService, Session) ->
$scope.credentials = {
username: ''
password: ''
}
$scope.closed = true
$scope.toggleAuthForm = () ->
$scope.closed = !$scope.closed
$scope.login = (credentials) ->
AuthService.login(credentials)
.then(
(response) ->
$scope.setCurrentUser(Session.user)
$scope.closed = true
(response) ->
# response.[config|data|headers|status|statusText]
console.log(response)
)
)
| 198222 | 'use strict'
###*
# @ngdoc function
# @name boardGamesCriticsClientApp.controller:LoginCtrl
# @description
# # LoginCtrl
# Controller of the boardGamesCriticsClientApp
###
angular.module('boardGamesCriticsClientApp')
.controller('LoginCtrl', ($scope, AuthService, Session) ->
$scope.credentials = {
username: ''
password:<PASSWORD> ''
}
$scope.closed = true
$scope.toggleAuthForm = () ->
$scope.closed = !$scope.closed
$scope.login = (credentials) ->
AuthService.login(credentials)
.then(
(response) ->
$scope.setCurrentUser(Session.user)
$scope.closed = true
(response) ->
# response.[config|data|headers|status|statusText]
console.log(response)
)
)
| true | 'use strict'
###*
# @ngdoc function
# @name boardGamesCriticsClientApp.controller:LoginCtrl
# @description
# # LoginCtrl
# Controller of the boardGamesCriticsClientApp
###
angular.module('boardGamesCriticsClientApp')
.controller('LoginCtrl', ($scope, AuthService, Session) ->
$scope.credentials = {
username: ''
password:PI:PASSWORD:<PASSWORD>END_PI ''
}
$scope.closed = true
$scope.toggleAuthForm = () ->
$scope.closed = !$scope.closed
$scope.login = (credentials) ->
AuthService.login(credentials)
.then(
(response) ->
$scope.setCurrentUser(Session.user)
$scope.closed = true
(response) ->
# response.[config|data|headers|status|statusText]
console.log(response)
)
)
|
[
{
"context": "return\n\n\nrouter.get '/auth', (req, res) ->\n key = process.env.pocket1\n codeUrl = 'https://getpocket.com/v3/oauth/reque",
"end": 281,
"score": 0.9092087149620056,
"start": 262,
"tag": "KEY",
"value": "process.env.pocket1"
},
{
"context": "'https://getpocket.com/v3/oauth/authorize'\n key = process.env.pocket1\n username = ''\n token = ''\n form = {\n cons",
"end": 1256,
"score": 0.9276737570762634,
"start": 1238,
"tag": "KEY",
"value": "process.env.pocket"
},
{
"context": "getpocket.com/v3/get'\n form = {\n consumer_key:process.env.pocket1\n access_token:''\n count:'2'\n detail",
"end": 1988,
"score": 0.6303654909133911,
"start": 1974,
"tag": "KEY",
"value": "process.env.po"
}
] | routes/index.coffee | youqingkui/read-my-pocket | 0 | express = require('express')
async = require('async')
request = require('request')
router = express.Router()
### GET home page. ###
router.get '/', (req, res, next) ->
res.render 'index', title: 'Express'
return
router.get '/auth', (req, res) ->
key = process.env.pocket1
codeUrl = 'https://getpocket.com/v3/oauth/request'
redirect_uri = process.env.pocket_url
form = {
'consumer_key':key
'redirect_uri':redirect_uri
}
op = {
url:codeUrl
form:form
}
async.auto
getCode:(cb) ->
request.post op, (err, response, body) ->
return saveErr op.url, 1, {err:err} if err
console.log "body1 ==>", body
if response.statusCode is 200
code = body.split('=')[1]
cb(null, code)
else
# saveErr op.url, 2, {err:body}
req.session.error = "连接Pocket出错"
return res.redirect('/')
directUrl:['getCode', (cb, result) ->
code = result.getCode
req.session.code = code
url = "https://getpocket.com/auth/authorize?request_token=#{code}&redirect_uri=#{redirect_uri}"
return res.redirect url
]
router.get '/oauth_callback', (req, res) ->
url = 'https://getpocket.com/v3/oauth/authorize'
key = process.env.pocket1
username = ''
token = ''
form = {
consumer_key:key
code:req.session.code
headers:{
'Content-Type': 'application/json; charset=UTF-8'
}
}
op = {
url:url
form:form
}
request.post op, (err, response, body) ->
return saveErr op.url, 1, {err:err} if err
if response.statusCode is 200
console.log "body =>", body
infoArr = body.split('&')
token = infoArr[0].split('=')[1]
username = infoArr[1].split('=')[1]
res.send "okok"
else
req.session.error = "获取pocket token 出错"
console.log token
return res.redirect('/')
router.get '/test', (req, res) ->
url = 'https://getpocket.com/v3/get'
form = {
consumer_key:process.env.pocket1
access_token:''
count:'2'
detailType:'complete'
}
op = {
url:url
form:form
}
request.post op, (err, response, body) ->
return console.log err if err
console.log body
module.exports = router | 19558 | express = require('express')
async = require('async')
request = require('request')
router = express.Router()
### GET home page. ###
router.get '/', (req, res, next) ->
res.render 'index', title: 'Express'
return
router.get '/auth', (req, res) ->
key = <KEY>
codeUrl = 'https://getpocket.com/v3/oauth/request'
redirect_uri = process.env.pocket_url
form = {
'consumer_key':key
'redirect_uri':redirect_uri
}
op = {
url:codeUrl
form:form
}
async.auto
getCode:(cb) ->
request.post op, (err, response, body) ->
return saveErr op.url, 1, {err:err} if err
console.log "body1 ==>", body
if response.statusCode is 200
code = body.split('=')[1]
cb(null, code)
else
# saveErr op.url, 2, {err:body}
req.session.error = "连接Pocket出错"
return res.redirect('/')
directUrl:['getCode', (cb, result) ->
code = result.getCode
req.session.code = code
url = "https://getpocket.com/auth/authorize?request_token=#{code}&redirect_uri=#{redirect_uri}"
return res.redirect url
]
router.get '/oauth_callback', (req, res) ->
url = 'https://getpocket.com/v3/oauth/authorize'
key = <KEY>1
username = ''
token = ''
form = {
consumer_key:key
code:req.session.code
headers:{
'Content-Type': 'application/json; charset=UTF-8'
}
}
op = {
url:url
form:form
}
request.post op, (err, response, body) ->
return saveErr op.url, 1, {err:err} if err
if response.statusCode is 200
console.log "body =>", body
infoArr = body.split('&')
token = infoArr[0].split('=')[1]
username = infoArr[1].split('=')[1]
res.send "okok"
else
req.session.error = "获取pocket token 出错"
console.log token
return res.redirect('/')
router.get '/test', (req, res) ->
url = 'https://getpocket.com/v3/get'
form = {
consumer_key:<KEY>cket1
access_token:''
count:'2'
detailType:'complete'
}
op = {
url:url
form:form
}
request.post op, (err, response, body) ->
return console.log err if err
console.log body
module.exports = router | true | express = require('express')
async = require('async')
request = require('request')
router = express.Router()
### GET home page. ###
router.get '/', (req, res, next) ->
res.render 'index', title: 'Express'
return
router.get '/auth', (req, res) ->
key = PI:KEY:<KEY>END_PI
codeUrl = 'https://getpocket.com/v3/oauth/request'
redirect_uri = process.env.pocket_url
form = {
'consumer_key':key
'redirect_uri':redirect_uri
}
op = {
url:codeUrl
form:form
}
async.auto
getCode:(cb) ->
request.post op, (err, response, body) ->
return saveErr op.url, 1, {err:err} if err
console.log "body1 ==>", body
if response.statusCode is 200
code = body.split('=')[1]
cb(null, code)
else
# saveErr op.url, 2, {err:body}
req.session.error = "连接Pocket出错"
return res.redirect('/')
directUrl:['getCode', (cb, result) ->
code = result.getCode
req.session.code = code
url = "https://getpocket.com/auth/authorize?request_token=#{code}&redirect_uri=#{redirect_uri}"
return res.redirect url
]
router.get '/oauth_callback', (req, res) ->
url = 'https://getpocket.com/v3/oauth/authorize'
key = PI:KEY:<KEY>END_PI1
username = ''
token = ''
form = {
consumer_key:key
code:req.session.code
headers:{
'Content-Type': 'application/json; charset=UTF-8'
}
}
op = {
url:url
form:form
}
request.post op, (err, response, body) ->
return saveErr op.url, 1, {err:err} if err
if response.statusCode is 200
console.log "body =>", body
infoArr = body.split('&')
token = infoArr[0].split('=')[1]
username = infoArr[1].split('=')[1]
res.send "okok"
else
req.session.error = "获取pocket token 出错"
console.log token
return res.redirect('/')
router.get '/test', (req, res) ->
url = 'https://getpocket.com/v3/get'
form = {
consumer_key:PI:KEY:<KEY>END_PIcket1
access_token:''
count:'2'
detailType:'complete'
}
op = {
url:url
form:form
}
request.post op, (err, response, body) ->
return console.log err if err
console.log body
module.exports = router |
[
{
"context": "cribe 'UserSessionsManager', ->\n\n\tbeforeEach ->\n\t\t@user =\n\t\t\t_id: \"abcd\"\n\t\t\temail: \"user@example.com\"",
"end": 263,
"score": 0.5071130990982056,
"start": 263,
"tag": "USERNAME",
"value": ""
},
{
"context": "beforeEach ->\n\t\t@user =\n\t\t\t_id: \"abcd\"\n\t\t\temail: \"user@example.com\"\n\t\t@sessionId = 'some_session_id'\n\n\t\t@rclient =\n\t",
"end": 313,
"score": 0.999919593334198,
"start": 297,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": "\texpire: sinon.stub()\n\t\t@rclient.multi.returns(@rclient)\n\t\t@rclient.get.returns(@rclient)\n\t\t@rclient.del.",
"end": 603,
"score": 0.9907939434051514,
"start": 596,
"tag": "USERNAME",
"value": "rclient"
},
{
"context": "ent.multi.returns(@rclient)\n\t\t@rclient.get.returns(@rclient)\n\t\t@rclient.del.returns(@rclient)\n\t\t@rclient.sadd",
"end": 636,
"score": 0.9553162455558777,
"start": 628,
"tag": "USERNAME",
"value": "@rclient"
},
{
"context": "lient.get.returns(@rclient)\n\t\t@rclient.del.returns(@rclient)\n\t\t@rclient.sadd.returns(@rclient)\n\t\t@rclient.sre",
"end": 669,
"score": 0.8364696502685547,
"start": 661,
"tag": "USERNAME",
"value": "@rclient"
},
{
"context": "ient.del.returns(@rclient)\n\t\t@rclient.sadd.returns(@rclient)\n\t\t@rclient.srem.returns(@rclient)\n\t\t@rclient.sme",
"end": 703,
"score": 0.9357448220252991,
"start": 695,
"tag": "USERNAME",
"value": "@rclient"
},
{
"context": "ent.sadd.returns(@rclient)\n\t\t@rclient.srem.returns(@rclient)\n\t\t@rclient.smembers.returns(@rclient)\n\t\t@rclient",
"end": 737,
"score": 0.9308724403381348,
"start": 729,
"tag": "USERNAME",
"value": "@rclient"
},
{
"context": "srem.returns(@rclient)\n\t\t@rclient.smembers.returns(@rclient)\n\t\t@rclient.expire.returns(@rclient)\n\t\t@rclient.e",
"end": 775,
"score": 0.9518337249755859,
"start": 767,
"tag": "USERNAME",
"value": "@rclient"
},
{
"context": "bers.returns(@rclient)\n\t\t@rclient.expire.returns(@rclient)\n\t\t@rclient.exec.callsArgWith(0, null)\n\n\t\t@redis ",
"end": 811,
"score": 0.9941284656524658,
"start": 804,
"tag": "USERNAME",
"value": "rclient"
},
{
"context": "->\n\t\t\tresult = @UserSessionsManager._sessionSetKey(@user)\n\t\t\tresult.should.equal 'UserSessions:abcd'\n\n\tdes",
"end": 1312,
"score": 0.6516136527061462,
"start": 1307,
"tag": "USERNAME",
"value": "@user"
},
{
"context": "essions', ->\n\n\t\tbeforeEach ->\n\t\t\t@sessionKeys = ['sess:one', 'sess:two']\n\t\t\t@retain = []\n\t\t\t@rclient.smember",
"end": 6857,
"score": 0.988431990146637,
"start": 6849,
"tag": "KEY",
"value": "sess:one"
},
{
"context": "\n\n\t\tbeforeEach ->\n\t\t\t@sessionKeys = ['sess:one', 'sess:two']\n\t\t\t@retain = []\n\t\t\t@rclient.smembers.callsArgWi",
"end": 6869,
"score": 0.950268030166626,
"start": 6861,
"tag": "KEY",
"value": "sess:two"
},
{
"context": "ained', ->\n\n\t\t\tbeforeEach ->\n\t\t\t\t@sessionKeys = ['sess:one', 'sess:two', 'sess:three', 'sess:four']\n\t\t\t\t@ret",
"end": 7775,
"score": 0.9917144775390625,
"start": 7767,
"tag": "KEY",
"value": "sess:one"
},
{
"context": "\t\t\tbeforeEach ->\n\t\t\t\t@sessionKeys = ['sess:one', 'sess:two', 'sess:three', 'sess:four']\n\t\t\t\t@retain = ['two'",
"end": 7787,
"score": 0.9777874946594238,
"start": 7779,
"tag": "KEY",
"value": "sess:two"
},
{
"context": "h ->\n\t\t\t\t@sessionKeys = ['sess:one', 'sess:two', 'sess:three', 'sess:four']\n\t\t\t\t@retain = ['two']\n\t\t\t\t@rclient",
"end": 7801,
"score": 0.9454329609870911,
"start": 7791,
"tag": "KEY",
"value": "sess:three"
},
{
"context": "ionKeys = ['sess:one', 'sess:two', 'sess:three', 'sess:four']\n\t\t\t\t@retain = ['two']\n\t\t\t\t@rclient.smembers.cal",
"end": 7814,
"score": 0.9062930941581726,
"start": 7805,
"tag": "KEY",
"value": "sess:four"
},
{
"context": "checkSessions @user, callback\n\t\t\t@sessionKeys = ['one', 'two']\n\t\t\t@rclient.smembers.callsArgWith(1, nul",
"end": 11484,
"score": 0.9937212467193604,
"start": 11481,
"tag": "KEY",
"value": "one"
},
{
"context": "Sessions @user, callback\n\t\t\t@sessionKeys = ['one', 'two']\n\t\t\t@rclient.smembers.callsArgWith(1, null, @ses",
"end": 11491,
"score": 0.8495469689369202,
"start": 11487,
"tag": "KEY",
"value": "'two"
}
] | test/UnitTests/coffee/User/UserSessionsManagerTests.coffee | bowlofstew/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserSessionsManager.js"
SandboxedModule = require('sandboxed-module')
describe 'UserSessionsManager', ->
beforeEach ->
@user =
_id: "abcd"
email: "user@example.com"
@sessionId = 'some_session_id'
@rclient =
multi: sinon.stub()
exec: sinon.stub()
get: sinon.stub()
del: sinon.stub()
sadd: sinon.stub()
srem: sinon.stub()
smembers: sinon.stub()
expire: sinon.stub()
@rclient.multi.returns(@rclient)
@rclient.get.returns(@rclient)
@rclient.del.returns(@rclient)
@rclient.sadd.returns(@rclient)
@rclient.srem.returns(@rclient)
@rclient.smembers.returns(@rclient)
@rclient.expire.returns(@rclient)
@rclient.exec.callsArgWith(0, null)
@redis =
createClient: () => @rclient
@logger =
err: sinon.stub()
error: sinon.stub()
log: sinon.stub()
@settings =
redis:
web: {}
@UserSessionsManager = SandboxedModule.require modulePath, requires:
"redis-sharelatex": @redis
"logger-sharelatex": @logger
"settings-sharelatex": @settings
describe '_sessionSetKey', ->
it 'should build the correct key', ->
result = @UserSessionsManager._sessionSetKey(@user)
result.should.equal 'UserSessions:abcd'
describe '_sessionKey', ->
it 'should build the correct key', ->
result = @UserSessionsManager._sessionKey(@sessionId)
result.should.equal 'sess:some_session_id'
describe 'trackSession', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession @user, @sessionId, callback
@rclient.exec.callsArgWith(0, null)
@_checkSessions = sinon.stub(@UserSessionsManager, '_checkSessions').returns(null)
afterEach ->
@_checkSessions.restore()
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 1
@rclient.sadd.callCount.should.equal 1
@rclient.expire.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession null, @sessionId, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.sadd.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no sessionId is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession @user, null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.sadd.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'untrackSession', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession @user, @sessionId, callback
@rclient.exec.callsArgWith(0, null)
@_checkSessions = sinon.stub(@UserSessionsManager, '_checkSessions').returns(null)
afterEach ->
@_checkSessions.restore()
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 1
@rclient.srem.callCount.should.equal 1
@rclient.expire.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession null, @sessionId, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no sessionId is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession @user, null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
##
describe 'revokeAllUserSessions', ->
beforeEach ->
@sessionKeys = ['sess:one', 'sess:two']
@retain = []
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.exec.callsArgWith(0, null)
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions @user, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 1
@rclient.del.callCount.should.equal 1
expect(@rclient.del.firstCall.args[0]).to.deep.equal @sessionKeys
@rclient.srem.callCount.should.equal 1
expect(@rclient.srem.firstCall.args[1]).to.deep.equal @sessionKeys
@rclient.exec.callCount.should.equal 1
done()
describe 'when a session is retained', ->
beforeEach ->
@sessionKeys = ['sess:one', 'sess:two', 'sess:three', 'sess:four']
@retain = ['two']
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.exec.callsArgWith(0, null)
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions @user, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 1
@rclient.del.callCount.should.equal 1
@rclient.srem.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should remove all sessions except for the retained one', (done) ->
@call (err) =>
expect(@rclient.del.firstCall.args[0]).to.deep.equal(['sess:one', 'sess:three', 'sess:four'])
expect(@rclient.srem.firstCall.args[1]).to.deep.equal(['sess:one', 'sess:three', 'sess:four'])
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions null, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 0
@rclient.multi.callCount.should.equal 0
@rclient.del.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
describe 'when there are no keys to delete', ->
beforeEach ->
@rclient.smembers.callsArgWith(1, null, [])
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not do the delete operation', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 0
@rclient.del.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
describe 'touch', ->
beforeEach ->
@rclient.expire.callsArgWith(2, null)
@call = (callback) =>
@UserSessionsManager.touch @user, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call rclient.expire', (done) ->
@call (err) =>
@rclient.expire.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.expire.callsArgWith(2, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.touch null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call expire', (done) ->
@call (err) =>
@rclient.expire.callCount.should.equal 0
done()
describe '_checkSessions', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager._checkSessions @user, callback
@sessionKeys = ['one', 'two']
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.get.callsArgWith(1, null, 'some-value')
@rclient.srem.callsArgWith(2, null, {})
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 2
@rclient.srem.callCount.should.equal 0
done()
describe 'when one of the keys is not present in redis', ->
beforeEach ->
@rclient.get.onCall(0).callsArgWith(1, null, 'some-val')
@rclient.get.onCall(1).callsArgWith(1, null, null)
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should remove that key from the set', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 2
@rclient.srem.callCount.should.equal 1
@rclient.srem.firstCall.args[1].should.equal 'two'
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager._checkSessions null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 0
@rclient.get.callCount.should.equal 0
done()
describe 'when one of the get operations produces an error', ->
beforeEach ->
@rclient.get.onCall(0).callsArgWith(1, new Error('woops'), null)
@rclient.get.onCall(1).callsArgWith(1, null, null)
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should call the right redis methods, bailing out early', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 1
@rclient.srem.callCount.should.equal 0
done()
| 157133 | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserSessionsManager.js"
SandboxedModule = require('sandboxed-module')
describe 'UserSessionsManager', ->
beforeEach ->
@user =
_id: "abcd"
email: "<EMAIL>"
@sessionId = 'some_session_id'
@rclient =
multi: sinon.stub()
exec: sinon.stub()
get: sinon.stub()
del: sinon.stub()
sadd: sinon.stub()
srem: sinon.stub()
smembers: sinon.stub()
expire: sinon.stub()
@rclient.multi.returns(@rclient)
@rclient.get.returns(@rclient)
@rclient.del.returns(@rclient)
@rclient.sadd.returns(@rclient)
@rclient.srem.returns(@rclient)
@rclient.smembers.returns(@rclient)
@rclient.expire.returns(@rclient)
@rclient.exec.callsArgWith(0, null)
@redis =
createClient: () => @rclient
@logger =
err: sinon.stub()
error: sinon.stub()
log: sinon.stub()
@settings =
redis:
web: {}
@UserSessionsManager = SandboxedModule.require modulePath, requires:
"redis-sharelatex": @redis
"logger-sharelatex": @logger
"settings-sharelatex": @settings
describe '_sessionSetKey', ->
it 'should build the correct key', ->
result = @UserSessionsManager._sessionSetKey(@user)
result.should.equal 'UserSessions:abcd'
describe '_sessionKey', ->
it 'should build the correct key', ->
result = @UserSessionsManager._sessionKey(@sessionId)
result.should.equal 'sess:some_session_id'
describe 'trackSession', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession @user, @sessionId, callback
@rclient.exec.callsArgWith(0, null)
@_checkSessions = sinon.stub(@UserSessionsManager, '_checkSessions').returns(null)
afterEach ->
@_checkSessions.restore()
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 1
@rclient.sadd.callCount.should.equal 1
@rclient.expire.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession null, @sessionId, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.sadd.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no sessionId is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession @user, null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.sadd.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'untrackSession', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession @user, @sessionId, callback
@rclient.exec.callsArgWith(0, null)
@_checkSessions = sinon.stub(@UserSessionsManager, '_checkSessions').returns(null)
afterEach ->
@_checkSessions.restore()
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 1
@rclient.srem.callCount.should.equal 1
@rclient.expire.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession null, @sessionId, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no sessionId is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession @user, null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
##
describe 'revokeAllUserSessions', ->
beforeEach ->
@sessionKeys = ['<KEY>', '<KEY>']
@retain = []
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.exec.callsArgWith(0, null)
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions @user, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 1
@rclient.del.callCount.should.equal 1
expect(@rclient.del.firstCall.args[0]).to.deep.equal @sessionKeys
@rclient.srem.callCount.should.equal 1
expect(@rclient.srem.firstCall.args[1]).to.deep.equal @sessionKeys
@rclient.exec.callCount.should.equal 1
done()
describe 'when a session is retained', ->
beforeEach ->
@sessionKeys = ['<KEY>', '<KEY>', '<KEY>', '<KEY>']
@retain = ['two']
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.exec.callsArgWith(0, null)
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions @user, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 1
@rclient.del.callCount.should.equal 1
@rclient.srem.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should remove all sessions except for the retained one', (done) ->
@call (err) =>
expect(@rclient.del.firstCall.args[0]).to.deep.equal(['sess:one', 'sess:three', 'sess:four'])
expect(@rclient.srem.firstCall.args[1]).to.deep.equal(['sess:one', 'sess:three', 'sess:four'])
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions null, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 0
@rclient.multi.callCount.should.equal 0
@rclient.del.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
describe 'when there are no keys to delete', ->
beforeEach ->
@rclient.smembers.callsArgWith(1, null, [])
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not do the delete operation', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 0
@rclient.del.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
describe 'touch', ->
beforeEach ->
@rclient.expire.callsArgWith(2, null)
@call = (callback) =>
@UserSessionsManager.touch @user, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call rclient.expire', (done) ->
@call (err) =>
@rclient.expire.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.expire.callsArgWith(2, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.touch null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call expire', (done) ->
@call (err) =>
@rclient.expire.callCount.should.equal 0
done()
describe '_checkSessions', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager._checkSessions @user, callback
@sessionKeys = ['<KEY>', <KEY>']
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.get.callsArgWith(1, null, 'some-value')
@rclient.srem.callsArgWith(2, null, {})
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 2
@rclient.srem.callCount.should.equal 0
done()
describe 'when one of the keys is not present in redis', ->
beforeEach ->
@rclient.get.onCall(0).callsArgWith(1, null, 'some-val')
@rclient.get.onCall(1).callsArgWith(1, null, null)
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should remove that key from the set', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 2
@rclient.srem.callCount.should.equal 1
@rclient.srem.firstCall.args[1].should.equal 'two'
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager._checkSessions null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 0
@rclient.get.callCount.should.equal 0
done()
describe 'when one of the get operations produces an error', ->
beforeEach ->
@rclient.get.onCall(0).callsArgWith(1, new Error('woops'), null)
@rclient.get.onCall(1).callsArgWith(1, null, null)
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should call the right redis methods, bailing out early', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 1
@rclient.srem.callCount.should.equal 0
done()
| true | sinon = require('sinon')
chai = require('chai')
should = chai.should()
expect = chai.expect
modulePath = "../../../../app/js/Features/User/UserSessionsManager.js"
SandboxedModule = require('sandboxed-module')
describe 'UserSessionsManager', ->
beforeEach ->
@user =
_id: "abcd"
email: "PI:EMAIL:<EMAIL>END_PI"
@sessionId = 'some_session_id'
@rclient =
multi: sinon.stub()
exec: sinon.stub()
get: sinon.stub()
del: sinon.stub()
sadd: sinon.stub()
srem: sinon.stub()
smembers: sinon.stub()
expire: sinon.stub()
@rclient.multi.returns(@rclient)
@rclient.get.returns(@rclient)
@rclient.del.returns(@rclient)
@rclient.sadd.returns(@rclient)
@rclient.srem.returns(@rclient)
@rclient.smembers.returns(@rclient)
@rclient.expire.returns(@rclient)
@rclient.exec.callsArgWith(0, null)
@redis =
createClient: () => @rclient
@logger =
err: sinon.stub()
error: sinon.stub()
log: sinon.stub()
@settings =
redis:
web: {}
@UserSessionsManager = SandboxedModule.require modulePath, requires:
"redis-sharelatex": @redis
"logger-sharelatex": @logger
"settings-sharelatex": @settings
describe '_sessionSetKey', ->
it 'should build the correct key', ->
result = @UserSessionsManager._sessionSetKey(@user)
result.should.equal 'UserSessions:abcd'
describe '_sessionKey', ->
it 'should build the correct key', ->
result = @UserSessionsManager._sessionKey(@sessionId)
result.should.equal 'sess:some_session_id'
describe 'trackSession', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession @user, @sessionId, callback
@rclient.exec.callsArgWith(0, null)
@_checkSessions = sinon.stub(@UserSessionsManager, '_checkSessions').returns(null)
afterEach ->
@_checkSessions.restore()
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 1
@rclient.sadd.callCount.should.equal 1
@rclient.expire.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession null, @sessionId, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.sadd.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no sessionId is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.trackSession @user, null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.sadd.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'untrackSession', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession @user, @sessionId, callback
@rclient.exec.callsArgWith(0, null)
@_checkSessions = sinon.stub(@UserSessionsManager, '_checkSessions').returns(null)
afterEach ->
@_checkSessions.restore()
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 1
@rclient.srem.callCount.should.equal 1
@rclient.expire.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession null, @sessionId, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
describe 'when no sessionId is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.untrackSession @user, null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.multi.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.expire.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
it 'should not call _checkSessions', (done) ->
@call (err) =>
@_checkSessions.callCount.should.equal 0
done()
##
describe 'revokeAllUserSessions', ->
beforeEach ->
@sessionKeys = ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
@retain = []
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.exec.callsArgWith(0, null)
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions @user, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 1
@rclient.del.callCount.should.equal 1
expect(@rclient.del.firstCall.args[0]).to.deep.equal @sessionKeys
@rclient.srem.callCount.should.equal 1
expect(@rclient.srem.firstCall.args[1]).to.deep.equal @sessionKeys
@rclient.exec.callCount.should.equal 1
done()
describe 'when a session is retained', ->
beforeEach ->
@sessionKeys = ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI']
@retain = ['two']
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.exec.callsArgWith(0, null)
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions @user, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 1
@rclient.del.callCount.should.equal 1
@rclient.srem.callCount.should.equal 1
@rclient.exec.callCount.should.equal 1
done()
it 'should remove all sessions except for the retained one', (done) ->
@call (err) =>
expect(@rclient.del.firstCall.args[0]).to.deep.equal(['sess:one', 'sess:three', 'sess:four'])
expect(@rclient.srem.firstCall.args[1]).to.deep.equal(['sess:one', 'sess:three', 'sess:four'])
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.exec.callsArgWith(0, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.revokeAllUserSessions null, @retain, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 0
@rclient.multi.callCount.should.equal 0
@rclient.del.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
describe 'when there are no keys to delete', ->
beforeEach ->
@rclient.smembers.callsArgWith(1, null, [])
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not do the delete operation', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.multi.callCount.should.equal 0
@rclient.del.callCount.should.equal 0
@rclient.srem.callCount.should.equal 0
@rclient.exec.callCount.should.equal 0
done()
describe 'touch', ->
beforeEach ->
@rclient.expire.callsArgWith(2, null)
@call = (callback) =>
@UserSessionsManager.touch @user, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should call rclient.expire', (done) ->
@call (err) =>
@rclient.expire.callCount.should.equal 1
done()
describe 'when rclient produces an error', ->
beforeEach ->
@rclient.expire.callsArgWith(2, new Error('woops'))
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager.touch null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call expire', (done) ->
@call (err) =>
@rclient.expire.callCount.should.equal 0
done()
describe '_checkSessions', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager._checkSessions @user, callback
@sessionKeys = ['PI:KEY:<KEY>END_PI', PI:KEY:<KEY>END_PI']
@rclient.smembers.callsArgWith(1, null, @sessionKeys)
@rclient.get.callsArgWith(1, null, 'some-value')
@rclient.srem.callsArgWith(2, null, {})
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should call the appropriate redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 2
@rclient.srem.callCount.should.equal 0
done()
describe 'when one of the keys is not present in redis', ->
beforeEach ->
@rclient.get.onCall(0).callsArgWith(1, null, 'some-val')
@rclient.get.onCall(1).callsArgWith(1, null, null)
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal undefined
done()
it 'should remove that key from the set', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 2
@rclient.srem.callCount.should.equal 1
@rclient.srem.firstCall.args[1].should.equal 'two'
done()
describe 'when no user is supplied', ->
beforeEach ->
@call = (callback) =>
@UserSessionsManager._checkSessions null, callback
it 'should not produce an error', (done) ->
@call (err) =>
expect(err).to.not.be.instanceof Error
expect(err).to.equal null
done()
it 'should not call redis methods', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 0
@rclient.get.callCount.should.equal 0
done()
describe 'when one of the get operations produces an error', ->
beforeEach ->
@rclient.get.onCall(0).callsArgWith(1, new Error('woops'), null)
@rclient.get.onCall(1).callsArgWith(1, null, null)
it 'should produce an error', (done) ->
@call (err) =>
expect(err).to.be.instanceof Error
done()
it 'should call the right redis methods, bailing out early', (done) ->
@call (err) =>
@rclient.smembers.callCount.should.equal 1
@rclient.get.callCount.should.equal 1
@rclient.srem.callCount.should.equal 0
done()
|
[
{
"context": "\"\n \"https://www.nylas.com\"\n \"mailto:evan@nylas.com\"\n \"tel:8585311718\"\n \"custom:www.nyl",
"end": 1051,
"score": 0.9999285936355591,
"start": 1037,
"tag": "EMAIL",
"value": "evan@nylas.com"
}
] | packages/client-app/spec/components/evented-iframe-spec.cjsx | cnheider/nylas-mail | 24,369 | React = require "react"
ReactTestUtils = require('react-addons-test-utils')
EventedIFrame = require '../../src/components/evented-iframe'
describe 'EventedIFrame', ->
describe 'link clicking behavior', ->
beforeEach ->
@frame = ReactTestUtils.renderIntoDocument(
<EventedIFrame src="about:blank" />
)
@setAttributeSpy = jasmine.createSpy('setAttribute')
@preventDefaultSpy = jasmine.createSpy('preventDefault')
@openLinkSpy = jasmine.createSpy("openLink")
@oldOpenLink = NylasEnv.windowEventHandler.openLink
NylasEnv.windowEventHandler.openLink = @openLinkSpy
@fakeEvent = (href) =>
stopPropagation: ->
preventDefault: @preventDefaultSpy
target:
getAttribute: (attr) -> return href
setAttribute: @setAttributeSpy
afterEach ->
NylasEnv.windowEventHandler.openLink = @oldOpenLink
it 'works for acceptable link types', ->
hrefs = [
"http://nylas.com"
"https://www.nylas.com"
"mailto:evan@nylas.com"
"tel:8585311718"
"custom:www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).not.toHaveBeenCalled()
expect(@openLinkSpy).toHaveBeenCalled()
target = @openLinkSpy.calls[i].args[0].target
targetHref = @openLinkSpy.calls[i].args[0].href
expect(target).not.toBeDefined()
expect(targetHref).toBe href
it 'corrects relative uris', ->
hrefs = [
"nylas.com"
"www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).toHaveBeenCalled()
modifiedHref = @setAttributeSpy.calls[i].args[1]
expect(modifiedHref).toBe "http://#{href}"
it 'corrects protocol-relative uris', ->
hrefs = [
"//nylas.com"
"//www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).toHaveBeenCalled()
modifiedHref = @setAttributeSpy.calls[i].args[1]
expect(modifiedHref).toBe "https:#{href}"
it 'disallows malicious uris', ->
hrefs = [
"file://usr/bin/bad"
]
for href in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@preventDefaultSpy).toHaveBeenCalled()
expect(@openLinkSpy).not.toHaveBeenCalled()
| 21099 | React = require "react"
ReactTestUtils = require('react-addons-test-utils')
EventedIFrame = require '../../src/components/evented-iframe'
describe 'EventedIFrame', ->
describe 'link clicking behavior', ->
beforeEach ->
@frame = ReactTestUtils.renderIntoDocument(
<EventedIFrame src="about:blank" />
)
@setAttributeSpy = jasmine.createSpy('setAttribute')
@preventDefaultSpy = jasmine.createSpy('preventDefault')
@openLinkSpy = jasmine.createSpy("openLink")
@oldOpenLink = NylasEnv.windowEventHandler.openLink
NylasEnv.windowEventHandler.openLink = @openLinkSpy
@fakeEvent = (href) =>
stopPropagation: ->
preventDefault: @preventDefaultSpy
target:
getAttribute: (attr) -> return href
setAttribute: @setAttributeSpy
afterEach ->
NylasEnv.windowEventHandler.openLink = @oldOpenLink
it 'works for acceptable link types', ->
hrefs = [
"http://nylas.com"
"https://www.nylas.com"
"mailto:<EMAIL>"
"tel:8585311718"
"custom:www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).not.toHaveBeenCalled()
expect(@openLinkSpy).toHaveBeenCalled()
target = @openLinkSpy.calls[i].args[0].target
targetHref = @openLinkSpy.calls[i].args[0].href
expect(target).not.toBeDefined()
expect(targetHref).toBe href
it 'corrects relative uris', ->
hrefs = [
"nylas.com"
"www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).toHaveBeenCalled()
modifiedHref = @setAttributeSpy.calls[i].args[1]
expect(modifiedHref).toBe "http://#{href}"
it 'corrects protocol-relative uris', ->
hrefs = [
"//nylas.com"
"//www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).toHaveBeenCalled()
modifiedHref = @setAttributeSpy.calls[i].args[1]
expect(modifiedHref).toBe "https:#{href}"
it 'disallows malicious uris', ->
hrefs = [
"file://usr/bin/bad"
]
for href in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@preventDefaultSpy).toHaveBeenCalled()
expect(@openLinkSpy).not.toHaveBeenCalled()
| true | React = require "react"
ReactTestUtils = require('react-addons-test-utils')
EventedIFrame = require '../../src/components/evented-iframe'
describe 'EventedIFrame', ->
describe 'link clicking behavior', ->
beforeEach ->
@frame = ReactTestUtils.renderIntoDocument(
<EventedIFrame src="about:blank" />
)
@setAttributeSpy = jasmine.createSpy('setAttribute')
@preventDefaultSpy = jasmine.createSpy('preventDefault')
@openLinkSpy = jasmine.createSpy("openLink")
@oldOpenLink = NylasEnv.windowEventHandler.openLink
NylasEnv.windowEventHandler.openLink = @openLinkSpy
@fakeEvent = (href) =>
stopPropagation: ->
preventDefault: @preventDefaultSpy
target:
getAttribute: (attr) -> return href
setAttribute: @setAttributeSpy
afterEach ->
NylasEnv.windowEventHandler.openLink = @oldOpenLink
it 'works for acceptable link types', ->
hrefs = [
"http://nylas.com"
"https://www.nylas.com"
"mailto:PI:EMAIL:<EMAIL>END_PI"
"tel:8585311718"
"custom:www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).not.toHaveBeenCalled()
expect(@openLinkSpy).toHaveBeenCalled()
target = @openLinkSpy.calls[i].args[0].target
targetHref = @openLinkSpy.calls[i].args[0].href
expect(target).not.toBeDefined()
expect(targetHref).toBe href
it 'corrects relative uris', ->
hrefs = [
"nylas.com"
"www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).toHaveBeenCalled()
modifiedHref = @setAttributeSpy.calls[i].args[1]
expect(modifiedHref).toBe "http://#{href}"
it 'corrects protocol-relative uris', ->
hrefs = [
"//nylas.com"
"//www.nylas.com"
]
for href, i in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@setAttributeSpy).toHaveBeenCalled()
modifiedHref = @setAttributeSpy.calls[i].args[1]
expect(modifiedHref).toBe "https:#{href}"
it 'disallows malicious uris', ->
hrefs = [
"file://usr/bin/bad"
]
for href in hrefs
@frame._onIFrameClick(@fakeEvent(href))
expect(@preventDefaultSpy).toHaveBeenCalled()
expect(@openLinkSpy).not.toHaveBeenCalled()
|
[
{
"context": "le categories\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hype",
"end": 78,
"score": 0.9993904829025269,
"start": 72,
"tag": "USERNAME",
"value": "nodize"
},
{
"context": "://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hypee.com\n#\n# Licensed under the MIT lic",
"end": 114,
"score": 0.9758190512657166,
"start": 109,
"tag": "NAME",
"value": "Hypee"
}
] | modules/backend/controllers/ctrl_category.coffee | nodize/nodizecms | 32 | # Controller for article categories
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, Hypee
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
Settings = @Settings
#
# CATEGORIES SETTINGS
#
@post "/:lang/admin/category/get_list" : ->
#
# Retrieve menus
#
Category.findAll({order:'ordering'})
.on 'success', (categories) =>
#
# Display menu edition page
#
@render "backend_category",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
categories : categories
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORIES ORDERING
#
@post "/:lang/admin/category/save_ordering" : (req) ->
values = req.body
requestCount = 0
#
# Call back on request finish
# We send success response when all requests are done
#
checkFinished = =>
requestCount--
if requestCount is 0
#
# Building JSON response
# - Notification
#
message =
message_type : "success"
message : "categories ordered"
update : []
callback : null
@send message
ordering = 1
#
# Doing UPDATE queries
#
for id_category in values.order.split ','
requestCount++
DB.query( "UPDATE category SET ordering=#{ordering} WHERE id_category=#{id_category}")
.on 'success', ->
checkFinished()
.on 'failure', (err) ->
console.log 'database error ', err
ordering++
#
# ADD A CATEGORY
#
@post "/:lang/admin/category/save" : (req, res) ->
values = req.body
category = Category.build()
category.name = values.name
requestCount = 0
#
# Add CATEGORY record
#
doCategorySave = (ordering)->
category.ordering = ordering
category.save()
.on 'success', (new_category) ->
# Sequelize needs "id" field & current primary key is "id_menu" in Ionize database
DB.query( "UPDATE category SET id = id_category")
# We will send as many async requests than existing langs
requestCount += Static_langs.length
for lang in Static_langs
doCategoryLangSave( lang, new_category.id_category )
.on 'failure', (err) ->
console.log "category save error ", err
#
# Save lang info for a category
#
doCategoryLangSave = (lang, id_category) ->
category_lang = Category_lang.build()
category_lang.title = values['title_'+lang]
category_lang.subtitle = values['subtitle_'+lang]
category_lang.description = values['description_'+lang]
category_lang.id_category = id_category
category_lang.lang = lang
category_lang.save()
.on 'success', ->
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category saved"
update : []
callback : [
fn:"ION.HTML"
args: ["category\/\/get_list","",{"update":"categoriesContainer"}]
,
fn:"ION.clearFormInput"
args:{"form":"newCategoryForm"}
]
id: id_category
res.send message
.on 'failure', (err) ->
console.log "Category_lang save error", err
#
# Find Category's max ordering value, then starting saving process
#
Category.max('ordering')
.on 'success', (max) ->
doCategorySave( max+1 )
#
# UPDATE A CATEGORY
#
@post "/:lang/admin/category/update" : (req, res) ->
values = req.body
requestCount = 0
doCategoryLangUpdate = (lang, id_category) ->
Category_lang.find({where:{id_category:id_category, lang:lang}})
.on 'success', (category_lang) ->
category_lang.title = values['title_'+lang]
category_lang.subtitle = values['subtitle_'+lang]
category_lang.description = values['description_'+lang]
category_lang.save()
.on 'success', ->
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category saved"
update : []
callback : [
fn:"ION.HTML"
args: ["category\/\/get_list","",{"update":"categoriesContainer"}]
,
fn:"ION.clearFormInput"
args:{"form":"newCategoryForm"}
]
id: id_category
res.send message
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
Category.find({where:{id_category:values.id_category}})
.on 'success', (category) ->
category.name = values.name
category.save()
.on 'success', (category) ->
# We will send as many async requests than existing langs
requestCount += Static_langs.length
for lang in Static_langs
doCategoryLangUpdate( lang, category.id_category )
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORY DELETE
#
@post "/:lang/admin/category/delete/:id_category" : ->
requestCount = 0
deleteCategoryLang = (category_lang) =>
category_lang.destroy()
.on 'success', =>
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category deleted"
update : [
element : "categories"
url : "\/#{@params.lang}\/admin\/category\/\/get_select"
]
callback : [
"fn":"ION.deleteDomElements"
"args":[".category"+@params.id_category]
]
id : @params.id_category
# / Message
@send message
.on 'failure', (err) ->
console.log 'database error ', err
Category.find({where:{id_category:@params.id_category}})
.on 'success', (category) =>
#
# Also delete category langs
#
Category_lang.findAll( {where:{id_category:category.id_category}})
.on 'success', (category_langs)->
requestCount += category_langs.length
for category_lang in category_langs
deleteCategoryLang( category_lang )
#
# Then delete the category record
#
category.destroy()
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORIES GET SELECT
#
@post "/:lang/admin/category/get_select" : ->
#
# Retrieve categories
#
Category.findAll({order:'ordering'})
.on 'success', (categories) =>
#
# Display response
#
@render "backend_categorySelect",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
categories : categories
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORY EDIT
#
@post "/:lang/admin/category/edit/:id_category" : ->
Category.find({where:{id_category:@params.id_category}})
.on 'success', (category) =>
#
# Retrieve category langs
#
Category_lang.findAll({where:{id_category:category.id_category}})
.on 'success', (category_langs) =>
#
# Display type edition page
#
@render "backend_categoryEdit",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
category : category
category_langs : category_langs
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err | 122100 | # Controller for article categories
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, <NAME>
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
Settings = @Settings
#
# CATEGORIES SETTINGS
#
@post "/:lang/admin/category/get_list" : ->
#
# Retrieve menus
#
Category.findAll({order:'ordering'})
.on 'success', (categories) =>
#
# Display menu edition page
#
@render "backend_category",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
categories : categories
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORIES ORDERING
#
@post "/:lang/admin/category/save_ordering" : (req) ->
values = req.body
requestCount = 0
#
# Call back on request finish
# We send success response when all requests are done
#
checkFinished = =>
requestCount--
if requestCount is 0
#
# Building JSON response
# - Notification
#
message =
message_type : "success"
message : "categories ordered"
update : []
callback : null
@send message
ordering = 1
#
# Doing UPDATE queries
#
for id_category in values.order.split ','
requestCount++
DB.query( "UPDATE category SET ordering=#{ordering} WHERE id_category=#{id_category}")
.on 'success', ->
checkFinished()
.on 'failure', (err) ->
console.log 'database error ', err
ordering++
#
# ADD A CATEGORY
#
@post "/:lang/admin/category/save" : (req, res) ->
values = req.body
category = Category.build()
category.name = values.name
requestCount = 0
#
# Add CATEGORY record
#
doCategorySave = (ordering)->
category.ordering = ordering
category.save()
.on 'success', (new_category) ->
# Sequelize needs "id" field & current primary key is "id_menu" in Ionize database
DB.query( "UPDATE category SET id = id_category")
# We will send as many async requests than existing langs
requestCount += Static_langs.length
for lang in Static_langs
doCategoryLangSave( lang, new_category.id_category )
.on 'failure', (err) ->
console.log "category save error ", err
#
# Save lang info for a category
#
doCategoryLangSave = (lang, id_category) ->
category_lang = Category_lang.build()
category_lang.title = values['title_'+lang]
category_lang.subtitle = values['subtitle_'+lang]
category_lang.description = values['description_'+lang]
category_lang.id_category = id_category
category_lang.lang = lang
category_lang.save()
.on 'success', ->
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category saved"
update : []
callback : [
fn:"ION.HTML"
args: ["category\/\/get_list","",{"update":"categoriesContainer"}]
,
fn:"ION.clearFormInput"
args:{"form":"newCategoryForm"}
]
id: id_category
res.send message
.on 'failure', (err) ->
console.log "Category_lang save error", err
#
# Find Category's max ordering value, then starting saving process
#
Category.max('ordering')
.on 'success', (max) ->
doCategorySave( max+1 )
#
# UPDATE A CATEGORY
#
@post "/:lang/admin/category/update" : (req, res) ->
values = req.body
requestCount = 0
doCategoryLangUpdate = (lang, id_category) ->
Category_lang.find({where:{id_category:id_category, lang:lang}})
.on 'success', (category_lang) ->
category_lang.title = values['title_'+lang]
category_lang.subtitle = values['subtitle_'+lang]
category_lang.description = values['description_'+lang]
category_lang.save()
.on 'success', ->
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category saved"
update : []
callback : [
fn:"ION.HTML"
args: ["category\/\/get_list","",{"update":"categoriesContainer"}]
,
fn:"ION.clearFormInput"
args:{"form":"newCategoryForm"}
]
id: id_category
res.send message
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
Category.find({where:{id_category:values.id_category}})
.on 'success', (category) ->
category.name = values.name
category.save()
.on 'success', (category) ->
# We will send as many async requests than existing langs
requestCount += Static_langs.length
for lang in Static_langs
doCategoryLangUpdate( lang, category.id_category )
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORY DELETE
#
@post "/:lang/admin/category/delete/:id_category" : ->
requestCount = 0
deleteCategoryLang = (category_lang) =>
category_lang.destroy()
.on 'success', =>
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category deleted"
update : [
element : "categories"
url : "\/#{@params.lang}\/admin\/category\/\/get_select"
]
callback : [
"fn":"ION.deleteDomElements"
"args":[".category"+@params.id_category]
]
id : @params.id_category
# / Message
@send message
.on 'failure', (err) ->
console.log 'database error ', err
Category.find({where:{id_category:@params.id_category}})
.on 'success', (category) =>
#
# Also delete category langs
#
Category_lang.findAll( {where:{id_category:category.id_category}})
.on 'success', (category_langs)->
requestCount += category_langs.length
for category_lang in category_langs
deleteCategoryLang( category_lang )
#
# Then delete the category record
#
category.destroy()
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORIES GET SELECT
#
@post "/:lang/admin/category/get_select" : ->
#
# Retrieve categories
#
Category.findAll({order:'ordering'})
.on 'success', (categories) =>
#
# Display response
#
@render "backend_categorySelect",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
categories : categories
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORY EDIT
#
@post "/:lang/admin/category/edit/:id_category" : ->
Category.find({where:{id_category:@params.id_category}})
.on 'success', (category) =>
#
# Retrieve category langs
#
Category_lang.findAll({where:{id_category:category.id_category}})
.on 'success', (category_langs) =>
#
# Display type edition page
#
@render "backend_categoryEdit",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
category : category
category_langs : category_langs
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err | true | # Controller for article categories
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, PI:NAME:<NAME>END_PI
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
Settings = @Settings
#
# CATEGORIES SETTINGS
#
@post "/:lang/admin/category/get_list" : ->
#
# Retrieve menus
#
Category.findAll({order:'ordering'})
.on 'success', (categories) =>
#
# Display menu edition page
#
@render "backend_category",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
categories : categories
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORIES ORDERING
#
@post "/:lang/admin/category/save_ordering" : (req) ->
values = req.body
requestCount = 0
#
# Call back on request finish
# We send success response when all requests are done
#
checkFinished = =>
requestCount--
if requestCount is 0
#
# Building JSON response
# - Notification
#
message =
message_type : "success"
message : "categories ordered"
update : []
callback : null
@send message
ordering = 1
#
# Doing UPDATE queries
#
for id_category in values.order.split ','
requestCount++
DB.query( "UPDATE category SET ordering=#{ordering} WHERE id_category=#{id_category}")
.on 'success', ->
checkFinished()
.on 'failure', (err) ->
console.log 'database error ', err
ordering++
#
# ADD A CATEGORY
#
@post "/:lang/admin/category/save" : (req, res) ->
values = req.body
category = Category.build()
category.name = values.name
requestCount = 0
#
# Add CATEGORY record
#
doCategorySave = (ordering)->
category.ordering = ordering
category.save()
.on 'success', (new_category) ->
# Sequelize needs "id" field & current primary key is "id_menu" in Ionize database
DB.query( "UPDATE category SET id = id_category")
# We will send as many async requests than existing langs
requestCount += Static_langs.length
for lang in Static_langs
doCategoryLangSave( lang, new_category.id_category )
.on 'failure', (err) ->
console.log "category save error ", err
#
# Save lang info for a category
#
doCategoryLangSave = (lang, id_category) ->
category_lang = Category_lang.build()
category_lang.title = values['title_'+lang]
category_lang.subtitle = values['subtitle_'+lang]
category_lang.description = values['description_'+lang]
category_lang.id_category = id_category
category_lang.lang = lang
category_lang.save()
.on 'success', ->
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category saved"
update : []
callback : [
fn:"ION.HTML"
args: ["category\/\/get_list","",{"update":"categoriesContainer"}]
,
fn:"ION.clearFormInput"
args:{"form":"newCategoryForm"}
]
id: id_category
res.send message
.on 'failure', (err) ->
console.log "Category_lang save error", err
#
# Find Category's max ordering value, then starting saving process
#
Category.max('ordering')
.on 'success', (max) ->
doCategorySave( max+1 )
#
# UPDATE A CATEGORY
#
@post "/:lang/admin/category/update" : (req, res) ->
values = req.body
requestCount = 0
doCategoryLangUpdate = (lang, id_category) ->
Category_lang.find({where:{id_category:id_category, lang:lang}})
.on 'success', (category_lang) ->
category_lang.title = values['title_'+lang]
category_lang.subtitle = values['subtitle_'+lang]
category_lang.description = values['description_'+lang]
category_lang.save()
.on 'success', ->
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category saved"
update : []
callback : [
fn:"ION.HTML"
args: ["category\/\/get_list","",{"update":"categoriesContainer"}]
,
fn:"ION.clearFormInput"
args:{"form":"newCategoryForm"}
]
id: id_category
res.send message
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
Category.find({where:{id_category:values.id_category}})
.on 'success', (category) ->
category.name = values.name
category.save()
.on 'success', (category) ->
# We will send as many async requests than existing langs
requestCount += Static_langs.length
for lang in Static_langs
doCategoryLangUpdate( lang, category.id_category )
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORY DELETE
#
@post "/:lang/admin/category/delete/:id_category" : ->
requestCount = 0
deleteCategoryLang = (category_lang) =>
category_lang.destroy()
.on 'success', =>
requestCount--
if requestCount is 0
#
# Building JSON response
#
message =
message_type : "success"
message : "Category deleted"
update : [
element : "categories"
url : "\/#{@params.lang}\/admin\/category\/\/get_select"
]
callback : [
"fn":"ION.deleteDomElements"
"args":[".category"+@params.id_category]
]
id : @params.id_category
# / Message
@send message
.on 'failure', (err) ->
console.log 'database error ', err
Category.find({where:{id_category:@params.id_category}})
.on 'success', (category) =>
#
# Also delete category langs
#
Category_lang.findAll( {where:{id_category:category.id_category}})
.on 'success', (category_langs)->
requestCount += category_langs.length
for category_lang in category_langs
deleteCategoryLang( category_lang )
#
# Then delete the category record
#
category.destroy()
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORIES GET SELECT
#
@post "/:lang/admin/category/get_select" : ->
#
# Retrieve categories
#
Category.findAll({order:'ordering'})
.on 'success', (categories) =>
#
# Display response
#
@render "backend_categorySelect",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
categories : categories
.on 'failure', (err) ->
console.log 'database error ', err
#
# CATEGORY EDIT
#
@post "/:lang/admin/category/edit/:id_category" : ->
Category.find({where:{id_category:@params.id_category}})
.on 'success', (category) =>
#
# Retrieve category langs
#
Category_lang.findAll({where:{id_category:category.id_category}})
.on 'success', (category_langs) =>
#
# Display type edition page
#
@render "backend_categoryEdit",
layout : no
hardcode : @helpers
settings : Settings
lang : @params.lang
ion_lang : ion_lang[ @params.lang ]
category : category
category_langs : category_langs
.on 'failure', (err) ->
console.log 'database error ', err
.on 'failure', (err) ->
console.log 'database error ', err |
[
{
"context": "iling list.\n#\n# Examples:\n# post json {\"email\":\"name@example.com\", \"source\":\"manylabs.org mailing list\"} to the ur",
"end": 134,
"score": 0.9999210238456726,
"start": 118,
"tag": "EMAIL",
"value": "name@example.com"
},
{
"context": "-H \"Content-Type: application/json\" -d '{\"email\":\"name@example.com\", \"source\":\"mailing list name via RAW JSON\"}' htt",
"end": 389,
"score": 0.9999164342880249,
"start": 373,
"tag": "EMAIL",
"value": "name@example.com"
},
{
"context": "source\":\"mailing list name via RAW JSON\"}' http://127.0.0.1:8080/hubot/signup-notifier\n#\n# Post raw json wi",
"end": 452,
"score": 0.967386782169342,
"start": 443,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "m&source=mailing+list+name+via+X-WWW-FORM' http://127.0.0.1:8080/hubot/signup-notifier\n#\n# Post raw json wi",
"end": 697,
"score": 0.9215864539146423,
"start": 688,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " -H \"Content-Type: multipart/form-data\" -F \"email=name@example.com\" -F \"source=manylabs.org mailing list via FORM-DA",
"end": 854,
"score": 0.9998687505722046,
"start": 838,
"tag": "EMAIL",
"value": "name@example.com"
},
{
"context": "e=manylabs.org mailing list via FORM-DATA\" http://127.0.0.1:8080/hubot/signup-notifier\n# \n# Post stringif",
"end": 924,
"score": 0.8968289494514465,
"start": 915,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "-Type: multipart/form-data\" -F 'payload={\"email\":\"name@example.com\", \"source\":\"mailing list name via payload json\"}'",
"end": 1404,
"score": 0.9999157190322876,
"start": 1388,
"tag": "EMAIL",
"value": "name@example.com"
}
] | scripts/signup-notifier.coffee | 100ideas/manylabs-hubot | 0 | # Description:
# let us know when someone has signed up for the mailing list.
#
# Examples:
# post json {"email":"name@example.com", "source":"manylabs.org mailing list"} to the url
#
# URLs:
# manylabs-hubot.heroku.com/hubot/signup-notifier
#
# Notes:
#
# Post raw json with application/json
# curl -X POST -H "Content-Type: application/json" -d '{"email":"name@example.com", "source":"mailing list name via RAW JSON"}' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post raw json with application/x-www-form-urlencoded
# curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'email=name%40example.com&source=mailing+list+name+via+X-WWW-FORM' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post raw json with multipart/form-data
# curl -X POST -H "Content-Type: multipart/form-data" -F "email=name@example.com" -F "source=manylabs.org mailing list via FORM-DATA" http://127.0.0.1:8080/hubot/signup-notifier
#
# Post stringified json with application/x-www-form-urlencoded
# curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'payload=%7B%22email%22%3A%22name%40example.com%22%2C+%22source%22%3A%22mailing+list+name+via+payload+json%22%7D' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post stringified json with multipart/form-data
# curl -X POST -H "Content-Type: multipart/form-data" -F 'payload={"email":"name@example.com", "source":"mailing list name via payload json"}' http://127.0.0.1:8080/hubot/signup-notifier
#
module.exports = (robot) ->
robot.router.post "/hubot/signup-notifier", (req, res) ->
# express.js body-parser middleware should JSONify req.body, if not try JSON.parse on payload
data = if req.body.payload? then JSON.parse req.body.payload else req.body
robot.messageRoom 'general', "Oooo! \<#{data.email}\> just signed up for #{data.source}."
robot.logger.info "signup-notifier: \<#{data.email}\> signed up for #{data.source}"
res.send 'OK' | 122941 | # Description:
# let us know when someone has signed up for the mailing list.
#
# Examples:
# post json {"email":"<EMAIL>", "source":"manylabs.org mailing list"} to the url
#
# URLs:
# manylabs-hubot.heroku.com/hubot/signup-notifier
#
# Notes:
#
# Post raw json with application/json
# curl -X POST -H "Content-Type: application/json" -d '{"email":"<EMAIL>", "source":"mailing list name via RAW JSON"}' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post raw json with application/x-www-form-urlencoded
# curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'email=name%40example.com&source=mailing+list+name+via+X-WWW-FORM' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post raw json with multipart/form-data
# curl -X POST -H "Content-Type: multipart/form-data" -F "email=<EMAIL>" -F "source=manylabs.org mailing list via FORM-DATA" http://127.0.0.1:8080/hubot/signup-notifier
#
# Post stringified json with application/x-www-form-urlencoded
# curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'payload=%7B%22email%22%3A%22name%40example.com%22%2C+%22source%22%3A%22mailing+list+name+via+payload+json%22%7D' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post stringified json with multipart/form-data
# curl -X POST -H "Content-Type: multipart/form-data" -F 'payload={"email":"<EMAIL>", "source":"mailing list name via payload json"}' http://127.0.0.1:8080/hubot/signup-notifier
#
module.exports = (robot) ->
robot.router.post "/hubot/signup-notifier", (req, res) ->
# express.js body-parser middleware should JSONify req.body, if not try JSON.parse on payload
data = if req.body.payload? then JSON.parse req.body.payload else req.body
robot.messageRoom 'general', "Oooo! \<#{data.email}\> just signed up for #{data.source}."
robot.logger.info "signup-notifier: \<#{data.email}\> signed up for #{data.source}"
res.send 'OK' | true | # Description:
# let us know when someone has signed up for the mailing list.
#
# Examples:
# post json {"email":"PI:EMAIL:<EMAIL>END_PI", "source":"manylabs.org mailing list"} to the url
#
# URLs:
# manylabs-hubot.heroku.com/hubot/signup-notifier
#
# Notes:
#
# Post raw json with application/json
# curl -X POST -H "Content-Type: application/json" -d '{"email":"PI:EMAIL:<EMAIL>END_PI", "source":"mailing list name via RAW JSON"}' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post raw json with application/x-www-form-urlencoded
# curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'email=name%40example.com&source=mailing+list+name+via+X-WWW-FORM' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post raw json with multipart/form-data
# curl -X POST -H "Content-Type: multipart/form-data" -F "email=PI:EMAIL:<EMAIL>END_PI" -F "source=manylabs.org mailing list via FORM-DATA" http://127.0.0.1:8080/hubot/signup-notifier
#
# Post stringified json with application/x-www-form-urlencoded
# curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d 'payload=%7B%22email%22%3A%22name%40example.com%22%2C+%22source%22%3A%22mailing+list+name+via+payload+json%22%7D' http://127.0.0.1:8080/hubot/signup-notifier
#
# Post stringified json with multipart/form-data
# curl -X POST -H "Content-Type: multipart/form-data" -F 'payload={"email":"PI:EMAIL:<EMAIL>END_PI", "source":"mailing list name via payload json"}' http://127.0.0.1:8080/hubot/signup-notifier
#
module.exports = (robot) ->
robot.router.post "/hubot/signup-notifier", (req, res) ->
# express.js body-parser middleware should JSONify req.body, if not try JSON.parse on payload
data = if req.body.payload? then JSON.parse req.body.payload else req.body
robot.messageRoom 'general', "Oooo! \<#{data.email}\> just signed up for #{data.source}."
robot.logger.info "signup-notifier: \<#{data.email}\> signed up for #{data.source}"
res.send 'OK' |
[
{
"context": "# Info.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Controls ap",
"end": 22,
"score": 0.998016893863678,
"start": 16,
"tag": "NAME",
"value": "Tomasz"
},
{
"context": "# Info.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Controls application in",
"end": 36,
"score": 0.9859371185302734,
"start": 24,
"tag": "NAME",
"value": "Tomek) Zemla"
},
{
"context": "# Info.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Controls application info console on the right",
"end": 59,
"score": 0.9999295473098755,
"start": 39,
"tag": "EMAIL",
"value": "tomek@datacratic.com"
}
] | src/Info.coffee | SachithDassanayaka/sachithdassanayaka.github.io | 0 | # Info.coffee
# Tomasz (Tomek) Zemla
# tomek@datacratic.com
# Controls application info console on the right side of the application window.
Panel = require('./Panel.coffee')
class Info extends Panel
# C O N S T R U C T O R
# Create info console panel.
constructor: (id) ->
super(id)
# M E T H O D S
# Display given message keeping the existing text intact.
display: (message) ->
$('#message').append(message + "<br/>")
# Clear the info console.
clear: ->
$('#message').text("")
module.exports = Info | 32843 | # Info.coffee
# <NAME> (<NAME>
# <EMAIL>
# Controls application info console on the right side of the application window.
Panel = require('./Panel.coffee')
class Info extends Panel
# C O N S T R U C T O R
# Create info console panel.
constructor: (id) ->
super(id)
# M E T H O D S
# Display given message keeping the existing text intact.
display: (message) ->
$('#message').append(message + "<br/>")
# Clear the info console.
clear: ->
$('#message').text("")
module.exports = Info | true | # Info.coffee
# PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI
# PI:EMAIL:<EMAIL>END_PI
# Controls application info console on the right side of the application window.
Panel = require('./Panel.coffee')
class Info extends Panel
# C O N S T R U C T O R
# Create info console panel.
constructor: (id) ->
super(id)
# M E T H O D S
# Display given message keeping the existing text intact.
display: (message) ->
$('#message').append(message + "<br/>")
# Clear the info console.
clear: ->
$('#message').text("")
module.exports = Info |
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991982579231262,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-upgrade-server2.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")
http = require("http")
net = require("net")
server = http.createServer((req, res) ->
common.error "got req"
throw new Error("This shouldn't happen.")return
)
server.on "upgrade", (req, socket, upgradeHead) ->
common.error "got upgrade event"
# test that throwing an error from upgrade gets
# is uncaught
throw new Error("upgrade error")return
gotError = false
process.on "uncaughtException", (e) ->
common.error "got 'clientError' event"
assert.equal "upgrade error", e.message
gotError = true
process.exit 0
return
server.listen common.PORT, ->
c = net.createConnection(common.PORT)
c.on "connect", ->
common.error "client wrote message"
c.write "GET /blah HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n\r\nhello world"
return
c.on "end", ->
c.end()
return
c.on "close", ->
common.error "client close"
server.close()
return
return
process.on "exit", ->
assert.ok gotError
return
| 53692 | # 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")
http = require("http")
net = require("net")
server = http.createServer((req, res) ->
common.error "got req"
throw new Error("This shouldn't happen.")return
)
server.on "upgrade", (req, socket, upgradeHead) ->
common.error "got upgrade event"
# test that throwing an error from upgrade gets
# is uncaught
throw new Error("upgrade error")return
gotError = false
process.on "uncaughtException", (e) ->
common.error "got 'clientError' event"
assert.equal "upgrade error", e.message
gotError = true
process.exit 0
return
server.listen common.PORT, ->
c = net.createConnection(common.PORT)
c.on "connect", ->
common.error "client wrote message"
c.write "GET /blah HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n\r\nhello world"
return
c.on "end", ->
c.end()
return
c.on "close", ->
common.error "client close"
server.close()
return
return
process.on "exit", ->
assert.ok gotError
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")
http = require("http")
net = require("net")
server = http.createServer((req, res) ->
common.error "got req"
throw new Error("This shouldn't happen.")return
)
server.on "upgrade", (req, socket, upgradeHead) ->
common.error "got upgrade event"
# test that throwing an error from upgrade gets
# is uncaught
throw new Error("upgrade error")return
gotError = false
process.on "uncaughtException", (e) ->
common.error "got 'clientError' event"
assert.equal "upgrade error", e.message
gotError = true
process.exit 0
return
server.listen common.PORT, ->
c = net.createConnection(common.PORT)
c.on "connect", ->
common.error "client wrote message"
c.write "GET /blah HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "\r\n\r\nhello world"
return
c.on "end", ->
c.end()
return
c.on "close", ->
common.error "client close"
server.close()
return
return
process.on "exit", ->
assert.ok gotError
return
|
[
{
"context": "h4Files = (body) ->\n keys = [1..4].map (n) -> \"tmp/spec/list/file_#{n}\"\n\n beforeEach (done) ->\n parallel(\n ",
"end": 543,
"score": 0.8500592112541199,
"start": 522,
"tag": "KEY",
"value": "tmp/spec/list/file_#{"
}
] | spec/knox-copy.spec.coffee | dweinstein/knox-copy | 3 | knoxCopy = require '..'
fs = require 'fs'
{parallel} = require 'async'
describe 'knox-copy', ->
{key, bucket, client} = {}
beforeEach ->
try
{key, secret, bucket} = JSON.parse fs.readFileSync('auth', 'ascii')
client = knoxCopy.createClient {key, secret, bucket}
catch err
console.error 'The tests require ./auth to contain a JSON string with'
console.error '`key, secret, and bucket in order to run tests.'
process.exit 1
with4Files = (body) ->
keys = [1..4].map (n) -> "tmp/spec/list/file_#{n}"
beforeEach (done) ->
parallel(
keys.map (key) -> (cb) ->
client.putBuffer 'test file', key, cb
done)
afterEach (done) ->
parallel(
keys.map (key) -> (cb) ->
client.deleteFile key, cb
done)
describe 'with 4 files', ->
body(keys)
describe 'listPageOfKeys()', ->
with4Files (keys) ->
it 'should list a page of S3 Object keys', (done) ->
# Middle 2 of 4 files
client.listPageOfKeys
maxKeys: 2
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_1'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeTruthy()
expect(page.Contents.length).toBe 2
done()
# Last of 4 files
client.listPageOfKeys
maxKeys: 4
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_3'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 1
done()
# Marker at the end
client.listPageOfKeys
maxKeys: 4
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_4'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 0
done()
# Empty prefix
client.listPageOfKeys
maxKeys: 4
prefix: '/does_not_exist'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 0
done()
describe 'streamKeys()', ->
with4Files (keys) ->
describe 'when all keys fit on single a page', ->
it 'should emit a data event for every key and an end event when keys are exhausted', (done) ->
streamedKeys = []
stream = client.streamKeys(prefix: '/tmp/spec/list')
stream.on 'data', (key) -> streamedKeys.push key
stream.on 'end', ->
expect(streamedKeys).toEqual keys
done()
describe 'when the number of keys exceeds page size', ->
maxKeysPerRequest = 2
it 'should emit a data event for every key and an end event when keys are exhausted', (done) ->
streamedKeys = []
stream = client.streamKeys({prefix: '/tmp/spec/list', maxKeysPerRequest})
stream.on 'data', (key) -> streamedKeys.push key
stream.on 'end', ->
expect(streamedKeys).toEqual keys
done()
describe 'copyBucket()', ->
with4Files (keys) ->
afterEach (done) ->
parallel(
[1..4].map (n) -> (cb) ->
client.deleteFile "/tmp/spec/copy_bucket/file_#{n}", cb
done)
it 'should copy a prefixed set of files across buckets', (done) ->
client.copyBucket
fromBucket: bucket # this is the default value. Included here to show where you'd set a different bucket
fromPrefix: '/tmp/spec/list'
toPrefix: '/tmp/spec/copy_bucket'
(err, count) ->
expect(err).toBeFalsy()
# returns the number of copied objects
expect(count).toBe 4
done()
describe 'with funky filenames', ->
filenames = [
'fruit and flour.png'
'MarkBreadMED05%20-%20cropped.jpg'
]
sourceKeys = filenames.map((filename) -> "/tmp/spec/spaces/#{filename}")
destinationKeys = filenames.map((filename) -> "tmp/spec/copy_spaces/#{filename}")
beforeEach (done) ->
parallel(
sourceKeys.map (key) -> (cb) ->
client.putBuffer 'test file', key, cb
done
)
afterEach (done) ->
parallel(
sourceKeys
.concat(destinationKeys)
.map((key) -> (cb) ->
client.deleteFile(key, cb)
), done)
it 'should copy and preserve filenames', (done) ->
client.copyBucket
fromBucket: bucket # this is the default value. Included here to show where you'd set a different bucket
fromPrefix: '/tmp/spec/spaces'
toPrefix: '/tmp/spec/copy_spaces'
(err, count) ->
expect(err).toBeFalsy()
# returns the number of copied objects
expect(count).toBe 2
client.listPageOfKeys
maxKeys: 2
prefix: '/tmp/spec/copy_spaces'
(err, page) ->
expect(err).toBeFalsy()
expect(
(Key for {Key} in page.Contents).sort()
).toEqual destinationKeys.sort()
done()
| 6536 | knoxCopy = require '..'
fs = require 'fs'
{parallel} = require 'async'
describe 'knox-copy', ->
{key, bucket, client} = {}
beforeEach ->
try
{key, secret, bucket} = JSON.parse fs.readFileSync('auth', 'ascii')
client = knoxCopy.createClient {key, secret, bucket}
catch err
console.error 'The tests require ./auth to contain a JSON string with'
console.error '`key, secret, and bucket in order to run tests.'
process.exit 1
with4Files = (body) ->
keys = [1..4].map (n) -> "<KEY>n}"
beforeEach (done) ->
parallel(
keys.map (key) -> (cb) ->
client.putBuffer 'test file', key, cb
done)
afterEach (done) ->
parallel(
keys.map (key) -> (cb) ->
client.deleteFile key, cb
done)
describe 'with 4 files', ->
body(keys)
describe 'listPageOfKeys()', ->
with4Files (keys) ->
it 'should list a page of S3 Object keys', (done) ->
# Middle 2 of 4 files
client.listPageOfKeys
maxKeys: 2
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_1'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeTruthy()
expect(page.Contents.length).toBe 2
done()
# Last of 4 files
client.listPageOfKeys
maxKeys: 4
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_3'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 1
done()
# Marker at the end
client.listPageOfKeys
maxKeys: 4
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_4'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 0
done()
# Empty prefix
client.listPageOfKeys
maxKeys: 4
prefix: '/does_not_exist'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 0
done()
describe 'streamKeys()', ->
with4Files (keys) ->
describe 'when all keys fit on single a page', ->
it 'should emit a data event for every key and an end event when keys are exhausted', (done) ->
streamedKeys = []
stream = client.streamKeys(prefix: '/tmp/spec/list')
stream.on 'data', (key) -> streamedKeys.push key
stream.on 'end', ->
expect(streamedKeys).toEqual keys
done()
describe 'when the number of keys exceeds page size', ->
maxKeysPerRequest = 2
it 'should emit a data event for every key and an end event when keys are exhausted', (done) ->
streamedKeys = []
stream = client.streamKeys({prefix: '/tmp/spec/list', maxKeysPerRequest})
stream.on 'data', (key) -> streamedKeys.push key
stream.on 'end', ->
expect(streamedKeys).toEqual keys
done()
describe 'copyBucket()', ->
with4Files (keys) ->
afterEach (done) ->
parallel(
[1..4].map (n) -> (cb) ->
client.deleteFile "/tmp/spec/copy_bucket/file_#{n}", cb
done)
it 'should copy a prefixed set of files across buckets', (done) ->
client.copyBucket
fromBucket: bucket # this is the default value. Included here to show where you'd set a different bucket
fromPrefix: '/tmp/spec/list'
toPrefix: '/tmp/spec/copy_bucket'
(err, count) ->
expect(err).toBeFalsy()
# returns the number of copied objects
expect(count).toBe 4
done()
describe 'with funky filenames', ->
filenames = [
'fruit and flour.png'
'MarkBreadMED05%20-%20cropped.jpg'
]
sourceKeys = filenames.map((filename) -> "/tmp/spec/spaces/#{filename}")
destinationKeys = filenames.map((filename) -> "tmp/spec/copy_spaces/#{filename}")
beforeEach (done) ->
parallel(
sourceKeys.map (key) -> (cb) ->
client.putBuffer 'test file', key, cb
done
)
afterEach (done) ->
parallel(
sourceKeys
.concat(destinationKeys)
.map((key) -> (cb) ->
client.deleteFile(key, cb)
), done)
it 'should copy and preserve filenames', (done) ->
client.copyBucket
fromBucket: bucket # this is the default value. Included here to show where you'd set a different bucket
fromPrefix: '/tmp/spec/spaces'
toPrefix: '/tmp/spec/copy_spaces'
(err, count) ->
expect(err).toBeFalsy()
# returns the number of copied objects
expect(count).toBe 2
client.listPageOfKeys
maxKeys: 2
prefix: '/tmp/spec/copy_spaces'
(err, page) ->
expect(err).toBeFalsy()
expect(
(Key for {Key} in page.Contents).sort()
).toEqual destinationKeys.sort()
done()
| true | knoxCopy = require '..'
fs = require 'fs'
{parallel} = require 'async'
describe 'knox-copy', ->
{key, bucket, client} = {}
beforeEach ->
try
{key, secret, bucket} = JSON.parse fs.readFileSync('auth', 'ascii')
client = knoxCopy.createClient {key, secret, bucket}
catch err
console.error 'The tests require ./auth to contain a JSON string with'
console.error '`key, secret, and bucket in order to run tests.'
process.exit 1
with4Files = (body) ->
keys = [1..4].map (n) -> "PI:KEY:<KEY>END_PIn}"
beforeEach (done) ->
parallel(
keys.map (key) -> (cb) ->
client.putBuffer 'test file', key, cb
done)
afterEach (done) ->
parallel(
keys.map (key) -> (cb) ->
client.deleteFile key, cb
done)
describe 'with 4 files', ->
body(keys)
describe 'listPageOfKeys()', ->
with4Files (keys) ->
it 'should list a page of S3 Object keys', (done) ->
# Middle 2 of 4 files
client.listPageOfKeys
maxKeys: 2
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_1'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeTruthy()
expect(page.Contents.length).toBe 2
done()
# Last of 4 files
client.listPageOfKeys
maxKeys: 4
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_3'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 1
done()
# Marker at the end
client.listPageOfKeys
maxKeys: 4
prefix: '/tmp/spec/list'
marker: '/tmp/spec/list/file_4'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 0
done()
# Empty prefix
client.listPageOfKeys
maxKeys: 4
prefix: '/does_not_exist'
(err, page) ->
expect(err).toBeFalsy()
expect(page.IsTruncated).toBeFalsy()
expect(page.Contents.length).toBe 0
done()
describe 'streamKeys()', ->
with4Files (keys) ->
describe 'when all keys fit on single a page', ->
it 'should emit a data event for every key and an end event when keys are exhausted', (done) ->
streamedKeys = []
stream = client.streamKeys(prefix: '/tmp/spec/list')
stream.on 'data', (key) -> streamedKeys.push key
stream.on 'end', ->
expect(streamedKeys).toEqual keys
done()
describe 'when the number of keys exceeds page size', ->
maxKeysPerRequest = 2
it 'should emit a data event for every key and an end event when keys are exhausted', (done) ->
streamedKeys = []
stream = client.streamKeys({prefix: '/tmp/spec/list', maxKeysPerRequest})
stream.on 'data', (key) -> streamedKeys.push key
stream.on 'end', ->
expect(streamedKeys).toEqual keys
done()
describe 'copyBucket()', ->
with4Files (keys) ->
afterEach (done) ->
parallel(
[1..4].map (n) -> (cb) ->
client.deleteFile "/tmp/spec/copy_bucket/file_#{n}", cb
done)
it 'should copy a prefixed set of files across buckets', (done) ->
client.copyBucket
fromBucket: bucket # this is the default value. Included here to show where you'd set a different bucket
fromPrefix: '/tmp/spec/list'
toPrefix: '/tmp/spec/copy_bucket'
(err, count) ->
expect(err).toBeFalsy()
# returns the number of copied objects
expect(count).toBe 4
done()
describe 'with funky filenames', ->
filenames = [
'fruit and flour.png'
'MarkBreadMED05%20-%20cropped.jpg'
]
sourceKeys = filenames.map((filename) -> "/tmp/spec/spaces/#{filename}")
destinationKeys = filenames.map((filename) -> "tmp/spec/copy_spaces/#{filename}")
beforeEach (done) ->
parallel(
sourceKeys.map (key) -> (cb) ->
client.putBuffer 'test file', key, cb
done
)
afterEach (done) ->
parallel(
sourceKeys
.concat(destinationKeys)
.map((key) -> (cb) ->
client.deleteFile(key, cb)
), done)
it 'should copy and preserve filenames', (done) ->
client.copyBucket
fromBucket: bucket # this is the default value. Included here to show where you'd set a different bucket
fromPrefix: '/tmp/spec/spaces'
toPrefix: '/tmp/spec/copy_spaces'
(err, count) ->
expect(err).toBeFalsy()
# returns the number of copied objects
expect(count).toBe 2
client.listPageOfKeys
maxKeys: 2
prefix: '/tmp/spec/copy_spaces'
(err, page) ->
expect(err).toBeFalsy()
expect(
(Key for {Key} in page.Contents).sort()
).toEqual destinationKeys.sort()
done()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985895156860352,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-cluster-setup-master-cumulative.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")
cluster = require("cluster")
assert cluster.isMaster
assert.deepEqual cluster.settings, {}, "cluster.settings should not be initialized until needed"
cluster.setupMaster()
assert.deepEqual cluster.settings,
args: process.argv.slice(2)
exec: process.argv[1]
execArgv: process.execArgv
silent: false
console.log "ok sets defaults"
cluster.setupMaster exec: "overridden"
assert.strictEqual cluster.settings.exec, "overridden"
console.log "ok overrids defaults"
cluster.setupMaster args: [
"foo"
"bar"
]
assert.strictEqual cluster.settings.exec, "overridden"
assert.deepEqual cluster.settings.args, [
"foo"
"bar"
]
cluster.setupMaster execArgv: [
"baz"
"bang"
]
assert.strictEqual cluster.settings.exec, "overridden"
assert.deepEqual cluster.settings.args, [
"foo"
"bar"
]
assert.deepEqual cluster.settings.execArgv, [
"baz"
"bang"
]
console.log "ok preserves unchanged settings on repeated calls"
cluster.setupMaster()
assert.deepEqual cluster.settings,
args: [
"foo"
"bar"
]
exec: "overridden"
execArgv: [
"baz"
"bang"
]
silent: false
console.log "ok preserves current settings"
| 1920 | # 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")
cluster = require("cluster")
assert cluster.isMaster
assert.deepEqual cluster.settings, {}, "cluster.settings should not be initialized until needed"
cluster.setupMaster()
assert.deepEqual cluster.settings,
args: process.argv.slice(2)
exec: process.argv[1]
execArgv: process.execArgv
silent: false
console.log "ok sets defaults"
cluster.setupMaster exec: "overridden"
assert.strictEqual cluster.settings.exec, "overridden"
console.log "ok overrids defaults"
cluster.setupMaster args: [
"foo"
"bar"
]
assert.strictEqual cluster.settings.exec, "overridden"
assert.deepEqual cluster.settings.args, [
"foo"
"bar"
]
cluster.setupMaster execArgv: [
"baz"
"bang"
]
assert.strictEqual cluster.settings.exec, "overridden"
assert.deepEqual cluster.settings.args, [
"foo"
"bar"
]
assert.deepEqual cluster.settings.execArgv, [
"baz"
"bang"
]
console.log "ok preserves unchanged settings on repeated calls"
cluster.setupMaster()
assert.deepEqual cluster.settings,
args: [
"foo"
"bar"
]
exec: "overridden"
execArgv: [
"baz"
"bang"
]
silent: false
console.log "ok preserves current settings"
| 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")
cluster = require("cluster")
assert cluster.isMaster
assert.deepEqual cluster.settings, {}, "cluster.settings should not be initialized until needed"
cluster.setupMaster()
assert.deepEqual cluster.settings,
args: process.argv.slice(2)
exec: process.argv[1]
execArgv: process.execArgv
silent: false
console.log "ok sets defaults"
cluster.setupMaster exec: "overridden"
assert.strictEqual cluster.settings.exec, "overridden"
console.log "ok overrids defaults"
cluster.setupMaster args: [
"foo"
"bar"
]
assert.strictEqual cluster.settings.exec, "overridden"
assert.deepEqual cluster.settings.args, [
"foo"
"bar"
]
cluster.setupMaster execArgv: [
"baz"
"bang"
]
assert.strictEqual cluster.settings.exec, "overridden"
assert.deepEqual cluster.settings.args, [
"foo"
"bar"
]
assert.deepEqual cluster.settings.execArgv, [
"baz"
"bang"
]
console.log "ok preserves unchanged settings on repeated calls"
cluster.setupMaster()
assert.deepEqual cluster.settings,
args: [
"foo"
"bar"
]
exec: "overridden"
execArgv: [
"baz"
"bang"
]
silent: false
console.log "ok preserves current settings"
|
[
{
"context": "v>\n </div>')\n\n person =\n firstname: 'Jasmine'\n lastname: 'Taylor'\n email: 'jasm",
"end": 345,
"score": 0.9996112585067749,
"start": 338,
"tag": "NAME",
"value": "Jasmine"
},
{
"context": "mine'\n lastname: 'Taylor'\n email: 'jasmine.tailor@example.com'\n\n directives =\n name: (element) -> (\"#{@",
"end": 417,
"score": 0.9999244213104248,
"start": 391,
"tag": "EMAIL",
"value": "jasmine.tailor@example.com"
},
{
"context": "<div class=\"person\">\n <span class=\"name\">Jasmine Taylor</span>\n <span class=\"email\">jasmine.tail",
"end": 602,
"score": 0.9996435642242432,
"start": 588,
"tag": "NAME",
"value": "Jasmine Taylor"
},
{
"context": "smine Taylor</span>\n <span class=\"email\">jasmine.tailor@example.com</span>\n </div>\n </div>')\n\n doc.fin",
"end": 666,
"score": 0.9999227523803711,
"start": 640,
"tag": "EMAIL",
"value": "jasmine.tailor@example.com"
},
{
"context": ">\n </div>')\n\n person =\n firstname: 'Jasmine'\n lastname: 'Taylor'\n email: 'ja",
"end": 1242,
"score": 0.9994726181030273,
"start": 1235,
"tag": "NAME",
"value": "Jasmine"
},
{
"context": "ne'\n lastname: 'Taylor'\n email: 'jasmine.taylor@example.com'\n friends: [\n firstname: 'John'\n ",
"end": 1316,
"score": 0.9999234080314636,
"start": 1290,
"tag": "EMAIL",
"value": "jasmine.taylor@example.com"
},
{
"context": "mple.com'\n friends: [\n firstname: 'John'\n lastname: 'Mayer'\n email: 'j",
"end": 1362,
"score": 0.9993129968643188,
"start": 1358,
"tag": "NAME",
"value": "John"
},
{
"context": "n'\n lastname: 'Mayer'\n email: 'john.mayer@example.com'\n ,\n firstname: 'Damien'\n last",
"end": 1433,
"score": 0.9999243021011353,
"start": 1411,
"tag": "EMAIL",
"value": "john.mayer@example.com"
},
{
"context": "hn.mayer@example.com'\n ,\n firstname: 'Damien'\n lastname: 'Rice'\n email: 'da",
"end": 1469,
"score": 0.9995779991149902,
"start": 1463,
"tag": "NAME",
"value": "Damien"
},
{
"context": "en'\n lastname: 'Rice'\n email: 'damien.rice@example.com'\n ]\n\n nameDecorator = (element) -> (\"#{@f",
"end": 1540,
"score": 0.9999254941940308,
"start": 1517,
"tag": "EMAIL",
"value": "damien.rice@example.com"
},
{
"context": "<div class=\"person\">\n <span class=\"name\">Jasmine Taylor</span>\n <span class=\"email\">jasmine.tayl",
"end": 1811,
"score": 0.9992589950561523,
"start": 1797,
"tag": "NAME",
"value": "Jasmine Taylor"
},
{
"context": "smine Taylor</span>\n <span class=\"email\">jasmine.taylor@example.com</span>\n <div class=\"friends\">\n ",
"end": 1875,
"score": 0.9999254941940308,
"start": 1849,
"tag": "EMAIL",
"value": "jasmine.taylor@example.com"
},
{
"context": " class=\"friend\">\n <span class=\"name\">John Mayer</span>\n <span class=\"email\">john.may",
"end": 1991,
"score": 0.9995474815368652,
"start": 1981,
"tag": "NAME",
"value": "John Mayer"
},
{
"context": "hn Mayer</span>\n <span class=\"email\">john.mayer@example.com</span>\n </div>\n <div class=",
"end": 2055,
"score": 0.9999049305915833,
"start": 2033,
"tag": "EMAIL",
"value": "john.mayer@example.com"
},
{
"context": " class=\"friend\">\n <span class=\"name\">Damien Rice</span>\n <span class=\"email\">damien.r",
"end": 2159,
"score": 0.9998790621757507,
"start": 2148,
"tag": "NAME",
"value": "Damien Rice"
},
{
"context": "ien Rice</span>\n <span class=\"email\">damien.rice@example.com</span>\n </div>\n </div>\n ",
"end": 2224,
"score": 0.9999184608459473,
"start": 2201,
"tag": "EMAIL",
"value": "damien.rice@example.com"
}
] | spec/directives.spec.coffee | dineshkummarc/transparency | 1 | require './spec_helper'
require '../src/jquery.transparency'
describe "Transparency", ->
it "should calculate values with directives", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
firstname: 'Jasmine'
lastname: 'Taylor'
email: 'jasmine.tailor@example.com'
directives =
name: (element) -> ("#{@firstname} #{@lastname}")
expected = jQuery(
'<div>
<div class="person">
<span class="name">Jasmine Taylor</span>
<span class="email">jasmine.tailor@example.com</span>
</div>
</div>')
doc.find('.person').render(person, directives)
expect(doc.html()).htmlToBeEqual(expected.html())
it "should handle nested directives", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
<div class="friends">
<div class="friend">
<span class="name"></span>
<span class="email"></span>
</div>
</div>
</div>
</div>')
person =
firstname: 'Jasmine'
lastname: 'Taylor'
email: 'jasmine.taylor@example.com'
friends: [
firstname: 'John'
lastname: 'Mayer'
email: 'john.mayer@example.com'
,
firstname: 'Damien'
lastname: 'Rice'
email: 'damien.rice@example.com'
]
nameDecorator = (element) -> ("#{@firstname} #{@lastname}")
directives =
name: nameDecorator
friends:
name: nameDecorator
expected = jQuery(
'<div>
<div class="person">
<span class="name">Jasmine Taylor</span>
<span class="email">jasmine.taylor@example.com</span>
<div class="friends">
<div class="friend">
<span class="name">John Mayer</span>
<span class="email">john.mayer@example.com</span>
</div>
<div class="friend">
<span class="name">Damien Rice</span>
<span class="email">damien.rice@example.com</span>
</div>
</div>
</div>
</div>')
doc.find('.person').render(person, directives)
expect(doc.html()).htmlToBeEqual(expected.html())
| 185466 | require './spec_helper'
require '../src/jquery.transparency'
describe "Transparency", ->
it "should calculate values with directives", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
firstname: '<NAME>'
lastname: 'Taylor'
email: '<EMAIL>'
directives =
name: (element) -> ("#{@firstname} #{@lastname}")
expected = jQuery(
'<div>
<div class="person">
<span class="name"><NAME></span>
<span class="email"><EMAIL></span>
</div>
</div>')
doc.find('.person').render(person, directives)
expect(doc.html()).htmlToBeEqual(expected.html())
it "should handle nested directives", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
<div class="friends">
<div class="friend">
<span class="name"></span>
<span class="email"></span>
</div>
</div>
</div>
</div>')
person =
firstname: '<NAME>'
lastname: 'Taylor'
email: '<EMAIL>'
friends: [
firstname: '<NAME>'
lastname: 'Mayer'
email: '<EMAIL>'
,
firstname: '<NAME>'
lastname: 'Rice'
email: '<EMAIL>'
]
nameDecorator = (element) -> ("#{@firstname} #{@lastname}")
directives =
name: nameDecorator
friends:
name: nameDecorator
expected = jQuery(
'<div>
<div class="person">
<span class="name"><NAME></span>
<span class="email"><EMAIL></span>
<div class="friends">
<div class="friend">
<span class="name"><NAME></span>
<span class="email"><EMAIL></span>
</div>
<div class="friend">
<span class="name"><NAME></span>
<span class="email"><EMAIL></span>
</div>
</div>
</div>
</div>')
doc.find('.person').render(person, directives)
expect(doc.html()).htmlToBeEqual(expected.html())
| true | require './spec_helper'
require '../src/jquery.transparency'
describe "Transparency", ->
it "should calculate values with directives", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
</div>
</div>')
person =
firstname: 'PI:NAME:<NAME>END_PI'
lastname: 'Taylor'
email: 'PI:EMAIL:<EMAIL>END_PI'
directives =
name: (element) -> ("#{@firstname} #{@lastname}")
expected = jQuery(
'<div>
<div class="person">
<span class="name">PI:NAME:<NAME>END_PI</span>
<span class="email">PI:EMAIL:<EMAIL>END_PI</span>
</div>
</div>')
doc.find('.person').render(person, directives)
expect(doc.html()).htmlToBeEqual(expected.html())
it "should handle nested directives", ->
doc = jQuery(
'<div>
<div class="person">
<span class="name"></span>
<span class="email"></span>
<div class="friends">
<div class="friend">
<span class="name"></span>
<span class="email"></span>
</div>
</div>
</div>
</div>')
person =
firstname: 'PI:NAME:<NAME>END_PI'
lastname: 'Taylor'
email: 'PI:EMAIL:<EMAIL>END_PI'
friends: [
firstname: 'PI:NAME:<NAME>END_PI'
lastname: 'Mayer'
email: 'PI:EMAIL:<EMAIL>END_PI'
,
firstname: 'PI:NAME:<NAME>END_PI'
lastname: 'Rice'
email: 'PI:EMAIL:<EMAIL>END_PI'
]
nameDecorator = (element) -> ("#{@firstname} #{@lastname}")
directives =
name: nameDecorator
friends:
name: nameDecorator
expected = jQuery(
'<div>
<div class="person">
<span class="name">PI:NAME:<NAME>END_PI</span>
<span class="email">PI:EMAIL:<EMAIL>END_PI</span>
<div class="friends">
<div class="friend">
<span class="name">PI:NAME:<NAME>END_PI</span>
<span class="email">PI:EMAIL:<EMAIL>END_PI</span>
</div>
<div class="friend">
<span class="name">PI:NAME:<NAME>END_PI</span>
<span class="email">PI:EMAIL:<EMAIL>END_PI</span>
</div>
</div>
</div>
</div>')
doc.find('.person').render(person, directives)
expect(doc.html()).htmlToBeEqual(expected.html())
|
[
{
"context": "\n model: @dataSource\n key: \"keywords\"\n\n @$el.prepend @searchInput.render().$el\n",
"end": 4199,
"score": 0.6265037655830383,
"start": 4191,
"tag": "KEY",
"value": "keywords"
}
] | app/vendor/kalnoy/cruddy/resources/assets/coffee/inputs/entitySelector.coffee | EH7AN/lawyers | 0 | class Cruddy.Inputs.EntitySelector extends Cruddy.Inputs.Base
className: "entity-selector"
events:
"click .items>.item": "checkItem"
"click .more": "loadMore"
"click .btn-add": "showNewForm"
"click .btn-refresh": "refresh"
"click [type=search]": -> false
initialize: (options) ->
super
@filter = options.filter ? false
@multiple = options.multiple ? false
@reference = options.reference
@allowSearch = options.allowSearch ? yes
@allowCreate = options.allowCreate ? yes and @reference.createPermitted()
@attributesForNewModel = {}
@makeSelectedMap @getValue()
if @reference.readPermitted()
@primaryKey = "id"
@dataSource = @reference.search ajaxOptions: data: owner: options.owner
@listenTo @dataSource, "request", @displayLoading
@listenTo @dataSource, "data", @renderItems
this
getValue: -> super or if @multiple then [] else null
displayLoading: (dataSource, xhr) ->
@$el.addClass "loading"
xhr.always => @$el.removeClass "loading"
this
maybeLoadMore: ->
height = @items.parent().height()
@loadMore() if @$more? and height > 0 and height + 50 > @$more.position().top
this
refresh: (e) ->
if e
e.preventDefault()
e.stopPropagation()
@dataSource.refresh()
return
checkItem: (e) ->
e.preventDefault()
e.stopPropagation()
@selectItem @dataSource.getById $(e.target).data("id")
return
selectItem: (item) ->
return if not item
if @multiple
if item.id of @selected
value = _.filter @getValue(), (_item) -> _item.id.toString() != item.id.toString()
else
value = _.clone @getValue()
value.push item
else
value = item
@setValue value
loadMore: ->
return if not @dataSource or @dataSource.inProgress()
@dataSource.next()
false
showNewForm: (e) ->
if e
e.preventDefault()
e.stopPropagation()
return if @newModelForm
instance = @reference.createInstance attributes: @attributesForNewModel
@newModelForm = form = Cruddy.Entity.Form.display instance
form.once "remove", => @newModelForm = null
form.once "created", (model, resp) =>
@selectItem model.meta
form.remove()
return
this
applyChanges: (data) ->
@makeSelectedMap data
@renderItems()
makeSelectedMap: (data) ->
@selected = {}
return this unless data
if @multiple
@selected[item.id] = yes for item in data
else
@selected[data.id] = yes if data?
this
renderItems: ->
@$more = null
html = ""
if @dataSource.data.length or @dataSource.more
html += @renderItem item for item in @dataSource.data
html += """<li class="more">#{ Cruddy.lang.more }</li>""" if @dataSource.more
else
html += """<li class="empty">#{ Cruddy.lang.no_results }</li>"""
@items.html html
if @dataSource.more
@$more = @items.children ".more"
@maybeLoadMore()
this
renderItem: (item) ->
className = if item.id of @selected then "selected" else ""
"""<li class="item #{ className }" data-id="#{ item.id }">#{ item.title }</li>"""
render: ->
if @reference.readPermitted()
@dispose()
@$el.html @template()
@items = @$ ".items"
@renderItems()
@items.parent().on "scroll", $.proxy this, "maybeLoadMore"
@renderSearch() if @allowSearch
@dataSource.refresh() if @dataSource.isEmpty()
else
@$el.html "<span class=error>#{ Cruddy.lang.forbidden }</span>"
this
renderSearch: ->
@searchInput = new Cruddy.Inputs.Search
model: @dataSource
key: "keywords"
@$el.prepend @searchInput.render().$el
@searchInput.$el.wrap "<div class=search-input-container></div>"
@searchInput.appendButton """
<button type="button" class="btn btn-default btn-refresh" tabindex="-1" title="#{ Cruddy.lang.refresh }">
<span class="glyphicon glyphicon-refresh"></span>
</button>
"""
@searchInput.appendButton """
<button type="button" class='btn btn-default btn-add' tabindex='-1' title="#{ Cruddy.lang.model_new_record }">
<span class='glyphicon glyphicon-plus'></span>
</button>
""" if @allowCreate
this
template: -> """<div class="items-container"><ul class="items"></ul></div>"""
focus: ->
@searchInput?.focus() or @entity.done => @searchInput.focus()
this
dispose: ->
@searchInput?.remove()
@newModelForm?.remove()
this
remove: ->
@dispose()
super
| 11658 | class Cruddy.Inputs.EntitySelector extends Cruddy.Inputs.Base
className: "entity-selector"
events:
"click .items>.item": "checkItem"
"click .more": "loadMore"
"click .btn-add": "showNewForm"
"click .btn-refresh": "refresh"
"click [type=search]": -> false
initialize: (options) ->
super
@filter = options.filter ? false
@multiple = options.multiple ? false
@reference = options.reference
@allowSearch = options.allowSearch ? yes
@allowCreate = options.allowCreate ? yes and @reference.createPermitted()
@attributesForNewModel = {}
@makeSelectedMap @getValue()
if @reference.readPermitted()
@primaryKey = "id"
@dataSource = @reference.search ajaxOptions: data: owner: options.owner
@listenTo @dataSource, "request", @displayLoading
@listenTo @dataSource, "data", @renderItems
this
getValue: -> super or if @multiple then [] else null
displayLoading: (dataSource, xhr) ->
@$el.addClass "loading"
xhr.always => @$el.removeClass "loading"
this
maybeLoadMore: ->
height = @items.parent().height()
@loadMore() if @$more? and height > 0 and height + 50 > @$more.position().top
this
refresh: (e) ->
if e
e.preventDefault()
e.stopPropagation()
@dataSource.refresh()
return
checkItem: (e) ->
e.preventDefault()
e.stopPropagation()
@selectItem @dataSource.getById $(e.target).data("id")
return
selectItem: (item) ->
return if not item
if @multiple
if item.id of @selected
value = _.filter @getValue(), (_item) -> _item.id.toString() != item.id.toString()
else
value = _.clone @getValue()
value.push item
else
value = item
@setValue value
loadMore: ->
return if not @dataSource or @dataSource.inProgress()
@dataSource.next()
false
showNewForm: (e) ->
if e
e.preventDefault()
e.stopPropagation()
return if @newModelForm
instance = @reference.createInstance attributes: @attributesForNewModel
@newModelForm = form = Cruddy.Entity.Form.display instance
form.once "remove", => @newModelForm = null
form.once "created", (model, resp) =>
@selectItem model.meta
form.remove()
return
this
applyChanges: (data) ->
@makeSelectedMap data
@renderItems()
makeSelectedMap: (data) ->
@selected = {}
return this unless data
if @multiple
@selected[item.id] = yes for item in data
else
@selected[data.id] = yes if data?
this
renderItems: ->
@$more = null
html = ""
if @dataSource.data.length or @dataSource.more
html += @renderItem item for item in @dataSource.data
html += """<li class="more">#{ Cruddy.lang.more }</li>""" if @dataSource.more
else
html += """<li class="empty">#{ Cruddy.lang.no_results }</li>"""
@items.html html
if @dataSource.more
@$more = @items.children ".more"
@maybeLoadMore()
this
renderItem: (item) ->
className = if item.id of @selected then "selected" else ""
"""<li class="item #{ className }" data-id="#{ item.id }">#{ item.title }</li>"""
render: ->
if @reference.readPermitted()
@dispose()
@$el.html @template()
@items = @$ ".items"
@renderItems()
@items.parent().on "scroll", $.proxy this, "maybeLoadMore"
@renderSearch() if @allowSearch
@dataSource.refresh() if @dataSource.isEmpty()
else
@$el.html "<span class=error>#{ Cruddy.lang.forbidden }</span>"
this
renderSearch: ->
@searchInput = new Cruddy.Inputs.Search
model: @dataSource
key: "<KEY>"
@$el.prepend @searchInput.render().$el
@searchInput.$el.wrap "<div class=search-input-container></div>"
@searchInput.appendButton """
<button type="button" class="btn btn-default btn-refresh" tabindex="-1" title="#{ Cruddy.lang.refresh }">
<span class="glyphicon glyphicon-refresh"></span>
</button>
"""
@searchInput.appendButton """
<button type="button" class='btn btn-default btn-add' tabindex='-1' title="#{ Cruddy.lang.model_new_record }">
<span class='glyphicon glyphicon-plus'></span>
</button>
""" if @allowCreate
this
template: -> """<div class="items-container"><ul class="items"></ul></div>"""
focus: ->
@searchInput?.focus() or @entity.done => @searchInput.focus()
this
dispose: ->
@searchInput?.remove()
@newModelForm?.remove()
this
remove: ->
@dispose()
super
| true | class Cruddy.Inputs.EntitySelector extends Cruddy.Inputs.Base
className: "entity-selector"
events:
"click .items>.item": "checkItem"
"click .more": "loadMore"
"click .btn-add": "showNewForm"
"click .btn-refresh": "refresh"
"click [type=search]": -> false
initialize: (options) ->
super
@filter = options.filter ? false
@multiple = options.multiple ? false
@reference = options.reference
@allowSearch = options.allowSearch ? yes
@allowCreate = options.allowCreate ? yes and @reference.createPermitted()
@attributesForNewModel = {}
@makeSelectedMap @getValue()
if @reference.readPermitted()
@primaryKey = "id"
@dataSource = @reference.search ajaxOptions: data: owner: options.owner
@listenTo @dataSource, "request", @displayLoading
@listenTo @dataSource, "data", @renderItems
this
getValue: -> super or if @multiple then [] else null
displayLoading: (dataSource, xhr) ->
@$el.addClass "loading"
xhr.always => @$el.removeClass "loading"
this
maybeLoadMore: ->
height = @items.parent().height()
@loadMore() if @$more? and height > 0 and height + 50 > @$more.position().top
this
refresh: (e) ->
if e
e.preventDefault()
e.stopPropagation()
@dataSource.refresh()
return
checkItem: (e) ->
e.preventDefault()
e.stopPropagation()
@selectItem @dataSource.getById $(e.target).data("id")
return
selectItem: (item) ->
return if not item
if @multiple
if item.id of @selected
value = _.filter @getValue(), (_item) -> _item.id.toString() != item.id.toString()
else
value = _.clone @getValue()
value.push item
else
value = item
@setValue value
loadMore: ->
return if not @dataSource or @dataSource.inProgress()
@dataSource.next()
false
showNewForm: (e) ->
if e
e.preventDefault()
e.stopPropagation()
return if @newModelForm
instance = @reference.createInstance attributes: @attributesForNewModel
@newModelForm = form = Cruddy.Entity.Form.display instance
form.once "remove", => @newModelForm = null
form.once "created", (model, resp) =>
@selectItem model.meta
form.remove()
return
this
applyChanges: (data) ->
@makeSelectedMap data
@renderItems()
makeSelectedMap: (data) ->
@selected = {}
return this unless data
if @multiple
@selected[item.id] = yes for item in data
else
@selected[data.id] = yes if data?
this
renderItems: ->
@$more = null
html = ""
if @dataSource.data.length or @dataSource.more
html += @renderItem item for item in @dataSource.data
html += """<li class="more">#{ Cruddy.lang.more }</li>""" if @dataSource.more
else
html += """<li class="empty">#{ Cruddy.lang.no_results }</li>"""
@items.html html
if @dataSource.more
@$more = @items.children ".more"
@maybeLoadMore()
this
renderItem: (item) ->
className = if item.id of @selected then "selected" else ""
"""<li class="item #{ className }" data-id="#{ item.id }">#{ item.title }</li>"""
render: ->
if @reference.readPermitted()
@dispose()
@$el.html @template()
@items = @$ ".items"
@renderItems()
@items.parent().on "scroll", $.proxy this, "maybeLoadMore"
@renderSearch() if @allowSearch
@dataSource.refresh() if @dataSource.isEmpty()
else
@$el.html "<span class=error>#{ Cruddy.lang.forbidden }</span>"
this
renderSearch: ->
@searchInput = new Cruddy.Inputs.Search
model: @dataSource
key: "PI:KEY:<KEY>END_PI"
@$el.prepend @searchInput.render().$el
@searchInput.$el.wrap "<div class=search-input-container></div>"
@searchInput.appendButton """
<button type="button" class="btn btn-default btn-refresh" tabindex="-1" title="#{ Cruddy.lang.refresh }">
<span class="glyphicon glyphicon-refresh"></span>
</button>
"""
@searchInput.appendButton """
<button type="button" class='btn btn-default btn-add' tabindex='-1' title="#{ Cruddy.lang.model_new_record }">
<span class='glyphicon glyphicon-plus'></span>
</button>
""" if @allowCreate
this
template: -> """<div class="items-container"><ul class="items"></ul></div>"""
focus: ->
@searchInput?.focus() or @entity.done => @searchInput.focus()
this
dispose: ->
@searchInput?.remove()
@newModelForm?.remove()
this
remove: ->
@dispose()
super
|
[
{
"context": " from awesome\n Atom-terminal-panel\n Copyright by isis97/VadimDor\n MIT licensed\n\n The main terminal view",
"end": 87,
"score": 0.9996684193611145,
"start": 81,
"tag": "USERNAME",
"value": "isis97"
},
{
"context": "esome\n Atom-terminal-panel\n Copyright by isis97/VadimDor\n MIT licensed\n\n The main terminal view class, w",
"end": 96,
"score": 0.9956873059272766,
"start": 88,
"tag": "USERNAME",
"value": "VadimDor"
},
{
"context": "gramSSH = execSSH('echo dada', {\n user: 'admin123'\n host: 'vps123.ovh.net'\n passp",
"end": 46857,
"score": 0.9995625615119934,
"start": 46849,
"tag": "USERNAME",
"value": "admin123"
},
{
"context": " host: 'vps123.ovh.net'\n passphrase: '123'\n key: 'c:/users/user1/.ssh/id_rsa'\n ",
"end": 46918,
"score": 0.999190092086792,
"start": 46915,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "net'\n passphrase: '123'\n key: 'c:/users/user1/.ssh/id_rsa'\n password: '123-2000'\n",
"end": 46945,
"score": 0.6494365334510803,
"start": 46939,
"tag": "KEY",
"value": "users/"
},
{
"context": " passphrase: '123'\n key: 'c:/users/user1/.ssh/id_rsa'\n password: '123-2000'\n timeout",
"end": 46962,
"score": 0.7189178466796875,
"start": 46949,
"tag": "KEY",
"value": "1/.ssh/id_rsa"
},
{
"context": "'c:/users/user1/.ssh/id_rsa'\n password: '123-2000'\n timeout: 10000\n }, processCall",
"end": 46993,
"score": 0.9992194175720215,
"start": 46985,
"tag": "PASSWORD",
"value": "123-2000"
},
{
"context": "showCmd()\n\n try\n connect {\n user: 'admin123'\n host: 'vps123.ovh.net'\n #passphra",
"end": 52395,
"score": 0.9996469020843506,
"start": 52387,
"tag": "USERNAME",
"value": "admin123"
},
{
"context": " host: 'vps123.ovh.net'\n #passphrase: '123'\n #key: 'c:/users/user1/.ssh/id_rsa'\n ",
"end": 52453,
"score": 0.9990267157554626,
"start": 52450,
"tag": "PASSWORD",
"value": "123"
},
{
"context": ": 'c:/users/user1/.ssh/id_rsa'\n password: '123-2000'\n timeout: 10000\n }, sshCallback\n ",
"end": 52525,
"score": 0.9991850852966309,
"start": 52517,
"tag": "PASSWORD",
"value": "123-2000"
}
] | lib/atp-view.coffee | VadimDor/terminalix | 1 | ###
Terminalix plugin forked from awesome
Atom-terminal-panel
Copyright by isis97/VadimDor
MIT licensed
The main terminal view class, which does the most of all the work.
###
#coffeelint: disable=max_line_length
lastOpenedView = null
fs = include 'fs'
os = include 'os'
{$, TextEditorView, View} = include 'atom-space-pen-views'
{spawn, exec, execSync} = include 'child_process'
{execR, execSyncR} = include 'ssh2-exec'
{connR} = include 'ssh2-connect'
EventEmitter = (include 'events').EventEmitter
{resolve, dirname, extname, sep} = include 'path'
findConfig = include 'find-config'
yaml = include 'js-yaml'
connect = include 'ssh2-connect'
exec_SSH = include 'ssh2-exec'
execSSH = include 'ssh-exec-plus'
ansihtml = include 'ansi-html-stream'
stream = include 'stream'
iconv = include 'iconv-lite'
ATPCommandFinderView = include 'atp-command-finder'
ATPCore = include 'atp-core'
ATPCommandsBuiltins = include 'atp-builtins-commands'
ATPVariablesBuiltins = include 'atp-builtins-variables'
window.$ = window.jQuery = $
include 'jquery-autocomplete-js'
module.exports =
class ATPOutputView extends View
cwd: null
#streamsEncoding: 'iso-8859-3'
streamsEncoding : '"'+atom.config.get('terminalix.textEncode')+'"'
_cmdintdel: 50
echoOn: true
configFileFtp: null
redirectOutput: ''
specsMode: false
inputLine: 0
helloMessageShown: false
minHeight: 250
util: include 'atp-terminal-util'
currentInputBox: null
#currentInputBox: null
currentInputBoxTmr: null
volatileSuggestions: []
disposables:
dispose: (field) =>
if not this[field]?
this[field] = []
a = this[field]
for i in [0..a.length-1] by 1
a[i].dispose()
add: (field, value) =>
if not this[field]?
this[field] = []
this[field].push value
keyCodes: {
enter: 13
arrowUp: 38
arrowDown: 40
arrowLeft: 37
arrowRight: 39
}
localCommandAtomBindings: []
localCommands: ATPCommandsBuiltins
@content: ->
@div tabIndex: -1, class: 'panel atp-panel panel-bottom', outlet: 'atpView', =>
@div class: 'terminal panel-divider', style: 'cursor:n-resize;width:100%;height:8px;', outlet: 'panelDivider'
@button outlet: 'maximizeIconBtn', class: 'atp-maximize-btn', click: 'maximize'
@button outlet: 'closeIconBtn', class: 'atp-close-btn', click: 'close'
@button outlet: 'destroyIconBtn', class: 'atp-destroy-btn', click: 'destroy'
@div class: 'panel-heading btn-toolbar', outlet:'consoleToolbarHeading', =>
@div class: 'btn-group', outlet:'consoleToolbar', =>
@button outlet: 'killBtn', click: 'kill', class: 'btn hide', =>
@span 'kill'
@button outlet: 'exitBtn', click: 'destroy', class: 'btn', =>
@span 'exit'
@button outlet: 'closeBtn', click: 'close', class: 'btn', =>
@span class: "icon icon-x"
@span 'close'
@button outlet: 'openConfigBtn', class: 'btn icon icon-gear inline-block-tight button-settings', click: 'showSettings', =>
@span 'Open config'
@button outlet: 'reloadConfigBtn', class: 'btn icon icon-gear inline-block-tight button-settings', click: 'reloadSettings', =>
@span 'Reload config'
@div class: 'atp-panel-body', =>
@pre class: "terminal", outlet: "cliOutput"
toggleAutoCompletion: () ->
if @currentInputBoxCmp?
@currentInputBoxCmp.enable()
@currentInputBoxCmp.repaint()
@currentInputBoxCmp.showDropDown()
@currentInputBox.find('.terminal-input').height('100px')
fsSpy: () ->
@volatileSuggestions = []
if @cwd?
fs.readdir @cwd, (err, files) =>
if files?
for file in files
@volatileSuggestions.push file
turnSpecsMode: (state) ->
@specsMode = state
getRawOutput: () ->
t = @getHtmlOutput().replace(/<[^>]*>/igm, "")
t = @util.replaceAll ">", ">", t
t = @util.replaceAll "<", "<", t
t = @util.replaceAll """, "\"", t
return t
getHtmlOutput: () ->
return @cliOutput.html()
resolvePath: (path) ->
path = @util.replaceAll '\"', '', path
filepath = ''
if path.match(/([A-Za-z]):/ig) != null
filepath = path
else
filepath = @getCwd() + '/' + path
filepath = @util.replaceAll '\\', '/', filepath
return @util.replaceAll '\\', '/', (resolve filepath)
reloadSettings: () ->
@onCommand 'update'
showSettings: () ->
setTimeout () ->
panelPath = atom.packages.resolvePackagePath 'terminalix'
atomPath = resolve panelPath+'/../..'
configPath = atomPath + '/terminal-commands.json'
atom.workspace.open configPath
, 50
focusInputBox: () ->
if @currentInputBoxCmp?
@currentInputBoxCmp.input.focus()
updateInputCursor: (textarea) ->
@rawMessage 'test\n'
val = textarea.val()
textarea
.blur()
.focus()
.val("")
.val(val)
removeInputBox: () ->
@cliOutput.find('.atp-dynamic-input-box').remove()
putInputBox: () ->
if @currentInputBoxTmr?
clearInterval @currentInputBoxTmr
@currentInputBoxTmr = null
@cliOutput.find('.atp-dynamic-input-box').remove()
prompt = @getCommandPrompt('')
@currentInputBox = $(
'<div style="width: 100%; white-space:nowrap; overflow:hidden; display:inline-block;" class="atp-dynamic-input-box">' +
'<div style="position:relative; top:5px; max-height:500px; width: 100%; bottom: -10px; height: 20px; white-space:nowrap; overflow:hidden; display:inline-block;" class="terminal-input native-key-bindings"></div>' +
'</div>'
)
@currentInputBox.prepend ' '
@currentInputBox.prepend prompt
#@cliOutput.mousedown (e) =>
# if e.which is 1
# @focusInputBox()
history = []
if @currentInputBoxCmp?
history = @currentInputBoxCmp.getInputHistory()
inputComp = @currentInputBox.find '.terminal-input'
@currentInputBoxCmp = inputComp.autocomplete {
animation: [
['opacity', 0, 0.8]
]
isDisabled: true
inputHistory: history
inputWidth: '80%'
dropDownWidth: '30%'
dropDownDescriptionBoxWidth: '30%'
dropDownPosition: 'top'
showDropDown: atom.config.get 'terminalix.enableConsoleSuggestionsDropdown'
}
@currentInputBoxCmp
.confirmed(() =>
@currentInputBoxCmp.disable().repaint()
@onCommand()
).changed((inst, text) =>
if inst.getText().length <= 0
@currentInputBoxCmp.disable().repaint()
@currentInputBox.find('.terminal-input').height('20px')
)
@currentInputBoxCmp.input.keydown((e) =>
if (e.keyCode == 17) and (@currentInputBoxCmp.getText().length > 0)
###
@currentInputBoxCmp.enable().repaint()
@currentInputBoxCmp.showDropDown()
@currentInputBox.find('.terminal-input').height('100px');
###
else if (e.keyCode == 32) or (e.keyCode == 8)
@currentInputBoxCmp.disable().repaint()
@currentInputBox.find('.terminal-input').height('20px')
)
endsWith = (text, suffix) ->
return text.indexOf(suffix, text.length - suffix.length) != -1
@currentInputBoxCmp.options = (instance, text, lastToken) =>
token = lastToken
if not token?
token = ''
if not (endsWith(token, '/') or endsWith(token, '\\'))
token = @util.replaceAll '\\', sep, token
token = token.split sep
token.pop()
token = token.join(sep)
if not endsWith(token, sep)
token = token + sep
o = @getCommandsNames().concat(@volatileSuggestions)
fsStat = []
if token?
try
fsStat = fs.readdirSync(token)
for i in [0..fsStat.length-1] by 1
fsStat[i] = token + fsStat[i]
catch e
ret = o.concat(fsStat)
return ret
@currentInputBoxCmp.hideDropDown()
setTimeout () =>
@currentInputBoxCmp.input.focus()
, 0
@cliOutput.append @currentInputBox
inputBoxState: () ->
inputState = @cliOutput.find('.atp-dynamic-input-box').clone()
inputState.find('.autocomplete-wrapper').replaceWith () ->
input = $(this).find('.autocomplete-input')[0]
return $('<span/>', class: input.className, text: input.value)
inputState.removeClass 'atp-dynamic-input-box'
return inputState.prop('outerHTML') + '\n'
readInputBox: () ->
ret = ''
if @currentInputBoxCmp?
# ret = @currentInputBox.find('.terminal-input').val()
ret = @currentInputBoxCmp.getText()
return ret
requireCSS: (location) ->
if not location?
return
location = resolve location
console.log ("Require terminalix plugin CSS file: "+location+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
$('head').append "<link rel='stylesheet' type='text/css' href='#{location}'/>"
resolvePluginDependencies: (path, plugin) ->
config = plugin.dependencies
if not config?
return
css_dependencies = config.css
if not css_dependencies?
css_dependencies = []
for css_dependency in css_dependencies
@requireCSS path+"/"+css_dependency
delete plugin['dependencies']
init: () ->
###
TODO: test-autocomplete Remove this!
el = $('<div style="z-index: 9999; position: absolute; left: 200px; top: 200px;" id="glotest"></div>')
el.autocomplete({
inputWidth: '80%'
})
$('body').append(el)
###
@streamsEncoding = '"'+atom.config.get('terminalix.textEncode')+'"'
lastY = -1
mouseDown = false
panelDraggingActive = false
@panelDivider
.mousedown () -> panelDraggingActive = true
.mouseup () -> panelDraggingActive = false
$(document)
.mousedown () -> mouseDown = true
.mouseup () -> mouseDown = false
.mousemove (e) ->
if mouseDown and panelDraggingActive
if lastY != -1
delta = e.pageY - lastY
@cliOutput.height @cliOutput.height()-delta
lastY = e.pageY
else
lastY = -1
normalizedPath = require("path").join(__dirname, "../commands")
console.log ("Loading terminalix plugins from the directory: "+normalizedPath+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
fs.readdirSync(normalizedPath).forEach( (folder) =>
fullpath = resolve "../commands/" +folder
console.log ("Require terminalix plugin: "+folder+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
obj = require ("../commands/" +folder+"/index.coffee")
console.log "Plugin loaded." if atom.config.get('terminalix.logConsole')
@resolvePluginDependencies fullpath, obj
for key, value of obj
if value.command?
@localCommands[key] = value
@localCommands[key].source = 'external-functional'
@localCommands[key].sourcefile = folder
else if value.variable?
value.name = key
ATPVariablesBuiltins.putVariable value
)
console.log ("All plugins were loaded.") if atom.config.get('terminalix.logConsole')
if ATPCore.getConfig()?
actions = ATPCore.getConfig().actions
if actions?
for action in actions
if action.length > 1
obj = {}
obj['terminalix:'+action[0]] = () =>
@open()
@onCommand action[1]
atom.commands.add 'atom-workspace', obj
if atom.workspace?
eleqr = atom.workspace.getActivePaneItem() ? atom.workspace
eleqr = atom.views.getView(eleqr)
atomCommands = atom.commands.findCommands({target: eleqr})
for command in atomCommands
comName = command.name
com = {}
com.description = command.displayName
com.command =
((comNameP) ->
return (state, args) ->
ele = atom.workspace.getActivePaneItem() ? atom.workspace
ele = atom.views.getView(ele)
atom.commands.dispatch ele, comNameP
return (state.consoleLabel 'info', "info") + (state.consoleText 'info', 'Atom command executed: '+comNameP)
)(comName)
com.source = "internal-atom"
@localCommands[comName] = com
toolbar = ATPCore.getConfig().toolbar
if toolbar?
toolbar.reverse()
for com in toolbar
bt = $("<div class=\"btn\" data-action=\"#{com[1]}\" ><span>#{com[0]}</span></div>")
if com[2]?
atom.tooltips.add bt,
title: com[2]
@consoleToolbar.prepend bt
caller = this
bt.click () ->
caller.onCommand $(this).data('action')
return this
commandLineNotCounted: () ->
@inputLine--
parseSpecialStringTemplate: (prompt, values, isDOM=false) =>
if isDOM
return ATPVariablesBuiltins.parseHtml(this, prompt, values)
else
return ATPVariablesBuiltins.parse(this, prompt, values)
getCommandPrompt: (cmd) ->
return @parseTemplate atom.config.get('terminalix.commandPrompt'), {cmd: cmd}, true
delay: (callback, delay=100) ->
setTimeout callback, delay
execDelayedCommand: (delay, cmd, args, state) ->
caller = this
callback = ->
caller.exec cmd, args, state
setTimeout callback, delay
moveToCurrentDirectory: ()->
CURRENT_LOCATION = @getCurrentFileLocation()
if CURRENT_LOCATION?
@cd [CURRENT_LOCATION]
else if atom.project.getDirectories()[0]?
@cd [atom.project.getDirectories()[0].path]
getCurrentFileName: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getBaseName()
return null
getCurrentFileLocation: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getPath().replace ///#{current_file.getBaseName()}$///, ""
getCurrentFilePath: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getPath()
return null
getCurrentFile: ()->
if not atom.workspace?
return null
te = atom.workspace.getActiveTextEditor()
if te?
if te.getPath()?
return te.buffer.file
return null
parseTemplate: (text, vars, isDOM=false) ->
if not vars?
vars = {}
ret = ''
if isDOM
ret = ATPVariablesBuiltins.parseHtml this, text, vars
else
ret = @parseSpecialStringTemplate text, vars
ret = @util.replaceAll '%(file-original)', @getCurrentFilePath(), ret
ret = @util.replaceAll '%(cwd-original)', @getCwd(), ret
ret = @util.replaceAll '&fs;', '/', ret
ret = @util.replaceAll '&bs;', '\\', ret
return ret
parseExecToken__: (cmd, args, strArgs) ->
if strArgs?
cmd = @util.replaceAll "%(*)", strArgs, cmd
cmd = @util.replaceAll "%(*^)", (@util.replaceAll "%(*^)", "", cmd), cmd
if args?
argsNum = args.length
for i in [0..argsNum] by 1
if args[i]?
v = args[i].replace /\n/ig, ''
cmd = @util.replaceAll "%(#{i})", args[i], cmd
cmd = @parseTemplate cmd, {file:@getCurrentFilePath()}
return cmd
execStackCounter: 0
exec: (cmdStr, ref_args, state, callback) ->
if not state?
state = this
if not ref_args?
ref_args = {}
if cmdStr.split?
cmdStrC = cmdStr.split ';;'
if cmdStrC.length > 1
cmdStr = cmdStrC
@execStackCounter = 0
return @exec_ cmdStr, ref_args, state, callback
exec_: (cmdStr, ref_args, state, callback) ->
if not callback?
callback = () -> return null
++@execStackCounter
if cmdStr instanceof Array
ret = ''
for com in cmdStr
val = @exec com, ref_args, state
if val?
ret += val
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
cmdStr = @util.replaceAll "\\\"", '&hquot;', cmdStr
cmdStr = @util.replaceAll "&bs;\"", '&hquot;', cmdStr
cmdStr = @util.replaceAll "\\\'", '&lquot;', cmdStr
cmdStr = @util.replaceAll "&bs;\'", '&lquot;', cmdStr
ref_args_str = null
if ref_args?
if ref_args.join?
ref_args_str = ref_args.join(' ')
cmdStr = @parseExecToken__ cmdStr, ref_args, ref_args_str
args = []
cmd = cmdStr
cmd.replace /("[^"]*"|'[^']*'|[^\s'"]+)/g, (s) =>
if s[0] != '"' and s[0] != "'"
s = s.replace /~/g, @userHome
s = @util.replaceAll '&hquot;', '"', s
s = @util.replaceAll '&lquot;', '\'', s
args.push s
args = @util.dir args, @getCwd()
cmd = args.shift()
command = null
if @isCommandEnabled(cmd)
command = ATPCore.findUserCommand(cmd)
if command?
if not state?
ret = null
throw new Error 'The console functional (not native) command cannot be executed without caller information: \''+cmd+'\'.'
if command?
try
ret = command(state, args)
catch e
throw new Error "Error at executing terminal command: '#{cmd}' ('#{cmdStr}'): #{e.message}"
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
if atom.config.get('terminalix.enableExtendedCommands') or @specsMode
if @isCommandEnabled(cmd)
command = @getLocalCommand(cmd)
if command?
ret = command(state, args)
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
cmdStr = @util.replaceAll '&hquot;', '"', cmdStr
cmd = @util.replaceAll '&hquot;', '"', cmd
cmdStr = @util.replaceAll '&lquot;', '\'', cmdStr
cmd = @util.replaceAll '&lquot;', '\'', cmd
#@spawn cmdStr, cmd, args
@spawnR cmdStr, cmd, args
--@execStackCounter
#if @execStackCounter==0
# callback()
if not cmd?
return null
return null
isCommandEnabled: (name) ->
disabledCommands = atom.config.get('terminalix.disabledExtendedCommands') or @specsMode
if not disabledCommands?
return true
if name in disabledCommands
return false
return true
getLocalCommand: (name) ->
for cmd_name, cmd_body of @localCommands
if cmd_name == name
if cmd_body.command?
return cmd_body.command
else
return cmd_body
return null
getCommandsRegistry: () ->
global_vars = ATPVariablesBuiltins.list
for key, value of process.env
global_vars['%(env.'+key+')'] = "access native environment variable: "+key
cmd = []
for cmd_name, cmd_body of @localCommands
cmd.push {
name: cmd_name
description: cmd_body.description
example: cmd_body.example
params: cmd_body.params
deprecated: cmd_body.deprecated
sourcefile: cmd_body.sourcefile
source: cmd_body.source or 'internal'
}
for cmd_name, cmd_body of ATPCore.getUserCommands()
cmd.push {
name: cmd_name
description: cmd_body.description
example: cmd_body.example
params: cmd_body.params
deprecated: cmd_body.deprecated
sourcefile: cmd_body.sourcefile
source: 'external'
}
for var_name, descr of global_vars
cmd.push {
name: var_name
description: descr
source: 'global-variable'
}
cmd_ = []
cmd_len = cmd.length
cmd_forbd = (atom.config.get 'terminalix.disabledExtendedCommands') or []
for cmd_item in cmd
if cmd_item.name in cmd_forbd
else
cmd_.push cmd_item
return cmd_
getCommandsNames: () ->
cmds = @getCommandsRegistry()
cmd_names = []
for item in cmds
descr = ""
example = ""
params = ""
sourcefile = ""
deprecated = false
name = item.name
if item.sourcefile?
sourcefile = "<div style='float:bottom'><b style='float:right'>Plugin #{item.sourcefile} <b></div>"
if item.example?
example = "<br><b><u>Example:</u></b><br><code>"+item.example+"</code>"
if item.params?
params = item.params
if item.deprecated
deprecated = true
icon_style = ''
descr_prefix = ''
if item.source == 'external'
icon_style = 'book'
descr_prefix = 'External: '
else if item.source == 'internal'
icon_style = 'repo'
descr_prefix = 'Builtin: '
else if item.source == 'internal-atom'
icon_style = 'repo'
descr_prefix = 'Atom command: '
else if item.source == 'external-functional'
icon_style = 'plus'
descr_prefix = 'Functional: '
else if item.source == 'global-variable'
icon_style = 'briefcase'
descr_prefix = 'Global variable: '
if deprecated
name = "<strike style='color:gray;font-weight:normal;'>"+name+"</strike>"
descr = "<div style='float:left; padding-top:10px;' class='status status-#{icon_style} icon icon-#{icon_style}'></div><div style='padding-left: 10px;'><b>#{name} #{params}</b><br>#{item.description} #{example} #{sourcefile}</div>"
cmd_names.push {
name: item.name
description: descr
html: true
}
return cmd_names
getLocalCommandsMemdump: () ->
cmd = @getCommandsRegistry()
commandFinder = new ATPCommandFinderView cmd
commandFinderPanel = atom.workspace.addModalPanel(item: commandFinder)
commandFinder.shown commandFinderPanel, this
return
commandProgress: (value) ->
if value < 0
@cliProgressBar.hide()
@cliProgressBar.attr('value', '0')
else
@cliProgressBar.show()
@cliProgressBar.attr('value', value/2)
showInitMessage: (forceShow=false) ->
if not forceShow
if @helloMessageShown
return
if atom.config.get 'terminalix.enableConsoleStartupInfo' or forceShow or (not @specsMode)
changelog_path = require("path").join(__dirname, "../CHANGELOG.md")
readme_path = require("path").join(__dirname, "../README.md")
hello_message = @consolePanel 'ATOM Terminal', 'Please enter new commands to the box below. (ctrl-to show suggestions dropdown)<br>The console supports special annotation like: %(path), %(file), %(link)file.something%(endlink).<br>It also supports special HTML elements like: %(tooltip:A:content:B) and so on.<br>Hope you\'ll enjoy the terminal.'+
"<br><a class='changelog-link' href='#{changelog_path}'>See changelog</a> <a class='readme-link' href='#{readme_path}'>and the README! :)</a>"
@rawMessage hello_message
$('.changelog-link').css('font-weight','300%').click(() ->
atom.workspace.open changelog_path
)
$('.readme-link').css('font-weight','300%').click(() ->
atom.workspace.open readme_path
)
@helloMessageShown = true
return this
clearStatusIcon: () ->
@statusIcon.removeClass()
@statusIcon.addClass('atp-panel icon icon-terminal')
onCommand: (inputCmd) ->
@fsSpy()
@rawMessage @inputBoxState()
@removeInputBox()
@clearStatusIcon()
if not inputCmd?
inputCmd = @readInputBox()
@disposables.dispose('statusIconTooltips')
@disposables.add 'statusIconTooltips', atom.tooltips.add @statusIcon,
title: 'Task: \"'+inputCmd+'\"'
delay: 0
animation: false
@inputLine++
inputCmd = @parseSpecialStringTemplate inputCmd
if @echoOn
console.log 'echo-on'
#AllOPenPointsTerminalix:0 Repair!
#@message "\n"+@getCommandPrompt(inputCmd)+" "+inputCmd+"\n", false
ret = @exec inputCmd, null, this, () =>
@putInputBox()
@showCmd()
if typeof ret is 'string'
@message ret + '\n'
return null
initialize: ->
@userHome = process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE
cmd = 'test -e /etc/profile && source /etc/profile;test -e ~/.profile && source ~/.profile; node -pe "JSON.stringify(process.env)"'
exec cmd, (code, stdout, stderr) ->
try
process.env = JSON.parse(stdout)
catch e
atom.commands.add 'atom-workspace',
"atp-status:toggle-output": => @toggle()
clear: ->
@cliOutput.empty()
@putInputBox()
setMaxWindowHeight: ->
maxHeight = atom.config.get('terminalix.WindowHeight')
@cliOutput.css("max-height", "#{maxHeight}px")
$('.terminal-input').css("max-height", "#{maxHeight}px")
showCmd: ->
@focusInputBox()
@scrollToBottom()
scrollToBottom: ->
@cliOutput.scrollTop 10000000
flashIconClass: (className, time=100)=>
@statusIcon.addClass className
@timer and clearTimeout(@timer)
onStatusOut = =>
@statusIcon.removeClass className
@timer = setTimeout onStatusOut, time
destroy: ->
@statusIcon.remove()
_destroy = =>
if @hasParent()
@close()
if @statusIcon and @statusIcon.parentNode
@statusIcon.parentNode.removeChild(@statusIcon)
@statusView.removeCommandView this
if @program
@program.once 'exit', _destroy
@program.kill()
else
_destroy()
terminateProcessTree: () ->
pid = @program.pid
psTree = require 'ps-tree'
killProcess = (pid, signal, callback) ->
signal = signal || 'SIGKILL'
callback = callback || () -> {}
killTree = true
if killTree
psTree(pid, (err, children) ->
[pid].concat(
children.map((p) ->
return p.PID
)
).forEach((tpid) ->
try
process.kill tpid, signal
catch ex
)
callback()
)
else
try
process.kill pid, signal
catch ex
callback()
killProcess pid, 'SIGINT'
kill: ->
if @program
@terminateProcessTree @program.pid
@program.stdin.pause()
@program.kill('SIGINT')
@program.kill()
maximize: ->
@cliOutput.height (@cliOutput.height()+9999)
open: ->
if (atom.config.get('terminalix.moveToCurrentDirOnOpen')) and (not @specsMode)
@moveToCurrentDirectory()
if (atom.config.get('terminalix.moveToCurrentDirOnOpenLS')) and (not @specsMode)
@clear()
@execDelayedCommand @_cmdintdel, 'ls', null, this
@configFileFtp = findConfig.read('.ftpconfig')
if @configFileFtp
#Get document, or throw exception on error
try
configData = yaml.safeLoad(@configFileFtp)
console.log("Found version"+configData.version)
#@execDelayedCommand @_cmdintdel, 'ssh', ['aa','bb'], this
#yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'))
catch e
console.log("Error reading .ftpconfig file: "+e)
else
console.log("Config file not found")
atom.workspace.addBottomPanel(item: this) unless @hasParent()
if lastOpenedView and lastOpenedView != this
lastOpenedView.close()
lastOpenedView = this
@setMaxWindowHeight()
@putInputBox() if not @spawnProcessActive
@scrollToBottom()
@statusView.setActiveCommandView this
@focusInputBox()
@showInitMessage()
atom.tooltips.add @killBtn,
title: 'Kill the long working process.'
atom.tooltips.add @exitBtn,
title: 'Destroy the terminal session.'
atom.tooltips.add @closeBtn,
title: 'Hide the terminal window.'
atom.tooltips.add @openConfigBtn,
title: 'Open the terminal config file.'
atom.tooltips.add @reloadConfigBtn,
title: 'Reload the terminal configuration.'
if atom.config.get 'terminalix.enableWindowAnimations'
@WindowMinHeight = @cliOutput.height() + 50
@height 0
@consoleToolbarHeading.css {opacity: 0}
@animate {
height: @WindowMinHeight
}, 250, =>
@attr 'style', ''
@consoleToolbarHeading.animate {
opacity: 1
}, 250, =>
@consoleToolbarHeading.attr 'style', ''
close: ->
if atom.config.get 'terminalix.enableWindowAnimations'
@WindowMinHeight = @cliOutput.height() + 50
@height @WindowMinHeight
@animate {
height: 0
}, 250, =>
@attr 'style', ''
@consoleToolbar.attr 'style', ''
@detach()
lastOpenedView = null
else
@detach()
lastOpenedView = null
toggle: ->
if @hasParent()
@close()
else
@open()
removeQuotes: (text)->
if not text?
return ''
if text instanceof Array
ret = []
for t in text
ret.push (@removeQuotes t)
return ret
return text.replace(/['"]+/g, '')
cd: (args)->
args = [atom.project.getPaths()[0]] if not args[0]
args = @removeQuotes args
dir = resolve @getCwd(), args[0]
try
stat = fs.statSync dir
if not stat.isDirectory()
return @errorMessage "cd: not a directory: #{args[0]}"
@cwd = dir
catch e
return @errorMessage "cd: #{args[0]}: No such file or directory"
return null
ls: (args) ->
try
files = fs.readdirSync @getCwd()
catch e
return false
if atom.config.get('terminalix.XExperimentEnableForceLinking')
ret = ''
files.forEach (filename) =>
ret += @resolvePath filename + '\t%(break)'
@message ret
return true
filesBlocks = []
files.forEach (filename) =>
filesBlocks.push @_fileInfoHtml(filename, @getCwd())
filesBlocks = filesBlocks.sort (a, b) ->
aDir = false
bDir = false
if a[1]?
aDir = a[1].isDirectory()
if b[1]?
bDir = b[1].isDirectory()
if aDir and not bDir
return -1
if not aDir and bDir
return 1
a[2] > b[2] and 1 or -1
filesBlocks.unshift @_fileInfoHtml('..', @getCwd())
filesBlocks = filesBlocks.map (b) ->
b[0]
@message filesBlocks.join('%(break)') + '<div class="clear"/>'
return true
parseSpecialNodes: () ->
caller = this
if atom.config.get 'terminalix.enableConsoleInteractiveHints'
$('.atp-tooltip[data-toggle="tooltip"]').each(() ->
title = $(this).attr('title')
atom.tooltips.add $(this), {}
)
if atom.config.get 'terminalix.enableConsoleInteractiveLinks'
@find('.console-link').each (
() ->
el = $(this)
link_target = el.data('target')
if link_target != null && link_target != undefined
el.data('target', null)
link_type = el.data('targettype')
link_target_name = el.data('targetname')
link_target_line = el.data('line')
link_target_column = el.data('column')
if not link_target_line?
link_target_line = 0
if not link_target_column?
link_target_column = 0
el.click () ->
el.addClass('link-used')
if link_type == 'file'
atom.workspace.open link_target, {
initialLine: link_target_line
initialColumn: link_target_column
}
if link_type == 'directory'
moveToDir = (directory, messageDisp=false)->
caller.clear()
caller.cd([directory])
setTimeout () ->
if not caller.ls()
if not messageDisp
caller.errorMessage 'The directory is inaccesible.\n'
messageDisp = true
setTimeout () ->
moveToDir('..', messageDisp)
, 1500
, caller._cmdintdel
setTimeout () ->
moveToDir(link_target_name)
, caller._cmdintdel
)
# el.data('filenameLink', '')
consoleAlert: (text) ->
return '<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Warning!</strong> ' + text + '</div>'
consolePanel: (title, content) ->
return '<div class="panel panel-info welcome-panel"><div class="panel-heading">'+title+'</div><div class="panel-body">'+content+'</div></div><br><br>'
consoleText: (type, text) ->
if type == 'info'
return '<span class="text-info" style="margin-left:10px;">'+text+'</span>'
if type == 'error'
return '<span class="text-error" style="margin-left:10px;">'+text+'</span>'
if type == 'warning'
return '<span class="text-warning" style="margin-left:10px;">'+text+'</span>'
if type == 'success'
return '<span class="text-success" style="margin-left:10px;">'+text+'</span>'
return text
consoleLabel: (type, text) ->
if (not atom.config.get 'terminalix.enableConsoleLabels') and (not @specsMode)
return text
if not text?
text = type
if type == 'badge'
return '<span class="badge">'+text+'</span>'
if type == 'default'
return '<span class="inline-block highlight">'+text+'</span>'
if type == 'primary'
return '<span class="label label-primary">'+text+'</span>'
if type == 'success'
return '<span class="inline-block highlight-success">'+text+'</span>'
if type == 'info'
return '<span class="inline-block highlight-info">'+text+'</span>'
if type == 'warning'
return '<span class="inline-block highlight-warning">'+text+'</span>'
if type == 'danger'
return '<span class="inline-block highlight-error">'+text+'</span>'
if type == 'error'
return '<span class="inline-block highlight-error">'+text+'</span>'
return '<span class="label label-default">'+text+'</span>'
consoleLink: (name, forced=true) ->
if (atom.config.get 'terminalix.XExperimentEnableForceLinking') and (not forced)
return name
return @_fileInfoHtml(name, @getCwd(), 'font', false)[0]
_fileInfoHtml: (filename, parent, wrapper_class='span', use_file_info_class='true') ->
str = filename
name_tokens = filename
filename = filename.replace /:[0-9]+:[0-9]/ig, ''
name_tokens = @util.replaceAll filename, '', name_tokens
name_tokens = name_tokens.split ':'
fileline = name_tokens[0]
filecolumn = name_tokens[1]
filename = @util.replaceAll '/', '\\', filename
filename = @util.replaceAll parent, '', filename
filename = @util.replaceAll (@util.replaceAll '/', '\\', parent), '', filename
if filename[0] == '\\' or filename[0] == '/'
filename = filename.substring(1)
if filename == '..'
if use_file_info_class
return ["<font class=\"file-extension\"><#{wrapper_class} data-targetname=\"#{filename}\" data-targettype=\"directory\" data-target=\"#{filename}\" class=\"console-link icon-file-directory parent-folder\">#{filename}</#{wrapper_class}></font>", null, filename]
else
return ["<font class=\"file-extension\"><#{wrapper_class} data-targetname=\"#{filename}\" data-targettype=\"directory\" data-target=\"#{filename}\" class=\"console-link icon-file-directory file-info parent-folder\">#{filename}</#{wrapper_class}></font>", null, filename]
file_exists = true
filepath = @resolvePath filename
classes = []
dataname = ''
if atom.config.get('terminalix.useAtomIcons')
classes.push 'name'
classes.push 'icon'
dataname = filepath
else
classes.push 'name'
if use_file_info_class
classes.push 'file-info'
stat = null
if file_exists
try
stat = fs.lstatSync filepath
catch e
file_exists = false
if file_exists
if atom.config.get('terminalix.enableConsoleInteractiveLinks') or @specsMode
classes.push 'console-link'
if stat.isSymbolicLink()
classes.push 'stat-link'
stat = fs.statSync filepath
target_type = 'null'
if stat.isFile()
if stat.mode & 73 #0111
classes.push 'stat-program'
# TODO:10 check extension
matcher = /(.:)((.*)\\)*((.*\.)*)/ig
extension = filepath.replace matcher, ""
classes.push @util.replaceAll(' ', '', extension)
classes.push 'icon-file-text'
target_type = 'file'
if stat.isDirectory()
classes.push 'icon-file-directory'
target_type = 'directory'
if stat.isCharacterDevice()
classes.push 'stat-char-dev'
target_type = 'device'
if stat.isFIFO()
classes.push 'stat-fifo'
target_type = 'fifo'
if stat.isSocket()
classes.push 'stat-sock'
target_type = 'sock'
else
classes.push 'file-not-found'
classes.push 'icon-file-text'
target_type = 'file'
if filename[0] == '.'
classes.push 'status-ignored'
target_type = 'ignored'
href = 'file:///' + @util.replaceAll('\\', '/', filepath)
classes.push 'atp-tooltip'
exattrs = []
if fileline?
exattrs.push 'data-line="'+fileline+'"'
if filecolumn?
exattrs.push 'data-column="'+filecolumn+'"'
filepath_tooltip = @util.replaceAll '\\', '/', filepath
filepath = @util.replaceAll '\\', '/', filepath
["<font class=\"file-extension\"><#{wrapper_class} #{exattrs.join ' '} tooltip=\"\" data-targetname=\"#{filename}\" data-targettype=\"#{target_type}\" data-target=\"#{filepath}\" data-name=\"#{dataname}\" class=\"#{classes.join ' '}\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"#{filepath_tooltip}\" >#{filename}</#{wrapper_class}></font>", stat, filename]
getGitStatusName: (path, gitRoot, repo) ->
status = (repo.getCachedPathStatus or repo.getPathStatus)(path)
if status
if repo.isStatusModified status
return 'modified'
if repo.isStatusNew status
return 'added'
if repo.isPathIgnore path
return 'ignored'
preserveOriginalPaths: (text) ->
text = @util.replaceAll @getCurrentFilePath(), '%(file-original)', text
text = @util.replaceAll @getCwd(), '%(cwd-original)', text
text = @util.replaceAll @getCwd(), '%(cwd-original)', text
text = @util.replaceAll '/', '&fs;', text
text = @util.replaceAll '\\', '&bs;', text
return text
parseMessage: (message, matchSpec=true, parseCustomRules=true) ->
instance = this
message = '<div>'+(instance.parseMessage_ message, false, true, true)+'</div>'
n = $(message)
n.contents().filter(() ->
return this.nodeType == 3
).each(() ->
thiz = $(this)
out = thiz.text()
out = instance.parseMessage_ out, matchSpec, parseCustomRules
thiz.replaceWith('<span>'+out+'</span>')
)
return n.html()
parseMessage_: (message, matchSpec=true, parseCustomRules=true, isForcelyPreparsering=false) ->
if message == null
return ''
if matchSpec
if atom.config.get('terminalix.XExperimentEnableForceLinking')
if atom.config.get('terminalix.textReplacementFileAdress')?
if atom.config.get('terminalix.textReplacementFileAdress') != ''
# regex = /(([A-Za-z]:)(\\|\/))?([A-Za-z$\*\-+&#@!_\.]+(\\|\/))([A-Za-z $\*\-+&#@!_\.]+(\\|\/))*[A-Za-z\-_$\*\+&\^@#\. ]+\.[A-Za-z\-_$\*\+]*/ig
# regex = /(([A-Za-z]:)(\\|\/))?(([^\s#@$%&!;<>\.\^:]| )+(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
regex = /(\.(\\|\/))?(([A-Za-z]:)(\\|\/))?(([^\s#@$%&!;<>\.\^:]| )+(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
regex2 = /(\.(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
message = message.replace regex2, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
else
if atom.config.get('terminalix.textReplacementFileAdress')?
if atom.config.get('terminalix.textReplacementFileAdress') != ''
#regex = /(([A-Za-z]:)(\\|\/))?([A-Za-z$\*\-+&#@!_\.]+(\\|\/))([A-Za-z $\*\-+&#@!_\.]+(\\|\/))*[A-Za-z\-_$\*\+&\^@#\. ]+\.[A-Za-z\-_$\*\+]*/ig
cwdN = @getCwd()
cwdE = @util.replaceAll '/', '\\', @getCwd()
regexString ='(' + (@util.escapeRegExp cwdN) + '|' + (@util.escapeRegExp cwdE) + ')\\\\([^\\s:#$%^&!:]| )+\\.?([^\\s:#$@%&\\*\\^!0-9:\\.+\\-,\\\\\\/\"]| )*'
regex = new RegExp(regexString, 'ig')
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
if atom.config.get('terminalix.textReplacementCurrentFile')?
if atom.config.get('terminalix.textReplacementCurrentFile') != ''
path = @getCurrentFilePath()
regex = new RegExp @util.escapeRegExp(path), 'g'
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementCurrentFile'), {file:match}
message = @preserveOriginalPaths message
if atom.config.get('terminalix.textReplacementCurrentPath')?
if atom.config.get('terminalix.textReplacementCurrentPath') != ''
path = @getCwd()
regex = new RegExp @util.escapeRegExp(path), 'g'
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementCurrentPath'), {file:match}
message = @util.replaceAll '%(file-original)', @getCurrentFilePath(), message
message = @util.replaceAll '%(cwd-original)', @getCwd(), message
message = @util.replaceAll '&fs;', '/', message
message = @util.replaceAll '&bs;', '\\', message
rules = ATPCore.getConfig().rules
for key, value of rules
matchExp = key
replExp = '%(content)'
matchAllLine = false
matchNextLines = 0
flags = 'gm'
forceParse = false
if value.match?
if value.match.flags?
flags = value.match.flags.join ''
if value.match.replace?
replExp = value.match.replace
if value.match.matchLine?
matchAllLine = value.match.matchLine
if value.match.matchNextLines?
matchNextLines = value.match.matchNextLines
if value.match.forced?
forceParse = value.match.forced
if (forceParse or parseCustomRules) and ((isForcelyPreparsering and forceParse) or (not isForcelyPreparsering))
if matchAllLine
matchExp = '.*' + matchExp
if matchNextLines > 0
for i in [0..matchNextLines] by 1
matchExp = matchExp + '[\\r\\n].*'
regex = new RegExp(matchExp, flags)
message = message.replace regex, (match, groups...) =>
style = ''
if value.css?
style = ATPCore.jsonCssToInlineStyle value.css
else if not value.match?
style = ATPCore.jsonCssToInlineStyle value
vars =
content: match
0: match
groupsNumber = groups.length-1
for i in [0..groupsNumber] by 1
if groups[i]?
vars[i+1] = groups[i]
# console.log 'Active rule => '+matchExp
repl = @parseSpecialStringTemplate replExp, vars
return "<font style=\"#{style}\">#{repl}</font>"
message = @util.replaceAll '%(file-original)', @getCurrentFilePath(), message
message = @util.replaceAll '%(cwd-original)', @getCwd(), message
message = @util.replaceAll '&fs;', '/', message
message = @util.replaceAll '&bs;', '\\', message
return message
redirect: (streamName) ->
@redirectOutput = streamName
rawMessage: (message) ->
if @redirectOutput == 'console'
console.log message
return
@cliOutput.append message
@showCmd()
# @parseSpecialNodes()
message: (message, matchSpec=true) ->
if @redirectOutput == 'console'
console.log message
return
if typeof message is 'object'
mes = message
else
if not message?
return
mes = message.split '%(break)'
if mes.length > 1
for m in mes
@message m
return
else
mes = mes[0]
mes = @parseMessage message, matchSpec, matchSpec
mes = @util.replaceAll '%(raw)', '', mes
mes = @parseTemplate mes, [], true
# mes = @util.replaceAll '<', '<', mes
# mes = @util.replaceAll '>', '>', mes
@cliOutput.append mes
@showCmd()
@parseSpecialNodes()
@scrollToBottom()
# @putInputBox()
errorMessage: (message) ->
@cliOutput.append @parseMessage(message)
@clearStatusIcon()
@statusIcon.addClass 'status-error'
@parseSpecialNodes()
correctFilePath: (path) ->
return @util.replaceAll '\\', '/', path
getCwd: ->
if not atom.project?
return null
extFile = extname atom.project.getPaths()[0]
if extFile == ""
if atom.project.getPaths()[0]
projectDir = atom.project.getPaths()[0]
else
if process.env.HOME
projectDir = process.env.HOME
else if process.env.USERPROFILE
projectDir = process.env.USERPROFILE
else
projectDir = '/'
else
projectDir = dirname atom.project.getPaths()[0]
cwd = @cwd or projectDir or @userHome
return @correctFilePath cwd
spawn: (inputCmd, cmd, args) =>
## @cmdEditor.hide()
## htmlStream = ansihtml()
# htmlStream = iconv.decodeStream @streamsEncoding
# htmlStream.on 'data', (data) =>
## @cliOutput.append data
# @message data
# @scrollToBottom()
# try
## @program = spawn cmd, args, stdio: 'pipe', env: process.env, cwd: @getCwd()
# @program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd()
## @program.stdin.pipe htmlStream
# @program.stdout.pipe htmlStream
# @program.stderr.pipe htmlStream
## @program.stdout.setEncoding @streamsEncoding
@spawnProcessActive = true
instance = this
dataCallback = (data) ->
instance.message(data)
instance.scrollToBottom()
processCallback = (error, stdout, stderr) ->
console.log 'callback' if atom.config.get('terminalix.logConsole') or @specsMode
console.log(error, stdout, stderr)
instance.putInputBox()
instance.showCmd()
htmlStream = ansihtml()
htmlStream = iconv.decodeStream @streamsEncoding
htmlStream.on 'data', dataCallback
try
if @configFileFtp
@program = process
@programSSH = execSSH('echo dada', {
user: 'admin123'
host: 'vps123.ovh.net'
passphrase: '123'
key: 'c:/users/user1/.ssh/id_rsa'
password: '123-2000'
timeout: 10000
}, processCallback)
console.log(@programSSH)
@programSSH.pipe @program.stdout
@program.stdin.pipe htmlStream
#(@program.stdin.pipe iconv.encodeStream 'base64').pipe htmlStream
#@program = execSSH inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
else
@program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
@program.stdout.setEncoding 'base64'
console.log @program if atom.config.get('terminalix.logConsole') or @specsMode
(@program.stdout.pipe iconv.encodeStream 'base64').pipe htmlStream
@clearStatusIcon()
@statusIcon.addClass 'status-running'
@killBtn.removeClass 'hide'
@program.on 'exit', (code, signal) =>
console.log 'exit', code, signal if atom.config.get('terminalix.logConsole') or @specsMode
@killBtn.addClass 'hide'
@statusIcon.removeClass 'status-running'
if code == 0
@statusIcon.addClass 'status-success'
else if code?
@statusIcon.addClass 'status-error'
if code == 127
@message (@consoleLabel 'error', 'Error')+(@consoleText 'error', cmd + ': command not found')
@message '\n'
@program = null
@spawnProcessActive = false
@program.on 'error', (err) =>
console.log 'error' if atom.config.get('terminalix.logConsole') or @specsMode
@message (err.message)
@message '\n'
@putInputBox()
@showCmd()
@statusIcon.addClass 'status-error'
@program.stdout.on 'data', (data) =>
@flashIconClass 'status-info'
@statusIcon.removeClass 'status-error'
@program.stderr.on 'data', (data) =>
console.log 'stderr' if atom.config.get('terminalix.logConsole') or @specsMode
@message data
@flashIconClass 'status-error', 300
#DOING:20 x 2017-08-09 This task was created on 2017-08-09 and complited 2017-08-23
catch err
console.log 'Failed to launch process' if atom.config.get('terminalix.logConsole') or @specsMode
# IDEA: test it
@message ('haha '+err.message)
#DOING:21 This task is due on 2017-08-24 due:2017-08-24
@showCmd()
spawnR: (inputCmd, cmd, args) =>
@spawnRProcessActive = true
instance = this
dataCallback = (data) ->
instance.message(data)
instance.scrollToBottom()
processCallback = (error, stdout, stderr) ->
console.log 'callback' if atom.config.get('terminalix.logConsole') or @specsMode
console.log(error, stdout, stderr)
instance.putInputBox()
instance.showCmd()
htmlStream = ansihtml()
htmlStream = iconv.decodeStream @streamsEncoding
htmlStream.on 'data', dataCallback
sshCallback = (err, ssh) =>
console.log 'ssh'
console.log ssh
console.log err
try
if err
@program = new EventEmitter()
@program.emit('error',err)
processCallback(err,null,null)
else
@program = execR {cmd: 'ls -lah', ssh: ssh}, (err, stdout, stderr) ->
console.log ssh
console.log 'err:'
console.log err
console.log stderr
console.log stdout
#@program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
@program.stdout.setEncoding 'base64'
console.log @program if atom.config.get('terminalix.logConsole') or @specsMode
(@program.stdout.pipe iconv.encodeStream 'base64').pipe htmlStream
@clearStatusIcon()
@statusIcon.addClass 'status-running'
@killBtn.removeClass 'hide'
@program.on 'exit', (code, signal) =>
console.log 'exit', code, signal if atom.config.get('terminalix.logConsole') or @specsMode
@killBtn.addClass 'hide'
@statusIcon.removeClass 'status-running'
if code == 0
@statusIcon.addClass 'status-success'
else if code?
@statusIcon.addClass 'status-error'
if code == 127
@message (@consoleLabel 'error', 'Error')+(@consoleText 'error', cmd + ': command not found')
@message '\n'
@program = null
@spawnRProcessActive = false
@program.on 'error', (err) =>
console.log 'error' if atom.config.get('terminalix.logConsole') or @specsMode
@message (err.message)
@message '\n'
@putInputBox()
@showCmd()
@statusIcon.addClass 'status-error'
@flashIconClass 'status-error', 300
@program.stdout.on 'data', (data) =>
@flashIconClass 'status-info'
@statusIcon.removeClass 'status-error'
@program.stderr.on 'data', (data) =>
console.log 'stderr' if atom.config.get('terminalix.logConsole') or @specsMode
@message data
@flashIconClass 'status-error', 300
#DOING:20 x 2017-08-09 This task was created on 2017-08-09 and complited 2017-08-23
catch err1
console.log 'Failed to launch process' if atom.config.get('terminalix.logConsole') or @specsMode
console.log err1
# IDEA: test it
@message err1.message
#DOING:21 This task is due on 2017-08-24 due:2017-08-24
@showCmd()
try
connect {
user: 'admin123'
host: 'vps123.ovh.net'
#passphrase: '123'
#key: 'c:/users/user1/.ssh/id_rsa'
password: '123-2000'
timeout: 10000
}, sshCallback
catch err2
console.log err2
# coffeeli1111nt: enable=*
# coffeelint: enable=max_line_length
| 81393 | ###
Terminalix plugin forked from awesome
Atom-terminal-panel
Copyright by isis97/VadimDor
MIT licensed
The main terminal view class, which does the most of all the work.
###
#coffeelint: disable=max_line_length
lastOpenedView = null
fs = include 'fs'
os = include 'os'
{$, TextEditorView, View} = include 'atom-space-pen-views'
{spawn, exec, execSync} = include 'child_process'
{execR, execSyncR} = include 'ssh2-exec'
{connR} = include 'ssh2-connect'
EventEmitter = (include 'events').EventEmitter
{resolve, dirname, extname, sep} = include 'path'
findConfig = include 'find-config'
yaml = include 'js-yaml'
connect = include 'ssh2-connect'
exec_SSH = include 'ssh2-exec'
execSSH = include 'ssh-exec-plus'
ansihtml = include 'ansi-html-stream'
stream = include 'stream'
iconv = include 'iconv-lite'
ATPCommandFinderView = include 'atp-command-finder'
ATPCore = include 'atp-core'
ATPCommandsBuiltins = include 'atp-builtins-commands'
ATPVariablesBuiltins = include 'atp-builtins-variables'
window.$ = window.jQuery = $
include 'jquery-autocomplete-js'
module.exports =
class ATPOutputView extends View
cwd: null
#streamsEncoding: 'iso-8859-3'
streamsEncoding : '"'+atom.config.get('terminalix.textEncode')+'"'
_cmdintdel: 50
echoOn: true
configFileFtp: null
redirectOutput: ''
specsMode: false
inputLine: 0
helloMessageShown: false
minHeight: 250
util: include 'atp-terminal-util'
currentInputBox: null
#currentInputBox: null
currentInputBoxTmr: null
volatileSuggestions: []
disposables:
dispose: (field) =>
if not this[field]?
this[field] = []
a = this[field]
for i in [0..a.length-1] by 1
a[i].dispose()
add: (field, value) =>
if not this[field]?
this[field] = []
this[field].push value
keyCodes: {
enter: 13
arrowUp: 38
arrowDown: 40
arrowLeft: 37
arrowRight: 39
}
localCommandAtomBindings: []
localCommands: ATPCommandsBuiltins
@content: ->
@div tabIndex: -1, class: 'panel atp-panel panel-bottom', outlet: 'atpView', =>
@div class: 'terminal panel-divider', style: 'cursor:n-resize;width:100%;height:8px;', outlet: 'panelDivider'
@button outlet: 'maximizeIconBtn', class: 'atp-maximize-btn', click: 'maximize'
@button outlet: 'closeIconBtn', class: 'atp-close-btn', click: 'close'
@button outlet: 'destroyIconBtn', class: 'atp-destroy-btn', click: 'destroy'
@div class: 'panel-heading btn-toolbar', outlet:'consoleToolbarHeading', =>
@div class: 'btn-group', outlet:'consoleToolbar', =>
@button outlet: 'killBtn', click: 'kill', class: 'btn hide', =>
@span 'kill'
@button outlet: 'exitBtn', click: 'destroy', class: 'btn', =>
@span 'exit'
@button outlet: 'closeBtn', click: 'close', class: 'btn', =>
@span class: "icon icon-x"
@span 'close'
@button outlet: 'openConfigBtn', class: 'btn icon icon-gear inline-block-tight button-settings', click: 'showSettings', =>
@span 'Open config'
@button outlet: 'reloadConfigBtn', class: 'btn icon icon-gear inline-block-tight button-settings', click: 'reloadSettings', =>
@span 'Reload config'
@div class: 'atp-panel-body', =>
@pre class: "terminal", outlet: "cliOutput"
toggleAutoCompletion: () ->
if @currentInputBoxCmp?
@currentInputBoxCmp.enable()
@currentInputBoxCmp.repaint()
@currentInputBoxCmp.showDropDown()
@currentInputBox.find('.terminal-input').height('100px')
fsSpy: () ->
@volatileSuggestions = []
if @cwd?
fs.readdir @cwd, (err, files) =>
if files?
for file in files
@volatileSuggestions.push file
turnSpecsMode: (state) ->
@specsMode = state
getRawOutput: () ->
t = @getHtmlOutput().replace(/<[^>]*>/igm, "")
t = @util.replaceAll ">", ">", t
t = @util.replaceAll "<", "<", t
t = @util.replaceAll """, "\"", t
return t
getHtmlOutput: () ->
return @cliOutput.html()
resolvePath: (path) ->
path = @util.replaceAll '\"', '', path
filepath = ''
if path.match(/([A-Za-z]):/ig) != null
filepath = path
else
filepath = @getCwd() + '/' + path
filepath = @util.replaceAll '\\', '/', filepath
return @util.replaceAll '\\', '/', (resolve filepath)
reloadSettings: () ->
@onCommand 'update'
showSettings: () ->
setTimeout () ->
panelPath = atom.packages.resolvePackagePath 'terminalix'
atomPath = resolve panelPath+'/../..'
configPath = atomPath + '/terminal-commands.json'
atom.workspace.open configPath
, 50
focusInputBox: () ->
if @currentInputBoxCmp?
@currentInputBoxCmp.input.focus()
updateInputCursor: (textarea) ->
@rawMessage 'test\n'
val = textarea.val()
textarea
.blur()
.focus()
.val("")
.val(val)
removeInputBox: () ->
@cliOutput.find('.atp-dynamic-input-box').remove()
putInputBox: () ->
if @currentInputBoxTmr?
clearInterval @currentInputBoxTmr
@currentInputBoxTmr = null
@cliOutput.find('.atp-dynamic-input-box').remove()
prompt = @getCommandPrompt('')
@currentInputBox = $(
'<div style="width: 100%; white-space:nowrap; overflow:hidden; display:inline-block;" class="atp-dynamic-input-box">' +
'<div style="position:relative; top:5px; max-height:500px; width: 100%; bottom: -10px; height: 20px; white-space:nowrap; overflow:hidden; display:inline-block;" class="terminal-input native-key-bindings"></div>' +
'</div>'
)
@currentInputBox.prepend ' '
@currentInputBox.prepend prompt
#@cliOutput.mousedown (e) =>
# if e.which is 1
# @focusInputBox()
history = []
if @currentInputBoxCmp?
history = @currentInputBoxCmp.getInputHistory()
inputComp = @currentInputBox.find '.terminal-input'
@currentInputBoxCmp = inputComp.autocomplete {
animation: [
['opacity', 0, 0.8]
]
isDisabled: true
inputHistory: history
inputWidth: '80%'
dropDownWidth: '30%'
dropDownDescriptionBoxWidth: '30%'
dropDownPosition: 'top'
showDropDown: atom.config.get 'terminalix.enableConsoleSuggestionsDropdown'
}
@currentInputBoxCmp
.confirmed(() =>
@currentInputBoxCmp.disable().repaint()
@onCommand()
).changed((inst, text) =>
if inst.getText().length <= 0
@currentInputBoxCmp.disable().repaint()
@currentInputBox.find('.terminal-input').height('20px')
)
@currentInputBoxCmp.input.keydown((e) =>
if (e.keyCode == 17) and (@currentInputBoxCmp.getText().length > 0)
###
@currentInputBoxCmp.enable().repaint()
@currentInputBoxCmp.showDropDown()
@currentInputBox.find('.terminal-input').height('100px');
###
else if (e.keyCode == 32) or (e.keyCode == 8)
@currentInputBoxCmp.disable().repaint()
@currentInputBox.find('.terminal-input').height('20px')
)
endsWith = (text, suffix) ->
return text.indexOf(suffix, text.length - suffix.length) != -1
@currentInputBoxCmp.options = (instance, text, lastToken) =>
token = lastToken
if not token?
token = ''
if not (endsWith(token, '/') or endsWith(token, '\\'))
token = @util.replaceAll '\\', sep, token
token = token.split sep
token.pop()
token = token.join(sep)
if not endsWith(token, sep)
token = token + sep
o = @getCommandsNames().concat(@volatileSuggestions)
fsStat = []
if token?
try
fsStat = fs.readdirSync(token)
for i in [0..fsStat.length-1] by 1
fsStat[i] = token + fsStat[i]
catch e
ret = o.concat(fsStat)
return ret
@currentInputBoxCmp.hideDropDown()
setTimeout () =>
@currentInputBoxCmp.input.focus()
, 0
@cliOutput.append @currentInputBox
inputBoxState: () ->
inputState = @cliOutput.find('.atp-dynamic-input-box').clone()
inputState.find('.autocomplete-wrapper').replaceWith () ->
input = $(this).find('.autocomplete-input')[0]
return $('<span/>', class: input.className, text: input.value)
inputState.removeClass 'atp-dynamic-input-box'
return inputState.prop('outerHTML') + '\n'
readInputBox: () ->
ret = ''
if @currentInputBoxCmp?
# ret = @currentInputBox.find('.terminal-input').val()
ret = @currentInputBoxCmp.getText()
return ret
requireCSS: (location) ->
if not location?
return
location = resolve location
console.log ("Require terminalix plugin CSS file: "+location+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
$('head').append "<link rel='stylesheet' type='text/css' href='#{location}'/>"
resolvePluginDependencies: (path, plugin) ->
config = plugin.dependencies
if not config?
return
css_dependencies = config.css
if not css_dependencies?
css_dependencies = []
for css_dependency in css_dependencies
@requireCSS path+"/"+css_dependency
delete plugin['dependencies']
init: () ->
###
TODO: test-autocomplete Remove this!
el = $('<div style="z-index: 9999; position: absolute; left: 200px; top: 200px;" id="glotest"></div>')
el.autocomplete({
inputWidth: '80%'
})
$('body').append(el)
###
@streamsEncoding = '"'+atom.config.get('terminalix.textEncode')+'"'
lastY = -1
mouseDown = false
panelDraggingActive = false
@panelDivider
.mousedown () -> panelDraggingActive = true
.mouseup () -> panelDraggingActive = false
$(document)
.mousedown () -> mouseDown = true
.mouseup () -> mouseDown = false
.mousemove (e) ->
if mouseDown and panelDraggingActive
if lastY != -1
delta = e.pageY - lastY
@cliOutput.height @cliOutput.height()-delta
lastY = e.pageY
else
lastY = -1
normalizedPath = require("path").join(__dirname, "../commands")
console.log ("Loading terminalix plugins from the directory: "+normalizedPath+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
fs.readdirSync(normalizedPath).forEach( (folder) =>
fullpath = resolve "../commands/" +folder
console.log ("Require terminalix plugin: "+folder+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
obj = require ("../commands/" +folder+"/index.coffee")
console.log "Plugin loaded." if atom.config.get('terminalix.logConsole')
@resolvePluginDependencies fullpath, obj
for key, value of obj
if value.command?
@localCommands[key] = value
@localCommands[key].source = 'external-functional'
@localCommands[key].sourcefile = folder
else if value.variable?
value.name = key
ATPVariablesBuiltins.putVariable value
)
console.log ("All plugins were loaded.") if atom.config.get('terminalix.logConsole')
if ATPCore.getConfig()?
actions = ATPCore.getConfig().actions
if actions?
for action in actions
if action.length > 1
obj = {}
obj['terminalix:'+action[0]] = () =>
@open()
@onCommand action[1]
atom.commands.add 'atom-workspace', obj
if atom.workspace?
eleqr = atom.workspace.getActivePaneItem() ? atom.workspace
eleqr = atom.views.getView(eleqr)
atomCommands = atom.commands.findCommands({target: eleqr})
for command in atomCommands
comName = command.name
com = {}
com.description = command.displayName
com.command =
((comNameP) ->
return (state, args) ->
ele = atom.workspace.getActivePaneItem() ? atom.workspace
ele = atom.views.getView(ele)
atom.commands.dispatch ele, comNameP
return (state.consoleLabel 'info', "info") + (state.consoleText 'info', 'Atom command executed: '+comNameP)
)(comName)
com.source = "internal-atom"
@localCommands[comName] = com
toolbar = ATPCore.getConfig().toolbar
if toolbar?
toolbar.reverse()
for com in toolbar
bt = $("<div class=\"btn\" data-action=\"#{com[1]}\" ><span>#{com[0]}</span></div>")
if com[2]?
atom.tooltips.add bt,
title: com[2]
@consoleToolbar.prepend bt
caller = this
bt.click () ->
caller.onCommand $(this).data('action')
return this
commandLineNotCounted: () ->
@inputLine--
parseSpecialStringTemplate: (prompt, values, isDOM=false) =>
if isDOM
return ATPVariablesBuiltins.parseHtml(this, prompt, values)
else
return ATPVariablesBuiltins.parse(this, prompt, values)
getCommandPrompt: (cmd) ->
return @parseTemplate atom.config.get('terminalix.commandPrompt'), {cmd: cmd}, true
delay: (callback, delay=100) ->
setTimeout callback, delay
execDelayedCommand: (delay, cmd, args, state) ->
caller = this
callback = ->
caller.exec cmd, args, state
setTimeout callback, delay
moveToCurrentDirectory: ()->
CURRENT_LOCATION = @getCurrentFileLocation()
if CURRENT_LOCATION?
@cd [CURRENT_LOCATION]
else if atom.project.getDirectories()[0]?
@cd [atom.project.getDirectories()[0].path]
getCurrentFileName: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getBaseName()
return null
getCurrentFileLocation: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getPath().replace ///#{current_file.getBaseName()}$///, ""
getCurrentFilePath: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getPath()
return null
getCurrentFile: ()->
if not atom.workspace?
return null
te = atom.workspace.getActiveTextEditor()
if te?
if te.getPath()?
return te.buffer.file
return null
parseTemplate: (text, vars, isDOM=false) ->
if not vars?
vars = {}
ret = ''
if isDOM
ret = ATPVariablesBuiltins.parseHtml this, text, vars
else
ret = @parseSpecialStringTemplate text, vars
ret = @util.replaceAll '%(file-original)', @getCurrentFilePath(), ret
ret = @util.replaceAll '%(cwd-original)', @getCwd(), ret
ret = @util.replaceAll '&fs;', '/', ret
ret = @util.replaceAll '&bs;', '\\', ret
return ret
parseExecToken__: (cmd, args, strArgs) ->
if strArgs?
cmd = @util.replaceAll "%(*)", strArgs, cmd
cmd = @util.replaceAll "%(*^)", (@util.replaceAll "%(*^)", "", cmd), cmd
if args?
argsNum = args.length
for i in [0..argsNum] by 1
if args[i]?
v = args[i].replace /\n/ig, ''
cmd = @util.replaceAll "%(#{i})", args[i], cmd
cmd = @parseTemplate cmd, {file:@getCurrentFilePath()}
return cmd
execStackCounter: 0
exec: (cmdStr, ref_args, state, callback) ->
if not state?
state = this
if not ref_args?
ref_args = {}
if cmdStr.split?
cmdStrC = cmdStr.split ';;'
if cmdStrC.length > 1
cmdStr = cmdStrC
@execStackCounter = 0
return @exec_ cmdStr, ref_args, state, callback
exec_: (cmdStr, ref_args, state, callback) ->
if not callback?
callback = () -> return null
++@execStackCounter
if cmdStr instanceof Array
ret = ''
for com in cmdStr
val = @exec com, ref_args, state
if val?
ret += val
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
cmdStr = @util.replaceAll "\\\"", '&hquot;', cmdStr
cmdStr = @util.replaceAll "&bs;\"", '&hquot;', cmdStr
cmdStr = @util.replaceAll "\\\'", '&lquot;', cmdStr
cmdStr = @util.replaceAll "&bs;\'", '&lquot;', cmdStr
ref_args_str = null
if ref_args?
if ref_args.join?
ref_args_str = ref_args.join(' ')
cmdStr = @parseExecToken__ cmdStr, ref_args, ref_args_str
args = []
cmd = cmdStr
cmd.replace /("[^"]*"|'[^']*'|[^\s'"]+)/g, (s) =>
if s[0] != '"' and s[0] != "'"
s = s.replace /~/g, @userHome
s = @util.replaceAll '&hquot;', '"', s
s = @util.replaceAll '&lquot;', '\'', s
args.push s
args = @util.dir args, @getCwd()
cmd = args.shift()
command = null
if @isCommandEnabled(cmd)
command = ATPCore.findUserCommand(cmd)
if command?
if not state?
ret = null
throw new Error 'The console functional (not native) command cannot be executed without caller information: \''+cmd+'\'.'
if command?
try
ret = command(state, args)
catch e
throw new Error "Error at executing terminal command: '#{cmd}' ('#{cmdStr}'): #{e.message}"
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
if atom.config.get('terminalix.enableExtendedCommands') or @specsMode
if @isCommandEnabled(cmd)
command = @getLocalCommand(cmd)
if command?
ret = command(state, args)
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
cmdStr = @util.replaceAll '&hquot;', '"', cmdStr
cmd = @util.replaceAll '&hquot;', '"', cmd
cmdStr = @util.replaceAll '&lquot;', '\'', cmdStr
cmd = @util.replaceAll '&lquot;', '\'', cmd
#@spawn cmdStr, cmd, args
@spawnR cmdStr, cmd, args
--@execStackCounter
#if @execStackCounter==0
# callback()
if not cmd?
return null
return null
isCommandEnabled: (name) ->
disabledCommands = atom.config.get('terminalix.disabledExtendedCommands') or @specsMode
if not disabledCommands?
return true
if name in disabledCommands
return false
return true
getLocalCommand: (name) ->
for cmd_name, cmd_body of @localCommands
if cmd_name == name
if cmd_body.command?
return cmd_body.command
else
return cmd_body
return null
getCommandsRegistry: () ->
global_vars = ATPVariablesBuiltins.list
for key, value of process.env
global_vars['%(env.'+key+')'] = "access native environment variable: "+key
cmd = []
for cmd_name, cmd_body of @localCommands
cmd.push {
name: cmd_name
description: cmd_body.description
example: cmd_body.example
params: cmd_body.params
deprecated: cmd_body.deprecated
sourcefile: cmd_body.sourcefile
source: cmd_body.source or 'internal'
}
for cmd_name, cmd_body of ATPCore.getUserCommands()
cmd.push {
name: cmd_name
description: cmd_body.description
example: cmd_body.example
params: cmd_body.params
deprecated: cmd_body.deprecated
sourcefile: cmd_body.sourcefile
source: 'external'
}
for var_name, descr of global_vars
cmd.push {
name: var_name
description: descr
source: 'global-variable'
}
cmd_ = []
cmd_len = cmd.length
cmd_forbd = (atom.config.get 'terminalix.disabledExtendedCommands') or []
for cmd_item in cmd
if cmd_item.name in cmd_forbd
else
cmd_.push cmd_item
return cmd_
getCommandsNames: () ->
cmds = @getCommandsRegistry()
cmd_names = []
for item in cmds
descr = ""
example = ""
params = ""
sourcefile = ""
deprecated = false
name = item.name
if item.sourcefile?
sourcefile = "<div style='float:bottom'><b style='float:right'>Plugin #{item.sourcefile} <b></div>"
if item.example?
example = "<br><b><u>Example:</u></b><br><code>"+item.example+"</code>"
if item.params?
params = item.params
if item.deprecated
deprecated = true
icon_style = ''
descr_prefix = ''
if item.source == 'external'
icon_style = 'book'
descr_prefix = 'External: '
else if item.source == 'internal'
icon_style = 'repo'
descr_prefix = 'Builtin: '
else if item.source == 'internal-atom'
icon_style = 'repo'
descr_prefix = 'Atom command: '
else if item.source == 'external-functional'
icon_style = 'plus'
descr_prefix = 'Functional: '
else if item.source == 'global-variable'
icon_style = 'briefcase'
descr_prefix = 'Global variable: '
if deprecated
name = "<strike style='color:gray;font-weight:normal;'>"+name+"</strike>"
descr = "<div style='float:left; padding-top:10px;' class='status status-#{icon_style} icon icon-#{icon_style}'></div><div style='padding-left: 10px;'><b>#{name} #{params}</b><br>#{item.description} #{example} #{sourcefile}</div>"
cmd_names.push {
name: item.name
description: descr
html: true
}
return cmd_names
getLocalCommandsMemdump: () ->
cmd = @getCommandsRegistry()
commandFinder = new ATPCommandFinderView cmd
commandFinderPanel = atom.workspace.addModalPanel(item: commandFinder)
commandFinder.shown commandFinderPanel, this
return
commandProgress: (value) ->
if value < 0
@cliProgressBar.hide()
@cliProgressBar.attr('value', '0')
else
@cliProgressBar.show()
@cliProgressBar.attr('value', value/2)
showInitMessage: (forceShow=false) ->
if not forceShow
if @helloMessageShown
return
if atom.config.get 'terminalix.enableConsoleStartupInfo' or forceShow or (not @specsMode)
changelog_path = require("path").join(__dirname, "../CHANGELOG.md")
readme_path = require("path").join(__dirname, "../README.md")
hello_message = @consolePanel 'ATOM Terminal', 'Please enter new commands to the box below. (ctrl-to show suggestions dropdown)<br>The console supports special annotation like: %(path), %(file), %(link)file.something%(endlink).<br>It also supports special HTML elements like: %(tooltip:A:content:B) and so on.<br>Hope you\'ll enjoy the terminal.'+
"<br><a class='changelog-link' href='#{changelog_path}'>See changelog</a> <a class='readme-link' href='#{readme_path}'>and the README! :)</a>"
@rawMessage hello_message
$('.changelog-link').css('font-weight','300%').click(() ->
atom.workspace.open changelog_path
)
$('.readme-link').css('font-weight','300%').click(() ->
atom.workspace.open readme_path
)
@helloMessageShown = true
return this
clearStatusIcon: () ->
@statusIcon.removeClass()
@statusIcon.addClass('atp-panel icon icon-terminal')
onCommand: (inputCmd) ->
@fsSpy()
@rawMessage @inputBoxState()
@removeInputBox()
@clearStatusIcon()
if not inputCmd?
inputCmd = @readInputBox()
@disposables.dispose('statusIconTooltips')
@disposables.add 'statusIconTooltips', atom.tooltips.add @statusIcon,
title: 'Task: \"'+inputCmd+'\"'
delay: 0
animation: false
@inputLine++
inputCmd = @parseSpecialStringTemplate inputCmd
if @echoOn
console.log 'echo-on'
#AllOPenPointsTerminalix:0 Repair!
#@message "\n"+@getCommandPrompt(inputCmd)+" "+inputCmd+"\n", false
ret = @exec inputCmd, null, this, () =>
@putInputBox()
@showCmd()
if typeof ret is 'string'
@message ret + '\n'
return null
initialize: ->
@userHome = process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE
cmd = 'test -e /etc/profile && source /etc/profile;test -e ~/.profile && source ~/.profile; node -pe "JSON.stringify(process.env)"'
exec cmd, (code, stdout, stderr) ->
try
process.env = JSON.parse(stdout)
catch e
atom.commands.add 'atom-workspace',
"atp-status:toggle-output": => @toggle()
clear: ->
@cliOutput.empty()
@putInputBox()
setMaxWindowHeight: ->
maxHeight = atom.config.get('terminalix.WindowHeight')
@cliOutput.css("max-height", "#{maxHeight}px")
$('.terminal-input').css("max-height", "#{maxHeight}px")
showCmd: ->
@focusInputBox()
@scrollToBottom()
scrollToBottom: ->
@cliOutput.scrollTop 10000000
flashIconClass: (className, time=100)=>
@statusIcon.addClass className
@timer and clearTimeout(@timer)
onStatusOut = =>
@statusIcon.removeClass className
@timer = setTimeout onStatusOut, time
destroy: ->
@statusIcon.remove()
_destroy = =>
if @hasParent()
@close()
if @statusIcon and @statusIcon.parentNode
@statusIcon.parentNode.removeChild(@statusIcon)
@statusView.removeCommandView this
if @program
@program.once 'exit', _destroy
@program.kill()
else
_destroy()
terminateProcessTree: () ->
pid = @program.pid
psTree = require 'ps-tree'
killProcess = (pid, signal, callback) ->
signal = signal || 'SIGKILL'
callback = callback || () -> {}
killTree = true
if killTree
psTree(pid, (err, children) ->
[pid].concat(
children.map((p) ->
return p.PID
)
).forEach((tpid) ->
try
process.kill tpid, signal
catch ex
)
callback()
)
else
try
process.kill pid, signal
catch ex
callback()
killProcess pid, 'SIGINT'
kill: ->
if @program
@terminateProcessTree @program.pid
@program.stdin.pause()
@program.kill('SIGINT')
@program.kill()
maximize: ->
@cliOutput.height (@cliOutput.height()+9999)
open: ->
if (atom.config.get('terminalix.moveToCurrentDirOnOpen')) and (not @specsMode)
@moveToCurrentDirectory()
if (atom.config.get('terminalix.moveToCurrentDirOnOpenLS')) and (not @specsMode)
@clear()
@execDelayedCommand @_cmdintdel, 'ls', null, this
@configFileFtp = findConfig.read('.ftpconfig')
if @configFileFtp
#Get document, or throw exception on error
try
configData = yaml.safeLoad(@configFileFtp)
console.log("Found version"+configData.version)
#@execDelayedCommand @_cmdintdel, 'ssh', ['aa','bb'], this
#yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'))
catch e
console.log("Error reading .ftpconfig file: "+e)
else
console.log("Config file not found")
atom.workspace.addBottomPanel(item: this) unless @hasParent()
if lastOpenedView and lastOpenedView != this
lastOpenedView.close()
lastOpenedView = this
@setMaxWindowHeight()
@putInputBox() if not @spawnProcessActive
@scrollToBottom()
@statusView.setActiveCommandView this
@focusInputBox()
@showInitMessage()
atom.tooltips.add @killBtn,
title: 'Kill the long working process.'
atom.tooltips.add @exitBtn,
title: 'Destroy the terminal session.'
atom.tooltips.add @closeBtn,
title: 'Hide the terminal window.'
atom.tooltips.add @openConfigBtn,
title: 'Open the terminal config file.'
atom.tooltips.add @reloadConfigBtn,
title: 'Reload the terminal configuration.'
if atom.config.get 'terminalix.enableWindowAnimations'
@WindowMinHeight = @cliOutput.height() + 50
@height 0
@consoleToolbarHeading.css {opacity: 0}
@animate {
height: @WindowMinHeight
}, 250, =>
@attr 'style', ''
@consoleToolbarHeading.animate {
opacity: 1
}, 250, =>
@consoleToolbarHeading.attr 'style', ''
close: ->
if atom.config.get 'terminalix.enableWindowAnimations'
@WindowMinHeight = @cliOutput.height() + 50
@height @WindowMinHeight
@animate {
height: 0
}, 250, =>
@attr 'style', ''
@consoleToolbar.attr 'style', ''
@detach()
lastOpenedView = null
else
@detach()
lastOpenedView = null
toggle: ->
if @hasParent()
@close()
else
@open()
removeQuotes: (text)->
if not text?
return ''
if text instanceof Array
ret = []
for t in text
ret.push (@removeQuotes t)
return ret
return text.replace(/['"]+/g, '')
cd: (args)->
args = [atom.project.getPaths()[0]] if not args[0]
args = @removeQuotes args
dir = resolve @getCwd(), args[0]
try
stat = fs.statSync dir
if not stat.isDirectory()
return @errorMessage "cd: not a directory: #{args[0]}"
@cwd = dir
catch e
return @errorMessage "cd: #{args[0]}: No such file or directory"
return null
ls: (args) ->
try
files = fs.readdirSync @getCwd()
catch e
return false
if atom.config.get('terminalix.XExperimentEnableForceLinking')
ret = ''
files.forEach (filename) =>
ret += @resolvePath filename + '\t%(break)'
@message ret
return true
filesBlocks = []
files.forEach (filename) =>
filesBlocks.push @_fileInfoHtml(filename, @getCwd())
filesBlocks = filesBlocks.sort (a, b) ->
aDir = false
bDir = false
if a[1]?
aDir = a[1].isDirectory()
if b[1]?
bDir = b[1].isDirectory()
if aDir and not bDir
return -1
if not aDir and bDir
return 1
a[2] > b[2] and 1 or -1
filesBlocks.unshift @_fileInfoHtml('..', @getCwd())
filesBlocks = filesBlocks.map (b) ->
b[0]
@message filesBlocks.join('%(break)') + '<div class="clear"/>'
return true
parseSpecialNodes: () ->
caller = this
if atom.config.get 'terminalix.enableConsoleInteractiveHints'
$('.atp-tooltip[data-toggle="tooltip"]').each(() ->
title = $(this).attr('title')
atom.tooltips.add $(this), {}
)
if atom.config.get 'terminalix.enableConsoleInteractiveLinks'
@find('.console-link').each (
() ->
el = $(this)
link_target = el.data('target')
if link_target != null && link_target != undefined
el.data('target', null)
link_type = el.data('targettype')
link_target_name = el.data('targetname')
link_target_line = el.data('line')
link_target_column = el.data('column')
if not link_target_line?
link_target_line = 0
if not link_target_column?
link_target_column = 0
el.click () ->
el.addClass('link-used')
if link_type == 'file'
atom.workspace.open link_target, {
initialLine: link_target_line
initialColumn: link_target_column
}
if link_type == 'directory'
moveToDir = (directory, messageDisp=false)->
caller.clear()
caller.cd([directory])
setTimeout () ->
if not caller.ls()
if not messageDisp
caller.errorMessage 'The directory is inaccesible.\n'
messageDisp = true
setTimeout () ->
moveToDir('..', messageDisp)
, 1500
, caller._cmdintdel
setTimeout () ->
moveToDir(link_target_name)
, caller._cmdintdel
)
# el.data('filenameLink', '')
consoleAlert: (text) ->
return '<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Warning!</strong> ' + text + '</div>'
consolePanel: (title, content) ->
return '<div class="panel panel-info welcome-panel"><div class="panel-heading">'+title+'</div><div class="panel-body">'+content+'</div></div><br><br>'
consoleText: (type, text) ->
if type == 'info'
return '<span class="text-info" style="margin-left:10px;">'+text+'</span>'
if type == 'error'
return '<span class="text-error" style="margin-left:10px;">'+text+'</span>'
if type == 'warning'
return '<span class="text-warning" style="margin-left:10px;">'+text+'</span>'
if type == 'success'
return '<span class="text-success" style="margin-left:10px;">'+text+'</span>'
return text
consoleLabel: (type, text) ->
if (not atom.config.get 'terminalix.enableConsoleLabels') and (not @specsMode)
return text
if not text?
text = type
if type == 'badge'
return '<span class="badge">'+text+'</span>'
if type == 'default'
return '<span class="inline-block highlight">'+text+'</span>'
if type == 'primary'
return '<span class="label label-primary">'+text+'</span>'
if type == 'success'
return '<span class="inline-block highlight-success">'+text+'</span>'
if type == 'info'
return '<span class="inline-block highlight-info">'+text+'</span>'
if type == 'warning'
return '<span class="inline-block highlight-warning">'+text+'</span>'
if type == 'danger'
return '<span class="inline-block highlight-error">'+text+'</span>'
if type == 'error'
return '<span class="inline-block highlight-error">'+text+'</span>'
return '<span class="label label-default">'+text+'</span>'
consoleLink: (name, forced=true) ->
if (atom.config.get 'terminalix.XExperimentEnableForceLinking') and (not forced)
return name
return @_fileInfoHtml(name, @getCwd(), 'font', false)[0]
_fileInfoHtml: (filename, parent, wrapper_class='span', use_file_info_class='true') ->
str = filename
name_tokens = filename
filename = filename.replace /:[0-9]+:[0-9]/ig, ''
name_tokens = @util.replaceAll filename, '', name_tokens
name_tokens = name_tokens.split ':'
fileline = name_tokens[0]
filecolumn = name_tokens[1]
filename = @util.replaceAll '/', '\\', filename
filename = @util.replaceAll parent, '', filename
filename = @util.replaceAll (@util.replaceAll '/', '\\', parent), '', filename
if filename[0] == '\\' or filename[0] == '/'
filename = filename.substring(1)
if filename == '..'
if use_file_info_class
return ["<font class=\"file-extension\"><#{wrapper_class} data-targetname=\"#{filename}\" data-targettype=\"directory\" data-target=\"#{filename}\" class=\"console-link icon-file-directory parent-folder\">#{filename}</#{wrapper_class}></font>", null, filename]
else
return ["<font class=\"file-extension\"><#{wrapper_class} data-targetname=\"#{filename}\" data-targettype=\"directory\" data-target=\"#{filename}\" class=\"console-link icon-file-directory file-info parent-folder\">#{filename}</#{wrapper_class}></font>", null, filename]
file_exists = true
filepath = @resolvePath filename
classes = []
dataname = ''
if atom.config.get('terminalix.useAtomIcons')
classes.push 'name'
classes.push 'icon'
dataname = filepath
else
classes.push 'name'
if use_file_info_class
classes.push 'file-info'
stat = null
if file_exists
try
stat = fs.lstatSync filepath
catch e
file_exists = false
if file_exists
if atom.config.get('terminalix.enableConsoleInteractiveLinks') or @specsMode
classes.push 'console-link'
if stat.isSymbolicLink()
classes.push 'stat-link'
stat = fs.statSync filepath
target_type = 'null'
if stat.isFile()
if stat.mode & 73 #0111
classes.push 'stat-program'
# TODO:10 check extension
matcher = /(.:)((.*)\\)*((.*\.)*)/ig
extension = filepath.replace matcher, ""
classes.push @util.replaceAll(' ', '', extension)
classes.push 'icon-file-text'
target_type = 'file'
if stat.isDirectory()
classes.push 'icon-file-directory'
target_type = 'directory'
if stat.isCharacterDevice()
classes.push 'stat-char-dev'
target_type = 'device'
if stat.isFIFO()
classes.push 'stat-fifo'
target_type = 'fifo'
if stat.isSocket()
classes.push 'stat-sock'
target_type = 'sock'
else
classes.push 'file-not-found'
classes.push 'icon-file-text'
target_type = 'file'
if filename[0] == '.'
classes.push 'status-ignored'
target_type = 'ignored'
href = 'file:///' + @util.replaceAll('\\', '/', filepath)
classes.push 'atp-tooltip'
exattrs = []
if fileline?
exattrs.push 'data-line="'+fileline+'"'
if filecolumn?
exattrs.push 'data-column="'+filecolumn+'"'
filepath_tooltip = @util.replaceAll '\\', '/', filepath
filepath = @util.replaceAll '\\', '/', filepath
["<font class=\"file-extension\"><#{wrapper_class} #{exattrs.join ' '} tooltip=\"\" data-targetname=\"#{filename}\" data-targettype=\"#{target_type}\" data-target=\"#{filepath}\" data-name=\"#{dataname}\" class=\"#{classes.join ' '}\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"#{filepath_tooltip}\" >#{filename}</#{wrapper_class}></font>", stat, filename]
getGitStatusName: (path, gitRoot, repo) ->
status = (repo.getCachedPathStatus or repo.getPathStatus)(path)
if status
if repo.isStatusModified status
return 'modified'
if repo.isStatusNew status
return 'added'
if repo.isPathIgnore path
return 'ignored'
preserveOriginalPaths: (text) ->
text = @util.replaceAll @getCurrentFilePath(), '%(file-original)', text
text = @util.replaceAll @getCwd(), '%(cwd-original)', text
text = @util.replaceAll @getCwd(), '%(cwd-original)', text
text = @util.replaceAll '/', '&fs;', text
text = @util.replaceAll '\\', '&bs;', text
return text
parseMessage: (message, matchSpec=true, parseCustomRules=true) ->
instance = this
message = '<div>'+(instance.parseMessage_ message, false, true, true)+'</div>'
n = $(message)
n.contents().filter(() ->
return this.nodeType == 3
).each(() ->
thiz = $(this)
out = thiz.text()
out = instance.parseMessage_ out, matchSpec, parseCustomRules
thiz.replaceWith('<span>'+out+'</span>')
)
return n.html()
parseMessage_: (message, matchSpec=true, parseCustomRules=true, isForcelyPreparsering=false) ->
if message == null
return ''
if matchSpec
if atom.config.get('terminalix.XExperimentEnableForceLinking')
if atom.config.get('terminalix.textReplacementFileAdress')?
if atom.config.get('terminalix.textReplacementFileAdress') != ''
# regex = /(([A-Za-z]:)(\\|\/))?([A-Za-z$\*\-+&#@!_\.]+(\\|\/))([A-Za-z $\*\-+&#@!_\.]+(\\|\/))*[A-Za-z\-_$\*\+&\^@#\. ]+\.[A-Za-z\-_$\*\+]*/ig
# regex = /(([A-Za-z]:)(\\|\/))?(([^\s#@$%&!;<>\.\^:]| )+(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
regex = /(\.(\\|\/))?(([A-Za-z]:)(\\|\/))?(([^\s#@$%&!;<>\.\^:]| )+(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
regex2 = /(\.(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
message = message.replace regex2, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
else
if atom.config.get('terminalix.textReplacementFileAdress')?
if atom.config.get('terminalix.textReplacementFileAdress') != ''
#regex = /(([A-Za-z]:)(\\|\/))?([A-Za-z$\*\-+&#@!_\.]+(\\|\/))([A-Za-z $\*\-+&#@!_\.]+(\\|\/))*[A-Za-z\-_$\*\+&\^@#\. ]+\.[A-Za-z\-_$\*\+]*/ig
cwdN = @getCwd()
cwdE = @util.replaceAll '/', '\\', @getCwd()
regexString ='(' + (@util.escapeRegExp cwdN) + '|' + (@util.escapeRegExp cwdE) + ')\\\\([^\\s:#$%^&!:]| )+\\.?([^\\s:#$@%&\\*\\^!0-9:\\.+\\-,\\\\\\/\"]| )*'
regex = new RegExp(regexString, 'ig')
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
if atom.config.get('terminalix.textReplacementCurrentFile')?
if atom.config.get('terminalix.textReplacementCurrentFile') != ''
path = @getCurrentFilePath()
regex = new RegExp @util.escapeRegExp(path), 'g'
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementCurrentFile'), {file:match}
message = @preserveOriginalPaths message
if atom.config.get('terminalix.textReplacementCurrentPath')?
if atom.config.get('terminalix.textReplacementCurrentPath') != ''
path = @getCwd()
regex = new RegExp @util.escapeRegExp(path), 'g'
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementCurrentPath'), {file:match}
message = @util.replaceAll '%(file-original)', @getCurrentFilePath(), message
message = @util.replaceAll '%(cwd-original)', @getCwd(), message
message = @util.replaceAll '&fs;', '/', message
message = @util.replaceAll '&bs;', '\\', message
rules = ATPCore.getConfig().rules
for key, value of rules
matchExp = key
replExp = '%(content)'
matchAllLine = false
matchNextLines = 0
flags = 'gm'
forceParse = false
if value.match?
if value.match.flags?
flags = value.match.flags.join ''
if value.match.replace?
replExp = value.match.replace
if value.match.matchLine?
matchAllLine = value.match.matchLine
if value.match.matchNextLines?
matchNextLines = value.match.matchNextLines
if value.match.forced?
forceParse = value.match.forced
if (forceParse or parseCustomRules) and ((isForcelyPreparsering and forceParse) or (not isForcelyPreparsering))
if matchAllLine
matchExp = '.*' + matchExp
if matchNextLines > 0
for i in [0..matchNextLines] by 1
matchExp = matchExp + '[\\r\\n].*'
regex = new RegExp(matchExp, flags)
message = message.replace regex, (match, groups...) =>
style = ''
if value.css?
style = ATPCore.jsonCssToInlineStyle value.css
else if not value.match?
style = ATPCore.jsonCssToInlineStyle value
vars =
content: match
0: match
groupsNumber = groups.length-1
for i in [0..groupsNumber] by 1
if groups[i]?
vars[i+1] = groups[i]
# console.log 'Active rule => '+matchExp
repl = @parseSpecialStringTemplate replExp, vars
return "<font style=\"#{style}\">#{repl}</font>"
message = @util.replaceAll '%(file-original)', @getCurrentFilePath(), message
message = @util.replaceAll '%(cwd-original)', @getCwd(), message
message = @util.replaceAll '&fs;', '/', message
message = @util.replaceAll '&bs;', '\\', message
return message
redirect: (streamName) ->
@redirectOutput = streamName
rawMessage: (message) ->
if @redirectOutput == 'console'
console.log message
return
@cliOutput.append message
@showCmd()
# @parseSpecialNodes()
message: (message, matchSpec=true) ->
if @redirectOutput == 'console'
console.log message
return
if typeof message is 'object'
mes = message
else
if not message?
return
mes = message.split '%(break)'
if mes.length > 1
for m in mes
@message m
return
else
mes = mes[0]
mes = @parseMessage message, matchSpec, matchSpec
mes = @util.replaceAll '%(raw)', '', mes
mes = @parseTemplate mes, [], true
# mes = @util.replaceAll '<', '<', mes
# mes = @util.replaceAll '>', '>', mes
@cliOutput.append mes
@showCmd()
@parseSpecialNodes()
@scrollToBottom()
# @putInputBox()
errorMessage: (message) ->
@cliOutput.append @parseMessage(message)
@clearStatusIcon()
@statusIcon.addClass 'status-error'
@parseSpecialNodes()
correctFilePath: (path) ->
return @util.replaceAll '\\', '/', path
getCwd: ->
if not atom.project?
return null
extFile = extname atom.project.getPaths()[0]
if extFile == ""
if atom.project.getPaths()[0]
projectDir = atom.project.getPaths()[0]
else
if process.env.HOME
projectDir = process.env.HOME
else if process.env.USERPROFILE
projectDir = process.env.USERPROFILE
else
projectDir = '/'
else
projectDir = dirname atom.project.getPaths()[0]
cwd = @cwd or projectDir or @userHome
return @correctFilePath cwd
spawn: (inputCmd, cmd, args) =>
## @cmdEditor.hide()
## htmlStream = ansihtml()
# htmlStream = iconv.decodeStream @streamsEncoding
# htmlStream.on 'data', (data) =>
## @cliOutput.append data
# @message data
# @scrollToBottom()
# try
## @program = spawn cmd, args, stdio: 'pipe', env: process.env, cwd: @getCwd()
# @program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd()
## @program.stdin.pipe htmlStream
# @program.stdout.pipe htmlStream
# @program.stderr.pipe htmlStream
## @program.stdout.setEncoding @streamsEncoding
@spawnProcessActive = true
instance = this
dataCallback = (data) ->
instance.message(data)
instance.scrollToBottom()
processCallback = (error, stdout, stderr) ->
console.log 'callback' if atom.config.get('terminalix.logConsole') or @specsMode
console.log(error, stdout, stderr)
instance.putInputBox()
instance.showCmd()
htmlStream = ansihtml()
htmlStream = iconv.decodeStream @streamsEncoding
htmlStream.on 'data', dataCallback
try
if @configFileFtp
@program = process
@programSSH = execSSH('echo dada', {
user: 'admin123'
host: 'vps123.ovh.net'
passphrase: '<PASSWORD>'
key: 'c:/<KEY>user<KEY>'
password: '<PASSWORD>'
timeout: 10000
}, processCallback)
console.log(@programSSH)
@programSSH.pipe @program.stdout
@program.stdin.pipe htmlStream
#(@program.stdin.pipe iconv.encodeStream 'base64').pipe htmlStream
#@program = execSSH inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
else
@program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
@program.stdout.setEncoding 'base64'
console.log @program if atom.config.get('terminalix.logConsole') or @specsMode
(@program.stdout.pipe iconv.encodeStream 'base64').pipe htmlStream
@clearStatusIcon()
@statusIcon.addClass 'status-running'
@killBtn.removeClass 'hide'
@program.on 'exit', (code, signal) =>
console.log 'exit', code, signal if atom.config.get('terminalix.logConsole') or @specsMode
@killBtn.addClass 'hide'
@statusIcon.removeClass 'status-running'
if code == 0
@statusIcon.addClass 'status-success'
else if code?
@statusIcon.addClass 'status-error'
if code == 127
@message (@consoleLabel 'error', 'Error')+(@consoleText 'error', cmd + ': command not found')
@message '\n'
@program = null
@spawnProcessActive = false
@program.on 'error', (err) =>
console.log 'error' if atom.config.get('terminalix.logConsole') or @specsMode
@message (err.message)
@message '\n'
@putInputBox()
@showCmd()
@statusIcon.addClass 'status-error'
@program.stdout.on 'data', (data) =>
@flashIconClass 'status-info'
@statusIcon.removeClass 'status-error'
@program.stderr.on 'data', (data) =>
console.log 'stderr' if atom.config.get('terminalix.logConsole') or @specsMode
@message data
@flashIconClass 'status-error', 300
#DOING:20 x 2017-08-09 This task was created on 2017-08-09 and complited 2017-08-23
catch err
console.log 'Failed to launch process' if atom.config.get('terminalix.logConsole') or @specsMode
# IDEA: test it
@message ('haha '+err.message)
#DOING:21 This task is due on 2017-08-24 due:2017-08-24
@showCmd()
spawnR: (inputCmd, cmd, args) =>
@spawnRProcessActive = true
instance = this
dataCallback = (data) ->
instance.message(data)
instance.scrollToBottom()
processCallback = (error, stdout, stderr) ->
console.log 'callback' if atom.config.get('terminalix.logConsole') or @specsMode
console.log(error, stdout, stderr)
instance.putInputBox()
instance.showCmd()
htmlStream = ansihtml()
htmlStream = iconv.decodeStream @streamsEncoding
htmlStream.on 'data', dataCallback
sshCallback = (err, ssh) =>
console.log 'ssh'
console.log ssh
console.log err
try
if err
@program = new EventEmitter()
@program.emit('error',err)
processCallback(err,null,null)
else
@program = execR {cmd: 'ls -lah', ssh: ssh}, (err, stdout, stderr) ->
console.log ssh
console.log 'err:'
console.log err
console.log stderr
console.log stdout
#@program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
@program.stdout.setEncoding 'base64'
console.log @program if atom.config.get('terminalix.logConsole') or @specsMode
(@program.stdout.pipe iconv.encodeStream 'base64').pipe htmlStream
@clearStatusIcon()
@statusIcon.addClass 'status-running'
@killBtn.removeClass 'hide'
@program.on 'exit', (code, signal) =>
console.log 'exit', code, signal if atom.config.get('terminalix.logConsole') or @specsMode
@killBtn.addClass 'hide'
@statusIcon.removeClass 'status-running'
if code == 0
@statusIcon.addClass 'status-success'
else if code?
@statusIcon.addClass 'status-error'
if code == 127
@message (@consoleLabel 'error', 'Error')+(@consoleText 'error', cmd + ': command not found')
@message '\n'
@program = null
@spawnRProcessActive = false
@program.on 'error', (err) =>
console.log 'error' if atom.config.get('terminalix.logConsole') or @specsMode
@message (err.message)
@message '\n'
@putInputBox()
@showCmd()
@statusIcon.addClass 'status-error'
@flashIconClass 'status-error', 300
@program.stdout.on 'data', (data) =>
@flashIconClass 'status-info'
@statusIcon.removeClass 'status-error'
@program.stderr.on 'data', (data) =>
console.log 'stderr' if atom.config.get('terminalix.logConsole') or @specsMode
@message data
@flashIconClass 'status-error', 300
#DOING:20 x 2017-08-09 This task was created on 2017-08-09 and complited 2017-08-23
catch err1
console.log 'Failed to launch process' if atom.config.get('terminalix.logConsole') or @specsMode
console.log err1
# IDEA: test it
@message err1.message
#DOING:21 This task is due on 2017-08-24 due:2017-08-24
@showCmd()
try
connect {
user: 'admin123'
host: 'vps123.ovh.net'
#passphrase: '<PASSWORD>'
#key: 'c:/users/user1/.ssh/id_rsa'
password: '<PASSWORD>'
timeout: 10000
}, sshCallback
catch err2
console.log err2
# coffeeli1111nt: enable=*
# coffeelint: enable=max_line_length
| true | ###
Terminalix plugin forked from awesome
Atom-terminal-panel
Copyright by isis97/VadimDor
MIT licensed
The main terminal view class, which does the most of all the work.
###
#coffeelint: disable=max_line_length
lastOpenedView = null
fs = include 'fs'
os = include 'os'
{$, TextEditorView, View} = include 'atom-space-pen-views'
{spawn, exec, execSync} = include 'child_process'
{execR, execSyncR} = include 'ssh2-exec'
{connR} = include 'ssh2-connect'
EventEmitter = (include 'events').EventEmitter
{resolve, dirname, extname, sep} = include 'path'
findConfig = include 'find-config'
yaml = include 'js-yaml'
connect = include 'ssh2-connect'
exec_SSH = include 'ssh2-exec'
execSSH = include 'ssh-exec-plus'
ansihtml = include 'ansi-html-stream'
stream = include 'stream'
iconv = include 'iconv-lite'
ATPCommandFinderView = include 'atp-command-finder'
ATPCore = include 'atp-core'
ATPCommandsBuiltins = include 'atp-builtins-commands'
ATPVariablesBuiltins = include 'atp-builtins-variables'
window.$ = window.jQuery = $
include 'jquery-autocomplete-js'
module.exports =
class ATPOutputView extends View
cwd: null
#streamsEncoding: 'iso-8859-3'
streamsEncoding : '"'+atom.config.get('terminalix.textEncode')+'"'
_cmdintdel: 50
echoOn: true
configFileFtp: null
redirectOutput: ''
specsMode: false
inputLine: 0
helloMessageShown: false
minHeight: 250
util: include 'atp-terminal-util'
currentInputBox: null
#currentInputBox: null
currentInputBoxTmr: null
volatileSuggestions: []
disposables:
dispose: (field) =>
if not this[field]?
this[field] = []
a = this[field]
for i in [0..a.length-1] by 1
a[i].dispose()
add: (field, value) =>
if not this[field]?
this[field] = []
this[field].push value
keyCodes: {
enter: 13
arrowUp: 38
arrowDown: 40
arrowLeft: 37
arrowRight: 39
}
localCommandAtomBindings: []
localCommands: ATPCommandsBuiltins
@content: ->
@div tabIndex: -1, class: 'panel atp-panel panel-bottom', outlet: 'atpView', =>
@div class: 'terminal panel-divider', style: 'cursor:n-resize;width:100%;height:8px;', outlet: 'panelDivider'
@button outlet: 'maximizeIconBtn', class: 'atp-maximize-btn', click: 'maximize'
@button outlet: 'closeIconBtn', class: 'atp-close-btn', click: 'close'
@button outlet: 'destroyIconBtn', class: 'atp-destroy-btn', click: 'destroy'
@div class: 'panel-heading btn-toolbar', outlet:'consoleToolbarHeading', =>
@div class: 'btn-group', outlet:'consoleToolbar', =>
@button outlet: 'killBtn', click: 'kill', class: 'btn hide', =>
@span 'kill'
@button outlet: 'exitBtn', click: 'destroy', class: 'btn', =>
@span 'exit'
@button outlet: 'closeBtn', click: 'close', class: 'btn', =>
@span class: "icon icon-x"
@span 'close'
@button outlet: 'openConfigBtn', class: 'btn icon icon-gear inline-block-tight button-settings', click: 'showSettings', =>
@span 'Open config'
@button outlet: 'reloadConfigBtn', class: 'btn icon icon-gear inline-block-tight button-settings', click: 'reloadSettings', =>
@span 'Reload config'
@div class: 'atp-panel-body', =>
@pre class: "terminal", outlet: "cliOutput"
toggleAutoCompletion: () ->
if @currentInputBoxCmp?
@currentInputBoxCmp.enable()
@currentInputBoxCmp.repaint()
@currentInputBoxCmp.showDropDown()
@currentInputBox.find('.terminal-input').height('100px')
fsSpy: () ->
@volatileSuggestions = []
if @cwd?
fs.readdir @cwd, (err, files) =>
if files?
for file in files
@volatileSuggestions.push file
turnSpecsMode: (state) ->
@specsMode = state
getRawOutput: () ->
t = @getHtmlOutput().replace(/<[^>]*>/igm, "")
t = @util.replaceAll ">", ">", t
t = @util.replaceAll "<", "<", t
t = @util.replaceAll """, "\"", t
return t
getHtmlOutput: () ->
return @cliOutput.html()
resolvePath: (path) ->
path = @util.replaceAll '\"', '', path
filepath = ''
if path.match(/([A-Za-z]):/ig) != null
filepath = path
else
filepath = @getCwd() + '/' + path
filepath = @util.replaceAll '\\', '/', filepath
return @util.replaceAll '\\', '/', (resolve filepath)
reloadSettings: () ->
@onCommand 'update'
showSettings: () ->
setTimeout () ->
panelPath = atom.packages.resolvePackagePath 'terminalix'
atomPath = resolve panelPath+'/../..'
configPath = atomPath + '/terminal-commands.json'
atom.workspace.open configPath
, 50
focusInputBox: () ->
if @currentInputBoxCmp?
@currentInputBoxCmp.input.focus()
updateInputCursor: (textarea) ->
@rawMessage 'test\n'
val = textarea.val()
textarea
.blur()
.focus()
.val("")
.val(val)
removeInputBox: () ->
@cliOutput.find('.atp-dynamic-input-box').remove()
putInputBox: () ->
if @currentInputBoxTmr?
clearInterval @currentInputBoxTmr
@currentInputBoxTmr = null
@cliOutput.find('.atp-dynamic-input-box').remove()
prompt = @getCommandPrompt('')
@currentInputBox = $(
'<div style="width: 100%; white-space:nowrap; overflow:hidden; display:inline-block;" class="atp-dynamic-input-box">' +
'<div style="position:relative; top:5px; max-height:500px; width: 100%; bottom: -10px; height: 20px; white-space:nowrap; overflow:hidden; display:inline-block;" class="terminal-input native-key-bindings"></div>' +
'</div>'
)
@currentInputBox.prepend ' '
@currentInputBox.prepend prompt
#@cliOutput.mousedown (e) =>
# if e.which is 1
# @focusInputBox()
history = []
if @currentInputBoxCmp?
history = @currentInputBoxCmp.getInputHistory()
inputComp = @currentInputBox.find '.terminal-input'
@currentInputBoxCmp = inputComp.autocomplete {
animation: [
['opacity', 0, 0.8]
]
isDisabled: true
inputHistory: history
inputWidth: '80%'
dropDownWidth: '30%'
dropDownDescriptionBoxWidth: '30%'
dropDownPosition: 'top'
showDropDown: atom.config.get 'terminalix.enableConsoleSuggestionsDropdown'
}
@currentInputBoxCmp
.confirmed(() =>
@currentInputBoxCmp.disable().repaint()
@onCommand()
).changed((inst, text) =>
if inst.getText().length <= 0
@currentInputBoxCmp.disable().repaint()
@currentInputBox.find('.terminal-input').height('20px')
)
@currentInputBoxCmp.input.keydown((e) =>
if (e.keyCode == 17) and (@currentInputBoxCmp.getText().length > 0)
###
@currentInputBoxCmp.enable().repaint()
@currentInputBoxCmp.showDropDown()
@currentInputBox.find('.terminal-input').height('100px');
###
else if (e.keyCode == 32) or (e.keyCode == 8)
@currentInputBoxCmp.disable().repaint()
@currentInputBox.find('.terminal-input').height('20px')
)
endsWith = (text, suffix) ->
return text.indexOf(suffix, text.length - suffix.length) != -1
@currentInputBoxCmp.options = (instance, text, lastToken) =>
token = lastToken
if not token?
token = ''
if not (endsWith(token, '/') or endsWith(token, '\\'))
token = @util.replaceAll '\\', sep, token
token = token.split sep
token.pop()
token = token.join(sep)
if not endsWith(token, sep)
token = token + sep
o = @getCommandsNames().concat(@volatileSuggestions)
fsStat = []
if token?
try
fsStat = fs.readdirSync(token)
for i in [0..fsStat.length-1] by 1
fsStat[i] = token + fsStat[i]
catch e
ret = o.concat(fsStat)
return ret
@currentInputBoxCmp.hideDropDown()
setTimeout () =>
@currentInputBoxCmp.input.focus()
, 0
@cliOutput.append @currentInputBox
inputBoxState: () ->
inputState = @cliOutput.find('.atp-dynamic-input-box').clone()
inputState.find('.autocomplete-wrapper').replaceWith () ->
input = $(this).find('.autocomplete-input')[0]
return $('<span/>', class: input.className, text: input.value)
inputState.removeClass 'atp-dynamic-input-box'
return inputState.prop('outerHTML') + '\n'
readInputBox: () ->
ret = ''
if @currentInputBoxCmp?
# ret = @currentInputBox.find('.terminal-input').val()
ret = @currentInputBoxCmp.getText()
return ret
requireCSS: (location) ->
if not location?
return
location = resolve location
console.log ("Require terminalix plugin CSS file: "+location+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
$('head').append "<link rel='stylesheet' type='text/css' href='#{location}'/>"
resolvePluginDependencies: (path, plugin) ->
config = plugin.dependencies
if not config?
return
css_dependencies = config.css
if not css_dependencies?
css_dependencies = []
for css_dependency in css_dependencies
@requireCSS path+"/"+css_dependency
delete plugin['dependencies']
init: () ->
###
TODO: test-autocomplete Remove this!
el = $('<div style="z-index: 9999; position: absolute; left: 200px; top: 200px;" id="glotest"></div>')
el.autocomplete({
inputWidth: '80%'
})
$('body').append(el)
###
@streamsEncoding = '"'+atom.config.get('terminalix.textEncode')+'"'
lastY = -1
mouseDown = false
panelDraggingActive = false
@panelDivider
.mousedown () -> panelDraggingActive = true
.mouseup () -> panelDraggingActive = false
$(document)
.mousedown () -> mouseDown = true
.mouseup () -> mouseDown = false
.mousemove (e) ->
if mouseDown and panelDraggingActive
if lastY != -1
delta = e.pageY - lastY
@cliOutput.height @cliOutput.height()-delta
lastY = e.pageY
else
lastY = -1
normalizedPath = require("path").join(__dirname, "../commands")
console.log ("Loading terminalix plugins from the directory: "+normalizedPath+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
fs.readdirSync(normalizedPath).forEach( (folder) =>
fullpath = resolve "../commands/" +folder
console.log ("Require terminalix plugin: "+folder+"\n") if atom.config.get('terminalix.logConsole') or @specsMode
obj = require ("../commands/" +folder+"/index.coffee")
console.log "Plugin loaded." if atom.config.get('terminalix.logConsole')
@resolvePluginDependencies fullpath, obj
for key, value of obj
if value.command?
@localCommands[key] = value
@localCommands[key].source = 'external-functional'
@localCommands[key].sourcefile = folder
else if value.variable?
value.name = key
ATPVariablesBuiltins.putVariable value
)
console.log ("All plugins were loaded.") if atom.config.get('terminalix.logConsole')
if ATPCore.getConfig()?
actions = ATPCore.getConfig().actions
if actions?
for action in actions
if action.length > 1
obj = {}
obj['terminalix:'+action[0]] = () =>
@open()
@onCommand action[1]
atom.commands.add 'atom-workspace', obj
if atom.workspace?
eleqr = atom.workspace.getActivePaneItem() ? atom.workspace
eleqr = atom.views.getView(eleqr)
atomCommands = atom.commands.findCommands({target: eleqr})
for command in atomCommands
comName = command.name
com = {}
com.description = command.displayName
com.command =
((comNameP) ->
return (state, args) ->
ele = atom.workspace.getActivePaneItem() ? atom.workspace
ele = atom.views.getView(ele)
atom.commands.dispatch ele, comNameP
return (state.consoleLabel 'info', "info") + (state.consoleText 'info', 'Atom command executed: '+comNameP)
)(comName)
com.source = "internal-atom"
@localCommands[comName] = com
toolbar = ATPCore.getConfig().toolbar
if toolbar?
toolbar.reverse()
for com in toolbar
bt = $("<div class=\"btn\" data-action=\"#{com[1]}\" ><span>#{com[0]}</span></div>")
if com[2]?
atom.tooltips.add bt,
title: com[2]
@consoleToolbar.prepend bt
caller = this
bt.click () ->
caller.onCommand $(this).data('action')
return this
commandLineNotCounted: () ->
@inputLine--
parseSpecialStringTemplate: (prompt, values, isDOM=false) =>
if isDOM
return ATPVariablesBuiltins.parseHtml(this, prompt, values)
else
return ATPVariablesBuiltins.parse(this, prompt, values)
getCommandPrompt: (cmd) ->
return @parseTemplate atom.config.get('terminalix.commandPrompt'), {cmd: cmd}, true
delay: (callback, delay=100) ->
setTimeout callback, delay
execDelayedCommand: (delay, cmd, args, state) ->
caller = this
callback = ->
caller.exec cmd, args, state
setTimeout callback, delay
moveToCurrentDirectory: ()->
CURRENT_LOCATION = @getCurrentFileLocation()
if CURRENT_LOCATION?
@cd [CURRENT_LOCATION]
else if atom.project.getDirectories()[0]?
@cd [atom.project.getDirectories()[0].path]
getCurrentFileName: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getBaseName()
return null
getCurrentFileLocation: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getPath().replace ///#{current_file.getBaseName()}$///, ""
getCurrentFilePath: ()->
current_file = @getCurrentFile()
if current_file?
return current_file.getPath()
return null
getCurrentFile: ()->
if not atom.workspace?
return null
te = atom.workspace.getActiveTextEditor()
if te?
if te.getPath()?
return te.buffer.file
return null
parseTemplate: (text, vars, isDOM=false) ->
if not vars?
vars = {}
ret = ''
if isDOM
ret = ATPVariablesBuiltins.parseHtml this, text, vars
else
ret = @parseSpecialStringTemplate text, vars
ret = @util.replaceAll '%(file-original)', @getCurrentFilePath(), ret
ret = @util.replaceAll '%(cwd-original)', @getCwd(), ret
ret = @util.replaceAll '&fs;', '/', ret
ret = @util.replaceAll '&bs;', '\\', ret
return ret
parseExecToken__: (cmd, args, strArgs) ->
if strArgs?
cmd = @util.replaceAll "%(*)", strArgs, cmd
cmd = @util.replaceAll "%(*^)", (@util.replaceAll "%(*^)", "", cmd), cmd
if args?
argsNum = args.length
for i in [0..argsNum] by 1
if args[i]?
v = args[i].replace /\n/ig, ''
cmd = @util.replaceAll "%(#{i})", args[i], cmd
cmd = @parseTemplate cmd, {file:@getCurrentFilePath()}
return cmd
execStackCounter: 0
exec: (cmdStr, ref_args, state, callback) ->
if not state?
state = this
if not ref_args?
ref_args = {}
if cmdStr.split?
cmdStrC = cmdStr.split ';;'
if cmdStrC.length > 1
cmdStr = cmdStrC
@execStackCounter = 0
return @exec_ cmdStr, ref_args, state, callback
exec_: (cmdStr, ref_args, state, callback) ->
if not callback?
callback = () -> return null
++@execStackCounter
if cmdStr instanceof Array
ret = ''
for com in cmdStr
val = @exec com, ref_args, state
if val?
ret += val
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
cmdStr = @util.replaceAll "\\\"", '&hquot;', cmdStr
cmdStr = @util.replaceAll "&bs;\"", '&hquot;', cmdStr
cmdStr = @util.replaceAll "\\\'", '&lquot;', cmdStr
cmdStr = @util.replaceAll "&bs;\'", '&lquot;', cmdStr
ref_args_str = null
if ref_args?
if ref_args.join?
ref_args_str = ref_args.join(' ')
cmdStr = @parseExecToken__ cmdStr, ref_args, ref_args_str
args = []
cmd = cmdStr
cmd.replace /("[^"]*"|'[^']*'|[^\s'"]+)/g, (s) =>
if s[0] != '"' and s[0] != "'"
s = s.replace /~/g, @userHome
s = @util.replaceAll '&hquot;', '"', s
s = @util.replaceAll '&lquot;', '\'', s
args.push s
args = @util.dir args, @getCwd()
cmd = args.shift()
command = null
if @isCommandEnabled(cmd)
command = ATPCore.findUserCommand(cmd)
if command?
if not state?
ret = null
throw new Error 'The console functional (not native) command cannot be executed without caller information: \''+cmd+'\'.'
if command?
try
ret = command(state, args)
catch e
throw new Error "Error at executing terminal command: '#{cmd}' ('#{cmdStr}'): #{e.message}"
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
if atom.config.get('terminalix.enableExtendedCommands') or @specsMode
if @isCommandEnabled(cmd)
command = @getLocalCommand(cmd)
if command?
ret = command(state, args)
--@execStackCounter
if @execStackCounter==0
callback()
if not ret?
return null
return ret
else
cmdStr = @util.replaceAll '&hquot;', '"', cmdStr
cmd = @util.replaceAll '&hquot;', '"', cmd
cmdStr = @util.replaceAll '&lquot;', '\'', cmdStr
cmd = @util.replaceAll '&lquot;', '\'', cmd
#@spawn cmdStr, cmd, args
@spawnR cmdStr, cmd, args
--@execStackCounter
#if @execStackCounter==0
# callback()
if not cmd?
return null
return null
isCommandEnabled: (name) ->
disabledCommands = atom.config.get('terminalix.disabledExtendedCommands') or @specsMode
if not disabledCommands?
return true
if name in disabledCommands
return false
return true
getLocalCommand: (name) ->
for cmd_name, cmd_body of @localCommands
if cmd_name == name
if cmd_body.command?
return cmd_body.command
else
return cmd_body
return null
getCommandsRegistry: () ->
global_vars = ATPVariablesBuiltins.list
for key, value of process.env
global_vars['%(env.'+key+')'] = "access native environment variable: "+key
cmd = []
for cmd_name, cmd_body of @localCommands
cmd.push {
name: cmd_name
description: cmd_body.description
example: cmd_body.example
params: cmd_body.params
deprecated: cmd_body.deprecated
sourcefile: cmd_body.sourcefile
source: cmd_body.source or 'internal'
}
for cmd_name, cmd_body of ATPCore.getUserCommands()
cmd.push {
name: cmd_name
description: cmd_body.description
example: cmd_body.example
params: cmd_body.params
deprecated: cmd_body.deprecated
sourcefile: cmd_body.sourcefile
source: 'external'
}
for var_name, descr of global_vars
cmd.push {
name: var_name
description: descr
source: 'global-variable'
}
cmd_ = []
cmd_len = cmd.length
cmd_forbd = (atom.config.get 'terminalix.disabledExtendedCommands') or []
for cmd_item in cmd
if cmd_item.name in cmd_forbd
else
cmd_.push cmd_item
return cmd_
getCommandsNames: () ->
cmds = @getCommandsRegistry()
cmd_names = []
for item in cmds
descr = ""
example = ""
params = ""
sourcefile = ""
deprecated = false
name = item.name
if item.sourcefile?
sourcefile = "<div style='float:bottom'><b style='float:right'>Plugin #{item.sourcefile} <b></div>"
if item.example?
example = "<br><b><u>Example:</u></b><br><code>"+item.example+"</code>"
if item.params?
params = item.params
if item.deprecated
deprecated = true
icon_style = ''
descr_prefix = ''
if item.source == 'external'
icon_style = 'book'
descr_prefix = 'External: '
else if item.source == 'internal'
icon_style = 'repo'
descr_prefix = 'Builtin: '
else if item.source == 'internal-atom'
icon_style = 'repo'
descr_prefix = 'Atom command: '
else if item.source == 'external-functional'
icon_style = 'plus'
descr_prefix = 'Functional: '
else if item.source == 'global-variable'
icon_style = 'briefcase'
descr_prefix = 'Global variable: '
if deprecated
name = "<strike style='color:gray;font-weight:normal;'>"+name+"</strike>"
descr = "<div style='float:left; padding-top:10px;' class='status status-#{icon_style} icon icon-#{icon_style}'></div><div style='padding-left: 10px;'><b>#{name} #{params}</b><br>#{item.description} #{example} #{sourcefile}</div>"
cmd_names.push {
name: item.name
description: descr
html: true
}
return cmd_names
getLocalCommandsMemdump: () ->
cmd = @getCommandsRegistry()
commandFinder = new ATPCommandFinderView cmd
commandFinderPanel = atom.workspace.addModalPanel(item: commandFinder)
commandFinder.shown commandFinderPanel, this
return
commandProgress: (value) ->
if value < 0
@cliProgressBar.hide()
@cliProgressBar.attr('value', '0')
else
@cliProgressBar.show()
@cliProgressBar.attr('value', value/2)
showInitMessage: (forceShow=false) ->
if not forceShow
if @helloMessageShown
return
if atom.config.get 'terminalix.enableConsoleStartupInfo' or forceShow or (not @specsMode)
changelog_path = require("path").join(__dirname, "../CHANGELOG.md")
readme_path = require("path").join(__dirname, "../README.md")
hello_message = @consolePanel 'ATOM Terminal', 'Please enter new commands to the box below. (ctrl-to show suggestions dropdown)<br>The console supports special annotation like: %(path), %(file), %(link)file.something%(endlink).<br>It also supports special HTML elements like: %(tooltip:A:content:B) and so on.<br>Hope you\'ll enjoy the terminal.'+
"<br><a class='changelog-link' href='#{changelog_path}'>See changelog</a> <a class='readme-link' href='#{readme_path}'>and the README! :)</a>"
@rawMessage hello_message
$('.changelog-link').css('font-weight','300%').click(() ->
atom.workspace.open changelog_path
)
$('.readme-link').css('font-weight','300%').click(() ->
atom.workspace.open readme_path
)
@helloMessageShown = true
return this
clearStatusIcon: () ->
@statusIcon.removeClass()
@statusIcon.addClass('atp-panel icon icon-terminal')
onCommand: (inputCmd) ->
@fsSpy()
@rawMessage @inputBoxState()
@removeInputBox()
@clearStatusIcon()
if not inputCmd?
inputCmd = @readInputBox()
@disposables.dispose('statusIconTooltips')
@disposables.add 'statusIconTooltips', atom.tooltips.add @statusIcon,
title: 'Task: \"'+inputCmd+'\"'
delay: 0
animation: false
@inputLine++
inputCmd = @parseSpecialStringTemplate inputCmd
if @echoOn
console.log 'echo-on'
#AllOPenPointsTerminalix:0 Repair!
#@message "\n"+@getCommandPrompt(inputCmd)+" "+inputCmd+"\n", false
ret = @exec inputCmd, null, this, () =>
@putInputBox()
@showCmd()
if typeof ret is 'string'
@message ret + '\n'
return null
initialize: ->
@userHome = process.env.HOME or process.env.HOMEPATH or process.env.USERPROFILE
cmd = 'test -e /etc/profile && source /etc/profile;test -e ~/.profile && source ~/.profile; node -pe "JSON.stringify(process.env)"'
exec cmd, (code, stdout, stderr) ->
try
process.env = JSON.parse(stdout)
catch e
atom.commands.add 'atom-workspace',
"atp-status:toggle-output": => @toggle()
clear: ->
@cliOutput.empty()
@putInputBox()
setMaxWindowHeight: ->
maxHeight = atom.config.get('terminalix.WindowHeight')
@cliOutput.css("max-height", "#{maxHeight}px")
$('.terminal-input').css("max-height", "#{maxHeight}px")
showCmd: ->
@focusInputBox()
@scrollToBottom()
scrollToBottom: ->
@cliOutput.scrollTop 10000000
flashIconClass: (className, time=100)=>
@statusIcon.addClass className
@timer and clearTimeout(@timer)
onStatusOut = =>
@statusIcon.removeClass className
@timer = setTimeout onStatusOut, time
destroy: ->
@statusIcon.remove()
_destroy = =>
if @hasParent()
@close()
if @statusIcon and @statusIcon.parentNode
@statusIcon.parentNode.removeChild(@statusIcon)
@statusView.removeCommandView this
if @program
@program.once 'exit', _destroy
@program.kill()
else
_destroy()
terminateProcessTree: () ->
pid = @program.pid
psTree = require 'ps-tree'
killProcess = (pid, signal, callback) ->
signal = signal || 'SIGKILL'
callback = callback || () -> {}
killTree = true
if killTree
psTree(pid, (err, children) ->
[pid].concat(
children.map((p) ->
return p.PID
)
).forEach((tpid) ->
try
process.kill tpid, signal
catch ex
)
callback()
)
else
try
process.kill pid, signal
catch ex
callback()
killProcess pid, 'SIGINT'
kill: ->
if @program
@terminateProcessTree @program.pid
@program.stdin.pause()
@program.kill('SIGINT')
@program.kill()
maximize: ->
@cliOutput.height (@cliOutput.height()+9999)
open: ->
if (atom.config.get('terminalix.moveToCurrentDirOnOpen')) and (not @specsMode)
@moveToCurrentDirectory()
if (atom.config.get('terminalix.moveToCurrentDirOnOpenLS')) and (not @specsMode)
@clear()
@execDelayedCommand @_cmdintdel, 'ls', null, this
@configFileFtp = findConfig.read('.ftpconfig')
if @configFileFtp
#Get document, or throw exception on error
try
configData = yaml.safeLoad(@configFileFtp)
console.log("Found version"+configData.version)
#@execDelayedCommand @_cmdintdel, 'ssh', ['aa','bb'], this
#yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'))
catch e
console.log("Error reading .ftpconfig file: "+e)
else
console.log("Config file not found")
atom.workspace.addBottomPanel(item: this) unless @hasParent()
if lastOpenedView and lastOpenedView != this
lastOpenedView.close()
lastOpenedView = this
@setMaxWindowHeight()
@putInputBox() if not @spawnProcessActive
@scrollToBottom()
@statusView.setActiveCommandView this
@focusInputBox()
@showInitMessage()
atom.tooltips.add @killBtn,
title: 'Kill the long working process.'
atom.tooltips.add @exitBtn,
title: 'Destroy the terminal session.'
atom.tooltips.add @closeBtn,
title: 'Hide the terminal window.'
atom.tooltips.add @openConfigBtn,
title: 'Open the terminal config file.'
atom.tooltips.add @reloadConfigBtn,
title: 'Reload the terminal configuration.'
if atom.config.get 'terminalix.enableWindowAnimations'
@WindowMinHeight = @cliOutput.height() + 50
@height 0
@consoleToolbarHeading.css {opacity: 0}
@animate {
height: @WindowMinHeight
}, 250, =>
@attr 'style', ''
@consoleToolbarHeading.animate {
opacity: 1
}, 250, =>
@consoleToolbarHeading.attr 'style', ''
close: ->
if atom.config.get 'terminalix.enableWindowAnimations'
@WindowMinHeight = @cliOutput.height() + 50
@height @WindowMinHeight
@animate {
height: 0
}, 250, =>
@attr 'style', ''
@consoleToolbar.attr 'style', ''
@detach()
lastOpenedView = null
else
@detach()
lastOpenedView = null
toggle: ->
if @hasParent()
@close()
else
@open()
removeQuotes: (text)->
if not text?
return ''
if text instanceof Array
ret = []
for t in text
ret.push (@removeQuotes t)
return ret
return text.replace(/['"]+/g, '')
cd: (args)->
args = [atom.project.getPaths()[0]] if not args[0]
args = @removeQuotes args
dir = resolve @getCwd(), args[0]
try
stat = fs.statSync dir
if not stat.isDirectory()
return @errorMessage "cd: not a directory: #{args[0]}"
@cwd = dir
catch e
return @errorMessage "cd: #{args[0]}: No such file or directory"
return null
ls: (args) ->
try
files = fs.readdirSync @getCwd()
catch e
return false
if atom.config.get('terminalix.XExperimentEnableForceLinking')
ret = ''
files.forEach (filename) =>
ret += @resolvePath filename + '\t%(break)'
@message ret
return true
filesBlocks = []
files.forEach (filename) =>
filesBlocks.push @_fileInfoHtml(filename, @getCwd())
filesBlocks = filesBlocks.sort (a, b) ->
aDir = false
bDir = false
if a[1]?
aDir = a[1].isDirectory()
if b[1]?
bDir = b[1].isDirectory()
if aDir and not bDir
return -1
if not aDir and bDir
return 1
a[2] > b[2] and 1 or -1
filesBlocks.unshift @_fileInfoHtml('..', @getCwd())
filesBlocks = filesBlocks.map (b) ->
b[0]
@message filesBlocks.join('%(break)') + '<div class="clear"/>'
return true
parseSpecialNodes: () ->
caller = this
if atom.config.get 'terminalix.enableConsoleInteractiveHints'
$('.atp-tooltip[data-toggle="tooltip"]').each(() ->
title = $(this).attr('title')
atom.tooltips.add $(this), {}
)
if atom.config.get 'terminalix.enableConsoleInteractiveLinks'
@find('.console-link').each (
() ->
el = $(this)
link_target = el.data('target')
if link_target != null && link_target != undefined
el.data('target', null)
link_type = el.data('targettype')
link_target_name = el.data('targetname')
link_target_line = el.data('line')
link_target_column = el.data('column')
if not link_target_line?
link_target_line = 0
if not link_target_column?
link_target_column = 0
el.click () ->
el.addClass('link-used')
if link_type == 'file'
atom.workspace.open link_target, {
initialLine: link_target_line
initialColumn: link_target_column
}
if link_type == 'directory'
moveToDir = (directory, messageDisp=false)->
caller.clear()
caller.cd([directory])
setTimeout () ->
if not caller.ls()
if not messageDisp
caller.errorMessage 'The directory is inaccesible.\n'
messageDisp = true
setTimeout () ->
moveToDir('..', messageDisp)
, 1500
, caller._cmdintdel
setTimeout () ->
moveToDir(link_target_name)
, caller._cmdintdel
)
# el.data('filenameLink', '')
consoleAlert: (text) ->
return '<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button><strong>Warning!</strong> ' + text + '</div>'
consolePanel: (title, content) ->
return '<div class="panel panel-info welcome-panel"><div class="panel-heading">'+title+'</div><div class="panel-body">'+content+'</div></div><br><br>'
consoleText: (type, text) ->
if type == 'info'
return '<span class="text-info" style="margin-left:10px;">'+text+'</span>'
if type == 'error'
return '<span class="text-error" style="margin-left:10px;">'+text+'</span>'
if type == 'warning'
return '<span class="text-warning" style="margin-left:10px;">'+text+'</span>'
if type == 'success'
return '<span class="text-success" style="margin-left:10px;">'+text+'</span>'
return text
consoleLabel: (type, text) ->
if (not atom.config.get 'terminalix.enableConsoleLabels') and (not @specsMode)
return text
if not text?
text = type
if type == 'badge'
return '<span class="badge">'+text+'</span>'
if type == 'default'
return '<span class="inline-block highlight">'+text+'</span>'
if type == 'primary'
return '<span class="label label-primary">'+text+'</span>'
if type == 'success'
return '<span class="inline-block highlight-success">'+text+'</span>'
if type == 'info'
return '<span class="inline-block highlight-info">'+text+'</span>'
if type == 'warning'
return '<span class="inline-block highlight-warning">'+text+'</span>'
if type == 'danger'
return '<span class="inline-block highlight-error">'+text+'</span>'
if type == 'error'
return '<span class="inline-block highlight-error">'+text+'</span>'
return '<span class="label label-default">'+text+'</span>'
consoleLink: (name, forced=true) ->
if (atom.config.get 'terminalix.XExperimentEnableForceLinking') and (not forced)
return name
return @_fileInfoHtml(name, @getCwd(), 'font', false)[0]
_fileInfoHtml: (filename, parent, wrapper_class='span', use_file_info_class='true') ->
str = filename
name_tokens = filename
filename = filename.replace /:[0-9]+:[0-9]/ig, ''
name_tokens = @util.replaceAll filename, '', name_tokens
name_tokens = name_tokens.split ':'
fileline = name_tokens[0]
filecolumn = name_tokens[1]
filename = @util.replaceAll '/', '\\', filename
filename = @util.replaceAll parent, '', filename
filename = @util.replaceAll (@util.replaceAll '/', '\\', parent), '', filename
if filename[0] == '\\' or filename[0] == '/'
filename = filename.substring(1)
if filename == '..'
if use_file_info_class
return ["<font class=\"file-extension\"><#{wrapper_class} data-targetname=\"#{filename}\" data-targettype=\"directory\" data-target=\"#{filename}\" class=\"console-link icon-file-directory parent-folder\">#{filename}</#{wrapper_class}></font>", null, filename]
else
return ["<font class=\"file-extension\"><#{wrapper_class} data-targetname=\"#{filename}\" data-targettype=\"directory\" data-target=\"#{filename}\" class=\"console-link icon-file-directory file-info parent-folder\">#{filename}</#{wrapper_class}></font>", null, filename]
file_exists = true
filepath = @resolvePath filename
classes = []
dataname = ''
if atom.config.get('terminalix.useAtomIcons')
classes.push 'name'
classes.push 'icon'
dataname = filepath
else
classes.push 'name'
if use_file_info_class
classes.push 'file-info'
stat = null
if file_exists
try
stat = fs.lstatSync filepath
catch e
file_exists = false
if file_exists
if atom.config.get('terminalix.enableConsoleInteractiveLinks') or @specsMode
classes.push 'console-link'
if stat.isSymbolicLink()
classes.push 'stat-link'
stat = fs.statSync filepath
target_type = 'null'
if stat.isFile()
if stat.mode & 73 #0111
classes.push 'stat-program'
# TODO:10 check extension
matcher = /(.:)((.*)\\)*((.*\.)*)/ig
extension = filepath.replace matcher, ""
classes.push @util.replaceAll(' ', '', extension)
classes.push 'icon-file-text'
target_type = 'file'
if stat.isDirectory()
classes.push 'icon-file-directory'
target_type = 'directory'
if stat.isCharacterDevice()
classes.push 'stat-char-dev'
target_type = 'device'
if stat.isFIFO()
classes.push 'stat-fifo'
target_type = 'fifo'
if stat.isSocket()
classes.push 'stat-sock'
target_type = 'sock'
else
classes.push 'file-not-found'
classes.push 'icon-file-text'
target_type = 'file'
if filename[0] == '.'
classes.push 'status-ignored'
target_type = 'ignored'
href = 'file:///' + @util.replaceAll('\\', '/', filepath)
classes.push 'atp-tooltip'
exattrs = []
if fileline?
exattrs.push 'data-line="'+fileline+'"'
if filecolumn?
exattrs.push 'data-column="'+filecolumn+'"'
filepath_tooltip = @util.replaceAll '\\', '/', filepath
filepath = @util.replaceAll '\\', '/', filepath
["<font class=\"file-extension\"><#{wrapper_class} #{exattrs.join ' '} tooltip=\"\" data-targetname=\"#{filename}\" data-targettype=\"#{target_type}\" data-target=\"#{filepath}\" data-name=\"#{dataname}\" class=\"#{classes.join ' '}\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"#{filepath_tooltip}\" >#{filename}</#{wrapper_class}></font>", stat, filename]
getGitStatusName: (path, gitRoot, repo) ->
status = (repo.getCachedPathStatus or repo.getPathStatus)(path)
if status
if repo.isStatusModified status
return 'modified'
if repo.isStatusNew status
return 'added'
if repo.isPathIgnore path
return 'ignored'
preserveOriginalPaths: (text) ->
text = @util.replaceAll @getCurrentFilePath(), '%(file-original)', text
text = @util.replaceAll @getCwd(), '%(cwd-original)', text
text = @util.replaceAll @getCwd(), '%(cwd-original)', text
text = @util.replaceAll '/', '&fs;', text
text = @util.replaceAll '\\', '&bs;', text
return text
parseMessage: (message, matchSpec=true, parseCustomRules=true) ->
instance = this
message = '<div>'+(instance.parseMessage_ message, false, true, true)+'</div>'
n = $(message)
n.contents().filter(() ->
return this.nodeType == 3
).each(() ->
thiz = $(this)
out = thiz.text()
out = instance.parseMessage_ out, matchSpec, parseCustomRules
thiz.replaceWith('<span>'+out+'</span>')
)
return n.html()
parseMessage_: (message, matchSpec=true, parseCustomRules=true, isForcelyPreparsering=false) ->
if message == null
return ''
if matchSpec
if atom.config.get('terminalix.XExperimentEnableForceLinking')
if atom.config.get('terminalix.textReplacementFileAdress')?
if atom.config.get('terminalix.textReplacementFileAdress') != ''
# regex = /(([A-Za-z]:)(\\|\/))?([A-Za-z$\*\-+&#@!_\.]+(\\|\/))([A-Za-z $\*\-+&#@!_\.]+(\\|\/))*[A-Za-z\-_$\*\+&\^@#\. ]+\.[A-Za-z\-_$\*\+]*/ig
# regex = /(([A-Za-z]:)(\\|\/))?(([^\s#@$%&!;<>\.\^:]| )+(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
regex = /(\.(\\|\/))?(([A-Za-z]:)(\\|\/))?(([^\s#@$%&!;<>\.\^:]| )+(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
regex2 = /(\.(\\|\/))((([^\s#@$%&!;<>\.\^:]| )+(\\|\/))*([^\s<>:#@$%\^;]| )+(\.([^\s#@$%&!;<>\.0-9:\^]| )*)*)?/ig
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
message = message.replace regex2, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
else
if atom.config.get('terminalix.textReplacementFileAdress')?
if atom.config.get('terminalix.textReplacementFileAdress') != ''
#regex = /(([A-Za-z]:)(\\|\/))?([A-Za-z$\*\-+&#@!_\.]+(\\|\/))([A-Za-z $\*\-+&#@!_\.]+(\\|\/))*[A-Za-z\-_$\*\+&\^@#\. ]+\.[A-Za-z\-_$\*\+]*/ig
cwdN = @getCwd()
cwdE = @util.replaceAll '/', '\\', @getCwd()
regexString ='(' + (@util.escapeRegExp cwdN) + '|' + (@util.escapeRegExp cwdE) + ')\\\\([^\\s:#$%^&!:]| )+\\.?([^\\s:#$@%&\\*\\^!0-9:\\.+\\-,\\\\\\/\"]| )*'
regex = new RegExp(regexString, 'ig')
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementFileAdress'), {file:match}
if atom.config.get('terminalix.textReplacementCurrentFile')?
if atom.config.get('terminalix.textReplacementCurrentFile') != ''
path = @getCurrentFilePath()
regex = new RegExp @util.escapeRegExp(path), 'g'
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementCurrentFile'), {file:match}
message = @preserveOriginalPaths message
if atom.config.get('terminalix.textReplacementCurrentPath')?
if atom.config.get('terminalix.textReplacementCurrentPath') != ''
path = @getCwd()
regex = new RegExp @util.escapeRegExp(path), 'g'
message = message.replace regex, (match, text, urlId) =>
return @parseSpecialStringTemplate atom.config.get('terminalix.textReplacementCurrentPath'), {file:match}
message = @util.replaceAll '%(file-original)', @getCurrentFilePath(), message
message = @util.replaceAll '%(cwd-original)', @getCwd(), message
message = @util.replaceAll '&fs;', '/', message
message = @util.replaceAll '&bs;', '\\', message
rules = ATPCore.getConfig().rules
for key, value of rules
matchExp = key
replExp = '%(content)'
matchAllLine = false
matchNextLines = 0
flags = 'gm'
forceParse = false
if value.match?
if value.match.flags?
flags = value.match.flags.join ''
if value.match.replace?
replExp = value.match.replace
if value.match.matchLine?
matchAllLine = value.match.matchLine
if value.match.matchNextLines?
matchNextLines = value.match.matchNextLines
if value.match.forced?
forceParse = value.match.forced
if (forceParse or parseCustomRules) and ((isForcelyPreparsering and forceParse) or (not isForcelyPreparsering))
if matchAllLine
matchExp = '.*' + matchExp
if matchNextLines > 0
for i in [0..matchNextLines] by 1
matchExp = matchExp + '[\\r\\n].*'
regex = new RegExp(matchExp, flags)
message = message.replace regex, (match, groups...) =>
style = ''
if value.css?
style = ATPCore.jsonCssToInlineStyle value.css
else if not value.match?
style = ATPCore.jsonCssToInlineStyle value
vars =
content: match
0: match
groupsNumber = groups.length-1
for i in [0..groupsNumber] by 1
if groups[i]?
vars[i+1] = groups[i]
# console.log 'Active rule => '+matchExp
repl = @parseSpecialStringTemplate replExp, vars
return "<font style=\"#{style}\">#{repl}</font>"
message = @util.replaceAll '%(file-original)', @getCurrentFilePath(), message
message = @util.replaceAll '%(cwd-original)', @getCwd(), message
message = @util.replaceAll '&fs;', '/', message
message = @util.replaceAll '&bs;', '\\', message
return message
redirect: (streamName) ->
@redirectOutput = streamName
rawMessage: (message) ->
if @redirectOutput == 'console'
console.log message
return
@cliOutput.append message
@showCmd()
# @parseSpecialNodes()
message: (message, matchSpec=true) ->
if @redirectOutput == 'console'
console.log message
return
if typeof message is 'object'
mes = message
else
if not message?
return
mes = message.split '%(break)'
if mes.length > 1
for m in mes
@message m
return
else
mes = mes[0]
mes = @parseMessage message, matchSpec, matchSpec
mes = @util.replaceAll '%(raw)', '', mes
mes = @parseTemplate mes, [], true
# mes = @util.replaceAll '<', '<', mes
# mes = @util.replaceAll '>', '>', mes
@cliOutput.append mes
@showCmd()
@parseSpecialNodes()
@scrollToBottom()
# @putInputBox()
errorMessage: (message) ->
@cliOutput.append @parseMessage(message)
@clearStatusIcon()
@statusIcon.addClass 'status-error'
@parseSpecialNodes()
correctFilePath: (path) ->
return @util.replaceAll '\\', '/', path
getCwd: ->
if not atom.project?
return null
extFile = extname atom.project.getPaths()[0]
if extFile == ""
if atom.project.getPaths()[0]
projectDir = atom.project.getPaths()[0]
else
if process.env.HOME
projectDir = process.env.HOME
else if process.env.USERPROFILE
projectDir = process.env.USERPROFILE
else
projectDir = '/'
else
projectDir = dirname atom.project.getPaths()[0]
cwd = @cwd or projectDir or @userHome
return @correctFilePath cwd
spawn: (inputCmd, cmd, args) =>
## @cmdEditor.hide()
## htmlStream = ansihtml()
# htmlStream = iconv.decodeStream @streamsEncoding
# htmlStream.on 'data', (data) =>
## @cliOutput.append data
# @message data
# @scrollToBottom()
# try
## @program = spawn cmd, args, stdio: 'pipe', env: process.env, cwd: @getCwd()
# @program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd()
## @program.stdin.pipe htmlStream
# @program.stdout.pipe htmlStream
# @program.stderr.pipe htmlStream
## @program.stdout.setEncoding @streamsEncoding
@spawnProcessActive = true
instance = this
dataCallback = (data) ->
instance.message(data)
instance.scrollToBottom()
processCallback = (error, stdout, stderr) ->
console.log 'callback' if atom.config.get('terminalix.logConsole') or @specsMode
console.log(error, stdout, stderr)
instance.putInputBox()
instance.showCmd()
htmlStream = ansihtml()
htmlStream = iconv.decodeStream @streamsEncoding
htmlStream.on 'data', dataCallback
try
if @configFileFtp
@program = process
@programSSH = execSSH('echo dada', {
user: 'admin123'
host: 'vps123.ovh.net'
passphrase: 'PI:PASSWORD:<PASSWORD>END_PI'
key: 'c:/PI:KEY:<KEY>END_PIuserPI:KEY:<KEY>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
timeout: 10000
}, processCallback)
console.log(@programSSH)
@programSSH.pipe @program.stdout
@program.stdin.pipe htmlStream
#(@program.stdin.pipe iconv.encodeStream 'base64').pipe htmlStream
#@program = execSSH inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
else
@program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
@program.stdout.setEncoding 'base64'
console.log @program if atom.config.get('terminalix.logConsole') or @specsMode
(@program.stdout.pipe iconv.encodeStream 'base64').pipe htmlStream
@clearStatusIcon()
@statusIcon.addClass 'status-running'
@killBtn.removeClass 'hide'
@program.on 'exit', (code, signal) =>
console.log 'exit', code, signal if atom.config.get('terminalix.logConsole') or @specsMode
@killBtn.addClass 'hide'
@statusIcon.removeClass 'status-running'
if code == 0
@statusIcon.addClass 'status-success'
else if code?
@statusIcon.addClass 'status-error'
if code == 127
@message (@consoleLabel 'error', 'Error')+(@consoleText 'error', cmd + ': command not found')
@message '\n'
@program = null
@spawnProcessActive = false
@program.on 'error', (err) =>
console.log 'error' if atom.config.get('terminalix.logConsole') or @specsMode
@message (err.message)
@message '\n'
@putInputBox()
@showCmd()
@statusIcon.addClass 'status-error'
@program.stdout.on 'data', (data) =>
@flashIconClass 'status-info'
@statusIcon.removeClass 'status-error'
@program.stderr.on 'data', (data) =>
console.log 'stderr' if atom.config.get('terminalix.logConsole') or @specsMode
@message data
@flashIconClass 'status-error', 300
#DOING:20 x 2017-08-09 This task was created on 2017-08-09 and complited 2017-08-23
catch err
console.log 'Failed to launch process' if atom.config.get('terminalix.logConsole') or @specsMode
# IDEA: test it
@message ('haha '+err.message)
#DOING:21 This task is due on 2017-08-24 due:2017-08-24
@showCmd()
spawnR: (inputCmd, cmd, args) =>
@spawnRProcessActive = true
instance = this
dataCallback = (data) ->
instance.message(data)
instance.scrollToBottom()
processCallback = (error, stdout, stderr) ->
console.log 'callback' if atom.config.get('terminalix.logConsole') or @specsMode
console.log(error, stdout, stderr)
instance.putInputBox()
instance.showCmd()
htmlStream = ansihtml()
htmlStream = iconv.decodeStream @streamsEncoding
htmlStream.on 'data', dataCallback
sshCallback = (err, ssh) =>
console.log 'ssh'
console.log ssh
console.log err
try
if err
@program = new EventEmitter()
@program.emit('error',err)
processCallback(err,null,null)
else
@program = execR {cmd: 'ls -lah', ssh: ssh}, (err, stdout, stderr) ->
console.log ssh
console.log 'err:'
console.log err
console.log stderr
console.log stdout
#@program = exec inputCmd, stdio: 'pipe', env: process.env, cwd: @getCwd(), processCallback
@program.stdout.setEncoding 'base64'
console.log @program if atom.config.get('terminalix.logConsole') or @specsMode
(@program.stdout.pipe iconv.encodeStream 'base64').pipe htmlStream
@clearStatusIcon()
@statusIcon.addClass 'status-running'
@killBtn.removeClass 'hide'
@program.on 'exit', (code, signal) =>
console.log 'exit', code, signal if atom.config.get('terminalix.logConsole') or @specsMode
@killBtn.addClass 'hide'
@statusIcon.removeClass 'status-running'
if code == 0
@statusIcon.addClass 'status-success'
else if code?
@statusIcon.addClass 'status-error'
if code == 127
@message (@consoleLabel 'error', 'Error')+(@consoleText 'error', cmd + ': command not found')
@message '\n'
@program = null
@spawnRProcessActive = false
@program.on 'error', (err) =>
console.log 'error' if atom.config.get('terminalix.logConsole') or @specsMode
@message (err.message)
@message '\n'
@putInputBox()
@showCmd()
@statusIcon.addClass 'status-error'
@flashIconClass 'status-error', 300
@program.stdout.on 'data', (data) =>
@flashIconClass 'status-info'
@statusIcon.removeClass 'status-error'
@program.stderr.on 'data', (data) =>
console.log 'stderr' if atom.config.get('terminalix.logConsole') or @specsMode
@message data
@flashIconClass 'status-error', 300
#DOING:20 x 2017-08-09 This task was created on 2017-08-09 and complited 2017-08-23
catch err1
console.log 'Failed to launch process' if atom.config.get('terminalix.logConsole') or @specsMode
console.log err1
# IDEA: test it
@message err1.message
#DOING:21 This task is due on 2017-08-24 due:2017-08-24
@showCmd()
try
connect {
user: 'admin123'
host: 'vps123.ovh.net'
#passphrase: 'PI:PASSWORD:<PASSWORD>END_PI'
#key: 'c:/users/user1/.ssh/id_rsa'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
timeout: 10000
}, sshCallback
catch err2
console.log err2
# coffeeli1111nt: enable=*
# coffeelint: enable=max_line_length
|
[
{
"context": "\",\n# # region: s3.region\n# accessKeyId: s3.accessKeyId\n# secretAccessKey: s3.secretAccess",
"end": 441,
"score": 0.522564172744751,
"start": 441,
"tag": "KEY",
"value": ""
},
{
"context": "accessKeyId: s3.accessKeyId\n# secretAccessKey: s3.secretAccessKey\n# bucket: s3.bucket\n# ACL: s3.ACL\n# f",
"end": 495,
"score": 0.9060622453689575,
"start": 477,
"tag": "KEY",
"value": "s3.secretAccessKey"
}
] | _source/lib/collections/images.coffee | jbaxleyiii/dapperink | 0 |
# if Meteor.isClient
#
# Apollos.ImageStore = new FS.Store.S3 "images"
#
# Apollos.Images = new FS.Collection "images",
# stores: [Apollos.ImageStore]
#
# # should I move this to a template level subscribe?
# Meteor.subscribe "images"
#
#
# if Meteor.isServer and Meteor.settings.s3Config
# s3 = Meteor.settings.s3Config
#
#
# Apollos.ImageStore = new (FS.Store.S3)("images",
# # region: s3.region
# accessKeyId: s3.accessKeyId
# secretAccessKey: s3.secretAccessKey
# bucket: s3.bucket
# ACL: s3.ACL
# folder: "uploads/"
# )
#
# Apollos.Images = new FS.Collection("images",
# stores:
# [
# Apollos.ImageStore
# ]
# )
#
# Meteor.publish "images", ->
#
# Apollos.Images.find()
#
#
# Apollos.Images.allow
# insert: (user, file) ->
# # Anyone can insert
# true
# remove: (user, file) ->
# return file.metadata and file.metadata.user and file.metadata.user is user
# update: ->
# # Anyone can post
# true
# download: ->
# true
| 209333 |
# if Meteor.isClient
#
# Apollos.ImageStore = new FS.Store.S3 "images"
#
# Apollos.Images = new FS.Collection "images",
# stores: [Apollos.ImageStore]
#
# # should I move this to a template level subscribe?
# Meteor.subscribe "images"
#
#
# if Meteor.isServer and Meteor.settings.s3Config
# s3 = Meteor.settings.s3Config
#
#
# Apollos.ImageStore = new (FS.Store.S3)("images",
# # region: s3.region
# accessKeyId: s3<KEY>.accessKeyId
# secretAccessKey: <KEY>
# bucket: s3.bucket
# ACL: s3.ACL
# folder: "uploads/"
# )
#
# Apollos.Images = new FS.Collection("images",
# stores:
# [
# Apollos.ImageStore
# ]
# )
#
# Meteor.publish "images", ->
#
# Apollos.Images.find()
#
#
# Apollos.Images.allow
# insert: (user, file) ->
# # Anyone can insert
# true
# remove: (user, file) ->
# return file.metadata and file.metadata.user and file.metadata.user is user
# update: ->
# # Anyone can post
# true
# download: ->
# true
| true |
# if Meteor.isClient
#
# Apollos.ImageStore = new FS.Store.S3 "images"
#
# Apollos.Images = new FS.Collection "images",
# stores: [Apollos.ImageStore]
#
# # should I move this to a template level subscribe?
# Meteor.subscribe "images"
#
#
# if Meteor.isServer and Meteor.settings.s3Config
# s3 = Meteor.settings.s3Config
#
#
# Apollos.ImageStore = new (FS.Store.S3)("images",
# # region: s3.region
# accessKeyId: s3PI:KEY:<KEY>END_PI.accessKeyId
# secretAccessKey: PI:KEY:<KEY>END_PI
# bucket: s3.bucket
# ACL: s3.ACL
# folder: "uploads/"
# )
#
# Apollos.Images = new FS.Collection("images",
# stores:
# [
# Apollos.ImageStore
# ]
# )
#
# Meteor.publish "images", ->
#
# Apollos.Images.find()
#
#
# Apollos.Images.allow
# insert: (user, file) ->
# # Anyone can insert
# true
# remove: (user, file) ->
# return file.metadata and file.metadata.user and file.metadata.user is user
# update: ->
# # Anyone can post
# true
# download: ->
# true
|
[
{
"context": "use of variables before they are defined\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------",
"end": 97,
"score": 0.999799907207489,
"start": 85,
"tag": "NAME",
"value": "Ilya Volodin"
}
] | src/rules/no-use-before-define.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to flag use of variables before they are defined
# @author Ilya Volodin
###
'use strict'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
SENTINEL_TYPE =
/^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration|For)$/
FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/
###*
# Parses a given value as options.
#
# @param {any} options - A value to parse.
# @returns {Object} The parsed options.
###
parseOptions = (options) ->
functions = yes
classes = yes
variables = yes
if typeof options is 'string'
functions = options isnt 'nofunc'
else if typeof options is 'object' and options isnt null
functions = options.functions isnt no
classes = options.classes isnt no
variables = options.variables isnt no
{functions, classes, variables}
###*
# Checks whether or not a given variable is a function declaration.
#
# @param {eslint-scope.Variable} variable - A variable to check.
# @returns {boolean} `true` if the variable is a function declaration.
###
isFunction = (variable, reference) ->
{name} = variable.defs[0]
return no unless (
name.parent.type is 'AssignmentExpression' and
name.parent.right.type is 'FunctionExpression'
)
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given variable is a class declaration in an upper function scope.
#
# @param {eslint-scope.Variable} variable - A variable to check.
# @param {eslint-scope.Reference} reference - A reference to check.
# @returns {boolean} `true` if the variable is a class declaration.
###
isOuterClass = (variable, reference) ->
variable.defs[0].type is 'ClassName' and
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given variable is a variable declaration in an upper function scope.
# @param {eslint-scope.Variable} variable - A variable to check.
# @param {eslint-scope.Reference} reference - A reference to check.
# @returns {boolean} `true` if the variable is a variable declaration.
###
isOuterVariable = (variable, reference) ->
variable.defs[0].type is 'Variable' and
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given location is inside of the range of a given node.
#
# @param {ASTNode} node - An node to check.
# @param {number} location - A location to check.
# @returns {boolean} `true` if the location is inside of the range of the node.
###
isInRange = (node, location) ->
node and node.range[0] <= location and location <= node.range[1]
###*
# Checks whether or not a given reference is inside of the initializers of a given variable.
#
# This returns `true` in the following cases:
#
# var a = a
# var [a = a] = list
# var {a = a} = obj
# for (var a in a) {}
# for (var a of a) {}
#
# @param {Variable} variable - A variable to check.
# @param {Reference} reference - A reference to check.
# @returns {boolean} `true` if the reference is inside of the initializers.
###
isInInitializer = (variable, reference) ->
return no unless variable.scope is reference.from
node = variable.identifiers[0].parent
location = reference.identifier.range[1]
while node
if node.type is 'AssignmentExpression'
return yes if isInRange node.right, location
return yes if (
FOR_IN_OF_TYPE.test(node.parent.parent.type) and
isInRange node.parent.parent.right, location
)
break
else if node.type is 'AssignmentPattern'
return yes if isInRange node.right, location
else if SENTINEL_TYPE.test node.type
break
node = node.parent
no
isInPostfixBody = (variable, reference) ->
node = variable.identifiers[0].parent
location = reference.identifier.range[1]
while node
if node.postfix
return isInRange node.consequent ? node.body, location
node = node.parent
no
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow the use of variables before they are defined'
category: 'Variables'
recommended: no
url: 'https://eslint.org/docs/rules/no-use-before-define'
schema: [
oneOf: [
enum: ['nofunc']
,
type: 'object'
properties:
functions: type: 'boolean'
classes: type: 'boolean'
variables: type: 'boolean'
additionalProperties: no
]
]
create: (context) ->
options = parseOptions context.options[0]
###*
# Determines whether a given use-before-define case should be reported according to the options.
# @param {eslint-scope.Variable} variable The variable that gets used before being defined
# @param {eslint-scope.Reference} reference The reference to the variable
# @returns {boolean} `true` if the usage should be reported
###
isForbidden = (variable, reference) ->
return options.functions if isFunction variable, reference
return options.classes if isOuterClass variable, reference
return options.variables if isOuterVariable variable, reference
yes
###*
# Finds and validates all variables in a given scope.
# @param {Scope} scope The scope object.
# @returns {void}
# @private
###
findVariablesInScope = (scope) ->
scope.references.forEach (reference) ->
variable = reference.resolved
###
# Skips when the reference is:
# - initialization's.
# - referring to an undefined variable.
# - referring to a global environment variable (there're no identifiers).
# - located preceded by the variable (except in initializers).
# - allowed by options.
###
return if (
reference.init or
reference.identifier?.declaration or
not variable or
variable.identifiers.length is 0 or
(variable.identifiers[0].range[1] < reference.identifier.range[1] and
not isInInitializer(variable, reference)) or
not isForbidden variable, reference
)
return if isInPostfixBody variable, reference
# Reports.
context.report
node: reference.identifier
message: "'{{name}}' was used before it was defined."
data: reference.identifier
scope.childScopes.forEach findVariablesInScope
Program: -> findVariablesInScope context.getScope()
| 35133 | ###*
# @fileoverview Rule to flag use of variables before they are defined
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
SENTINEL_TYPE =
/^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration|For)$/
FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/
###*
# Parses a given value as options.
#
# @param {any} options - A value to parse.
# @returns {Object} The parsed options.
###
parseOptions = (options) ->
functions = yes
classes = yes
variables = yes
if typeof options is 'string'
functions = options isnt 'nofunc'
else if typeof options is 'object' and options isnt null
functions = options.functions isnt no
classes = options.classes isnt no
variables = options.variables isnt no
{functions, classes, variables}
###*
# Checks whether or not a given variable is a function declaration.
#
# @param {eslint-scope.Variable} variable - A variable to check.
# @returns {boolean} `true` if the variable is a function declaration.
###
isFunction = (variable, reference) ->
{name} = variable.defs[0]
return no unless (
name.parent.type is 'AssignmentExpression' and
name.parent.right.type is 'FunctionExpression'
)
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given variable is a class declaration in an upper function scope.
#
# @param {eslint-scope.Variable} variable - A variable to check.
# @param {eslint-scope.Reference} reference - A reference to check.
# @returns {boolean} `true` if the variable is a class declaration.
###
isOuterClass = (variable, reference) ->
variable.defs[0].type is 'ClassName' and
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given variable is a variable declaration in an upper function scope.
# @param {eslint-scope.Variable} variable - A variable to check.
# @param {eslint-scope.Reference} reference - A reference to check.
# @returns {boolean} `true` if the variable is a variable declaration.
###
isOuterVariable = (variable, reference) ->
variable.defs[0].type is 'Variable' and
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given location is inside of the range of a given node.
#
# @param {ASTNode} node - An node to check.
# @param {number} location - A location to check.
# @returns {boolean} `true` if the location is inside of the range of the node.
###
isInRange = (node, location) ->
node and node.range[0] <= location and location <= node.range[1]
###*
# Checks whether or not a given reference is inside of the initializers of a given variable.
#
# This returns `true` in the following cases:
#
# var a = a
# var [a = a] = list
# var {a = a} = obj
# for (var a in a) {}
# for (var a of a) {}
#
# @param {Variable} variable - A variable to check.
# @param {Reference} reference - A reference to check.
# @returns {boolean} `true` if the reference is inside of the initializers.
###
isInInitializer = (variable, reference) ->
return no unless variable.scope is reference.from
node = variable.identifiers[0].parent
location = reference.identifier.range[1]
while node
if node.type is 'AssignmentExpression'
return yes if isInRange node.right, location
return yes if (
FOR_IN_OF_TYPE.test(node.parent.parent.type) and
isInRange node.parent.parent.right, location
)
break
else if node.type is 'AssignmentPattern'
return yes if isInRange node.right, location
else if SENTINEL_TYPE.test node.type
break
node = node.parent
no
isInPostfixBody = (variable, reference) ->
node = variable.identifiers[0].parent
location = reference.identifier.range[1]
while node
if node.postfix
return isInRange node.consequent ? node.body, location
node = node.parent
no
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow the use of variables before they are defined'
category: 'Variables'
recommended: no
url: 'https://eslint.org/docs/rules/no-use-before-define'
schema: [
oneOf: [
enum: ['nofunc']
,
type: 'object'
properties:
functions: type: 'boolean'
classes: type: 'boolean'
variables: type: 'boolean'
additionalProperties: no
]
]
create: (context) ->
options = parseOptions context.options[0]
###*
# Determines whether a given use-before-define case should be reported according to the options.
# @param {eslint-scope.Variable} variable The variable that gets used before being defined
# @param {eslint-scope.Reference} reference The reference to the variable
# @returns {boolean} `true` if the usage should be reported
###
isForbidden = (variable, reference) ->
return options.functions if isFunction variable, reference
return options.classes if isOuterClass variable, reference
return options.variables if isOuterVariable variable, reference
yes
###*
# Finds and validates all variables in a given scope.
# @param {Scope} scope The scope object.
# @returns {void}
# @private
###
findVariablesInScope = (scope) ->
scope.references.forEach (reference) ->
variable = reference.resolved
###
# Skips when the reference is:
# - initialization's.
# - referring to an undefined variable.
# - referring to a global environment variable (there're no identifiers).
# - located preceded by the variable (except in initializers).
# - allowed by options.
###
return if (
reference.init or
reference.identifier?.declaration or
not variable or
variable.identifiers.length is 0 or
(variable.identifiers[0].range[1] < reference.identifier.range[1] and
not isInInitializer(variable, reference)) or
not isForbidden variable, reference
)
return if isInPostfixBody variable, reference
# Reports.
context.report
node: reference.identifier
message: "'{{name}}' was used before it was defined."
data: reference.identifier
scope.childScopes.forEach findVariablesInScope
Program: -> findVariablesInScope context.getScope()
| true | ###*
# @fileoverview Rule to flag use of variables before they are defined
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Helpers
#------------------------------------------------------------------------------
SENTINEL_TYPE =
/^(?:(?:Function|Class)(?:Declaration|Expression)|ArrowFunctionExpression|CatchClause|ImportDeclaration|ExportNamedDeclaration|For)$/
FOR_IN_OF_TYPE = /^For(?:In|Of)Statement$/
###*
# Parses a given value as options.
#
# @param {any} options - A value to parse.
# @returns {Object} The parsed options.
###
parseOptions = (options) ->
functions = yes
classes = yes
variables = yes
if typeof options is 'string'
functions = options isnt 'nofunc'
else if typeof options is 'object' and options isnt null
functions = options.functions isnt no
classes = options.classes isnt no
variables = options.variables isnt no
{functions, classes, variables}
###*
# Checks whether or not a given variable is a function declaration.
#
# @param {eslint-scope.Variable} variable - A variable to check.
# @returns {boolean} `true` if the variable is a function declaration.
###
isFunction = (variable, reference) ->
{name} = variable.defs[0]
return no unless (
name.parent.type is 'AssignmentExpression' and
name.parent.right.type is 'FunctionExpression'
)
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given variable is a class declaration in an upper function scope.
#
# @param {eslint-scope.Variable} variable - A variable to check.
# @param {eslint-scope.Reference} reference - A reference to check.
# @returns {boolean} `true` if the variable is a class declaration.
###
isOuterClass = (variable, reference) ->
variable.defs[0].type is 'ClassName' and
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given variable is a variable declaration in an upper function scope.
# @param {eslint-scope.Variable} variable - A variable to check.
# @param {eslint-scope.Reference} reference - A reference to check.
# @returns {boolean} `true` if the variable is a variable declaration.
###
isOuterVariable = (variable, reference) ->
variable.defs[0].type is 'Variable' and
variable.scope.variableScope isnt reference.from.variableScope
###*
# Checks whether or not a given location is inside of the range of a given node.
#
# @param {ASTNode} node - An node to check.
# @param {number} location - A location to check.
# @returns {boolean} `true` if the location is inside of the range of the node.
###
isInRange = (node, location) ->
node and node.range[0] <= location and location <= node.range[1]
###*
# Checks whether or not a given reference is inside of the initializers of a given variable.
#
# This returns `true` in the following cases:
#
# var a = a
# var [a = a] = list
# var {a = a} = obj
# for (var a in a) {}
# for (var a of a) {}
#
# @param {Variable} variable - A variable to check.
# @param {Reference} reference - A reference to check.
# @returns {boolean} `true` if the reference is inside of the initializers.
###
isInInitializer = (variable, reference) ->
return no unless variable.scope is reference.from
node = variable.identifiers[0].parent
location = reference.identifier.range[1]
while node
if node.type is 'AssignmentExpression'
return yes if isInRange node.right, location
return yes if (
FOR_IN_OF_TYPE.test(node.parent.parent.type) and
isInRange node.parent.parent.right, location
)
break
else if node.type is 'AssignmentPattern'
return yes if isInRange node.right, location
else if SENTINEL_TYPE.test node.type
break
node = node.parent
no
isInPostfixBody = (variable, reference) ->
node = variable.identifiers[0].parent
location = reference.identifier.range[1]
while node
if node.postfix
return isInRange node.consequent ? node.body, location
node = node.parent
no
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
module.exports =
meta:
docs:
description: 'disallow the use of variables before they are defined'
category: 'Variables'
recommended: no
url: 'https://eslint.org/docs/rules/no-use-before-define'
schema: [
oneOf: [
enum: ['nofunc']
,
type: 'object'
properties:
functions: type: 'boolean'
classes: type: 'boolean'
variables: type: 'boolean'
additionalProperties: no
]
]
create: (context) ->
options = parseOptions context.options[0]
###*
# Determines whether a given use-before-define case should be reported according to the options.
# @param {eslint-scope.Variable} variable The variable that gets used before being defined
# @param {eslint-scope.Reference} reference The reference to the variable
# @returns {boolean} `true` if the usage should be reported
###
isForbidden = (variable, reference) ->
return options.functions if isFunction variable, reference
return options.classes if isOuterClass variable, reference
return options.variables if isOuterVariable variable, reference
yes
###*
# Finds and validates all variables in a given scope.
# @param {Scope} scope The scope object.
# @returns {void}
# @private
###
findVariablesInScope = (scope) ->
scope.references.forEach (reference) ->
variable = reference.resolved
###
# Skips when the reference is:
# - initialization's.
# - referring to an undefined variable.
# - referring to a global environment variable (there're no identifiers).
# - located preceded by the variable (except in initializers).
# - allowed by options.
###
return if (
reference.init or
reference.identifier?.declaration or
not variable or
variable.identifiers.length is 0 or
(variable.identifiers[0].range[1] < reference.identifier.range[1] and
not isInInitializer(variable, reference)) or
not isForbidden variable, reference
)
return if isInPostfixBody variable, reference
# Reports.
context.report
node: reference.identifier
message: "'{{name}}' was used before it was defined."
data: reference.identifier
scope.childScopes.forEach findVariablesInScope
Program: -> findVariablesInScope context.getScope()
|
[
{
"context": "https://happening.im/x/' + group.key()\n\t\t\t\tdata: '64foNwpEfn3LQrTQC2q5NijPqG92Nv2xYi65gFz6uTJjPJS2stN7MbyNygtvKvNS'\n\t\t\t\tname: 'historyResult'\n\t\tcurrent++\n\tcurrentRe",
"end": 2455,
"score": 0.9994450211524963,
"start": 2391,
"tag": "KEY",
"value": "64foNwpEfn3LQrTQC2q5NijPqG92Nv2xYi65gFz6uTJjPJS2stN7MbyNygtvKvNS"
}
] | server.coffee | LarsStegeman/ConquestDataCollection | 0 | Db = require 'db'
Http = require 'http'
Timer = require 'timer'
Config = {
updateCompletionDelay: 500 # milliseconds between updating the doneCount for the client while gathering data
gatheringTimeout: 120*1000 # timeout of the gathering (time after receiving last result) non-updated plugins will be marked as inactive after this
gatherRequestsPerSecond: 100 # how many HTTP data gather requests will be send each second
startTimestamp: 1434405600.0 # Timestamp which is used as day 0 for the statistics
}
eventsPerDay = {}
groupsPerGroupSize = {}
# Upgrade of the plugin
exports.onUpgrade = ->
log '[onUpgrade()] at '+new Date()
Db.shared.set 'lastDeploy', new Date()+''
# Call from Conquest plugin for registering itself to this Data plugin
exports.onHttp = (request) ->
# special entrypoint for the Http API: called whenever a request is made to our plugin's inbound URL
log '[onHTTP()] Plugin ' + request.data + ' registered'
Db.backend.set 'pluginInfo', request.data, {'updateNumber': 0, 'active': 'true', 'upToDate': 'true'}
request.respond 200, 'Registered successfully'
updateNumberOfPlugins()
return 0
# Client call to update databases
exports.client_gatherHistory = ->
log '[gatherHistory()] Starting to request'
Timer.cancel 'gatheringTimeout', {}
Timer.cancel 'updateCompletion', {}
Db.shared.set 'doneCount', 0
Db.shared.set 'lastDoneCount', 0
Db.shared.set 'updating', 'true'
Db.shared.set "doneSendingRequests", 'no'
Db.backend.set 'pluginInfoCopy', Db.backend.peek('pluginInfo')
currentRequest = 0
Db.backend.iterate 'pluginInfo' , (group) !->
if group.peek('active') == 'true'
Db.backend.set 'pluginInfoCopy', group.key(), Db.backend.peek('pluginInfo', group.key())
Db.backend.set 'pluginInfoCopy', group.key(), 'upToDate', 'false'
currentRequest++
Db.shared.set 'currentRequest', currentRequest
Timer.set 0, 'doGatherStep', {}
Timer.set Config.gatheringTimeout, 'gatheringTimeout', {}
Timer.set Config.updateCompletionDelay, 'updateCompletion', {}
return 0
exports.doGatherStep = (args) ->
current = 0
currentRequest = Db.shared.peek('currentRequest')
Db.backend.iterate 'pluginInfoCopy' , (group) !->
if current >= currentRequest and current < (currentRequest+Config.gatherRequestsPerSecond)
log ' Requesting from: '+group.key()
Http.post
url: 'https://happening.im/x/' + group.key()
data: '64foNwpEfn3LQrTQC2q5NijPqG92Nv2xYi65gFz6uTJjPJS2stN7MbyNygtvKvNS'
name: 'historyResult'
current++
currentRequest = currentRequest-Config.gatherRequestsPerSecond
Db.shared.set 'currentRequest', currentRequest
if currentRequest > 0
Timer.set 1000, 'doGatherStep', {}
else
Db.shared.set "doneSendingRequests", 'yes'
log '[doGatherStep()] Done sending requests'
return 0
# Client call for updating statistics
exports.client_updateStatistics = ->
recalculateStatistics()
# Update the donecount to be shown to the client, finishes the gathering if done
exports.updateCompletion = (args) ->
done = true
doneCount = 0
Db.backend.iterate 'pluginInfoCopy', (group) !->
if Db.backend.peek('pluginInfoCopy', group.key(), 'upToDate') is 'false'
done = false
else
doneCount++
Db.shared.set 'doneCount', doneCount
if done
finishGathering()
else
if Db.shared.peek('lastDoneCount') != doneCount
Timer.cancel 'gatheringTimeout', {}
Timer.set Config.gatheringTimeout, 'gatheringTimeout', {}
Timer.set Config.updateCompletionDelay, 'updateCompletion', {}
Db.shared.set 'lastDoneCount', doneCount
# End the gathring, trigger statistics update
finishGathering = ->
Timer.cancel 'gatheringTimeout', {}
Timer.cancel 'updateCompletion', {}
Db.shared.set('latestUpdate', new Date()/1000)
Db.shared.set 'updating', 'false'
Db.backend.remove 'pluginInfoCopy'
recalculateStatistics()
exports.historyResult = (data) !->
if data? and data isnt ''
if data.indexOf("<html><head><title>404 no such group app</title></head>") <= -1
result = JSON.parse(data)
if result?
log '[historyResult()] Recieved history from plugin: code='+result.groupCode
if result.groupCode? and result.groupCode isnt ''
Db.backend.remove 'recievedData', result.groupCode
Db.backend.set('recievedData', result.groupCode, 'history', result)
Db.backend.remove('recievedData', result.groupCode, 'history', 'groupCode')
Db.backend.set('recievedData', result.groupCode, 'players', result.players)
Db.backend.remove('recievedData', result.groupCode, 'history', 'players')
if Db.backend.peek('pluginInfoCopy', result.groupCode, 'upToDate') is 'false'
Db.backend.set 'pluginInfoCopy', result.groupCode, 'upToDate', 'true'
Db.backend.incr 'pluginInfo', result.groupCode, 'updateNumber'
else
log "[historyResult()] NO groupcode!"
else
log "[historyResult()] JSON parsing failed!"
else
log "[historyResult()] Group app not found!"
else
log '[historyResult()] Data not available!'
# Triggers when not all plugins responded in time, sets plugins to inactive
exports.gatheringTimeout = (args) ->
#Db.backend.iterate 'pluginInfo', (group) !-> TODO reenable
# if Db.backend.peek('pluginInfo', group.key(), 'upToDate') is 'false'
# Db.backend.set 'pluginInfo', group.key(), 'active', 'false'
finishGathering()
# Update number of plugins registered
updateNumberOfPlugins = ->
numberOfRegisters = 0
Db.backend.iterate 'pluginInfo', () !->
numberOfRegisters++
Db.shared.set 'registeredPlugins', numberOfRegisters
# Statistic calculations
recalculateStatistics = ->
log "[recalculateStatistics()]"
Db.shared.set('updatingStatistics', 'true')
# Set general numbers
totalPlayers = 0
totalEvents = 0
totalCaptures = 0
totalNeutralizes = 0
totalGames = 0
endedSetup = 0
endedRunning = 0
endedProper = 0
inactive = 0
beacons = 0
validBounds = 0
boundsTotalX = 0
boundsTotalY = 0
Db.shared.remove('eventsPerDay')
#allLatLng = '' # lat/lng string
eventsPerDay = {}
groupsPerGroupSize = {}
# THE BIG LOOP
Db.backend.iterate 'recievedData', (group) !->
players = group.peek('players')
if players?
players = parseInt(players)
totalPlayers += players
playersString = players + ''
if groupsPerGroupSize[playersString]?
groupsPerGroupSize[playersString] = groupsPerGroupSize[playersString]+1
else
groupsPerGroupSize[playersString] = 1
if Db.backend.peek('pluginInfo', group.key(), 'active') is 'false'
inactive++
group.iterate 'history', (game) !->
# Game statistics
totalGames++
gameState = game.peek('gameState')
if gameState?
if gameState == 0
endedSetup++
else if gameState == 1
endedRunning++
else if gameState == 2
endedProper++
# Team statistics
game.iterate 'game', 'teams', (team) !->
neutralized = team.peek('neutralized')
if neutralized?
totalNeutralizes += neutralized
# Eventlist statistics
game.iterate 'game', 'eventlist', (gameEvent) !->
totalEvents++
if gameEvent.key() isnt 'maxId'
type = gameEvent.peek('type')
if type == 'capture'
totalCaptures++
timestampToDay(gameEvent.peek('timestamp'))
else if type == 'captureAll'
totalCaptures++
timestampToDay(gameEvent.peek('timestamp'))
# Beacon statistics
game.iterate 'game', 'beacons', (beacon) !->
if gameState == 1 or gameState == 2
beacons++
#allLatLng += beacon.peek('location', 'lat') + ',' + beacon.peek('location', 'lng') + ';' # lat/lng string
if gameState == 1 or gameState == 2
lat1 = game.peek('game', 'bounds', 'one', 'lat')
lat2 = game.peek('game', 'bounds', 'two', 'lat')
lng1 = game.peek('game', 'bounds', 'one', 'lng')
lng2 = game.peek('game', 'bounds', 'two', 'lng')
if lat1? and lat2? and lng1? and lng2?
validBounds++
distY = distance(lat1, lng1, lat2, lng1)
if distY? and distY != NaN
boundsTotalY += distY
distX = distance(lat1, lng1, lat1, lng2)
if distX? and distX != NaN
boundsTotalX += distX
# Beacon statistics
Db.shared.set('beacons', beacons)
Db.shared.set('validBounds', validBounds)
Db.shared.set('boundsX', boundsTotalX/validBounds)
Db.shared.set('boundsY', boundsTotalY/validBounds)
#Db.shared.set 'allLatLng', allLatLng # lat/lng string
# General statistics
Db.shared.set('totalPlayers', totalPlayers)
Db.shared.set('averagePlayers', totalPlayers / parseInt(Db.shared.peek('registeredPlugins')))
# Game statistics
Db.shared.set('gamesSetup', endedSetup)
Db.shared.set('gamesRunning', endedRunning)
Db.shared.set('gamesEnded', endedProper)
Db.shared.set('removedPlugins', inactive)
# Team statistics
Db.shared.set('totalNeutralizes', totalNeutralizes)
# Eventlist statistics
Db.shared.set('totalGames', totalGames)
Db.shared.set('totalCaptures', totalCaptures)
Db.shared.set('totalEvents', totalEvents)
# Update number of events per day
for day, number of eventsPerDay
if day? and number? and day >= 0
Db.shared.set('eventsPerDay', day, number)
# Update groups per groupsize
for groupsize, count of groupsPerGroupSize
if groupsize? and count?
Db.shared.set('groupsPerGroupSize', groupsize, count)
# Update to current time, will only update if above went okey
Db.shared.set 'lastStatisticUpdate', new Date()/1000
Db.shared.set('updatingStatistics', 'false')
# Add one point to the captures for the day of the timestamp
timestampToDay = (timestamp) ->
if timestamp?
timestamp = timestamp - Config.startTimestamp
days = Math.floor(Math.round(timestamp) / 86400) + ''
events = eventsPerDay[days]
if events isnt undefined and events? and events isnt null
eventsPerDay[days] = events+1
else
eventsPerDay[days] = 1
return 0
# Calculate distance
distance = (inputLat1, inputLng1, inputLat2, inputLng2) ->
r = 6378137
rad = 3.141592653589793 / 180
lat1 = inputLat1 * rad
lat2 = inputLat2 * rad
a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((inputLng2 - inputLng1) * rad);
return r * Math.acos(Math.min(a, 1)); | 215816 | Db = require 'db'
Http = require 'http'
Timer = require 'timer'
Config = {
updateCompletionDelay: 500 # milliseconds between updating the doneCount for the client while gathering data
gatheringTimeout: 120*1000 # timeout of the gathering (time after receiving last result) non-updated plugins will be marked as inactive after this
gatherRequestsPerSecond: 100 # how many HTTP data gather requests will be send each second
startTimestamp: 1434405600.0 # Timestamp which is used as day 0 for the statistics
}
eventsPerDay = {}
groupsPerGroupSize = {}
# Upgrade of the plugin
exports.onUpgrade = ->
log '[onUpgrade()] at '+new Date()
Db.shared.set 'lastDeploy', new Date()+''
# Call from Conquest plugin for registering itself to this Data plugin
exports.onHttp = (request) ->
# special entrypoint for the Http API: called whenever a request is made to our plugin's inbound URL
log '[onHTTP()] Plugin ' + request.data + ' registered'
Db.backend.set 'pluginInfo', request.data, {'updateNumber': 0, 'active': 'true', 'upToDate': 'true'}
request.respond 200, 'Registered successfully'
updateNumberOfPlugins()
return 0
# Client call to update databases
exports.client_gatherHistory = ->
log '[gatherHistory()] Starting to request'
Timer.cancel 'gatheringTimeout', {}
Timer.cancel 'updateCompletion', {}
Db.shared.set 'doneCount', 0
Db.shared.set 'lastDoneCount', 0
Db.shared.set 'updating', 'true'
Db.shared.set "doneSendingRequests", 'no'
Db.backend.set 'pluginInfoCopy', Db.backend.peek('pluginInfo')
currentRequest = 0
Db.backend.iterate 'pluginInfo' , (group) !->
if group.peek('active') == 'true'
Db.backend.set 'pluginInfoCopy', group.key(), Db.backend.peek('pluginInfo', group.key())
Db.backend.set 'pluginInfoCopy', group.key(), 'upToDate', 'false'
currentRequest++
Db.shared.set 'currentRequest', currentRequest
Timer.set 0, 'doGatherStep', {}
Timer.set Config.gatheringTimeout, 'gatheringTimeout', {}
Timer.set Config.updateCompletionDelay, 'updateCompletion', {}
return 0
exports.doGatherStep = (args) ->
current = 0
currentRequest = Db.shared.peek('currentRequest')
Db.backend.iterate 'pluginInfoCopy' , (group) !->
if current >= currentRequest and current < (currentRequest+Config.gatherRequestsPerSecond)
log ' Requesting from: '+group.key()
Http.post
url: 'https://happening.im/x/' + group.key()
data: '<KEY>'
name: 'historyResult'
current++
currentRequest = currentRequest-Config.gatherRequestsPerSecond
Db.shared.set 'currentRequest', currentRequest
if currentRequest > 0
Timer.set 1000, 'doGatherStep', {}
else
Db.shared.set "doneSendingRequests", 'yes'
log '[doGatherStep()] Done sending requests'
return 0
# Client call for updating statistics
exports.client_updateStatistics = ->
recalculateStatistics()
# Update the donecount to be shown to the client, finishes the gathering if done
exports.updateCompletion = (args) ->
done = true
doneCount = 0
Db.backend.iterate 'pluginInfoCopy', (group) !->
if Db.backend.peek('pluginInfoCopy', group.key(), 'upToDate') is 'false'
done = false
else
doneCount++
Db.shared.set 'doneCount', doneCount
if done
finishGathering()
else
if Db.shared.peek('lastDoneCount') != doneCount
Timer.cancel 'gatheringTimeout', {}
Timer.set Config.gatheringTimeout, 'gatheringTimeout', {}
Timer.set Config.updateCompletionDelay, 'updateCompletion', {}
Db.shared.set 'lastDoneCount', doneCount
# End the gathring, trigger statistics update
finishGathering = ->
Timer.cancel 'gatheringTimeout', {}
Timer.cancel 'updateCompletion', {}
Db.shared.set('latestUpdate', new Date()/1000)
Db.shared.set 'updating', 'false'
Db.backend.remove 'pluginInfoCopy'
recalculateStatistics()
exports.historyResult = (data) !->
if data? and data isnt ''
if data.indexOf("<html><head><title>404 no such group app</title></head>") <= -1
result = JSON.parse(data)
if result?
log '[historyResult()] Recieved history from plugin: code='+result.groupCode
if result.groupCode? and result.groupCode isnt ''
Db.backend.remove 'recievedData', result.groupCode
Db.backend.set('recievedData', result.groupCode, 'history', result)
Db.backend.remove('recievedData', result.groupCode, 'history', 'groupCode')
Db.backend.set('recievedData', result.groupCode, 'players', result.players)
Db.backend.remove('recievedData', result.groupCode, 'history', 'players')
if Db.backend.peek('pluginInfoCopy', result.groupCode, 'upToDate') is 'false'
Db.backend.set 'pluginInfoCopy', result.groupCode, 'upToDate', 'true'
Db.backend.incr 'pluginInfo', result.groupCode, 'updateNumber'
else
log "[historyResult()] NO groupcode!"
else
log "[historyResult()] JSON parsing failed!"
else
log "[historyResult()] Group app not found!"
else
log '[historyResult()] Data not available!'
# Triggers when not all plugins responded in time, sets plugins to inactive
exports.gatheringTimeout = (args) ->
#Db.backend.iterate 'pluginInfo', (group) !-> TODO reenable
# if Db.backend.peek('pluginInfo', group.key(), 'upToDate') is 'false'
# Db.backend.set 'pluginInfo', group.key(), 'active', 'false'
finishGathering()
# Update number of plugins registered
updateNumberOfPlugins = ->
numberOfRegisters = 0
Db.backend.iterate 'pluginInfo', () !->
numberOfRegisters++
Db.shared.set 'registeredPlugins', numberOfRegisters
# Statistic calculations
recalculateStatistics = ->
log "[recalculateStatistics()]"
Db.shared.set('updatingStatistics', 'true')
# Set general numbers
totalPlayers = 0
totalEvents = 0
totalCaptures = 0
totalNeutralizes = 0
totalGames = 0
endedSetup = 0
endedRunning = 0
endedProper = 0
inactive = 0
beacons = 0
validBounds = 0
boundsTotalX = 0
boundsTotalY = 0
Db.shared.remove('eventsPerDay')
#allLatLng = '' # lat/lng string
eventsPerDay = {}
groupsPerGroupSize = {}
# THE BIG LOOP
Db.backend.iterate 'recievedData', (group) !->
players = group.peek('players')
if players?
players = parseInt(players)
totalPlayers += players
playersString = players + ''
if groupsPerGroupSize[playersString]?
groupsPerGroupSize[playersString] = groupsPerGroupSize[playersString]+1
else
groupsPerGroupSize[playersString] = 1
if Db.backend.peek('pluginInfo', group.key(), 'active') is 'false'
inactive++
group.iterate 'history', (game) !->
# Game statistics
totalGames++
gameState = game.peek('gameState')
if gameState?
if gameState == 0
endedSetup++
else if gameState == 1
endedRunning++
else if gameState == 2
endedProper++
# Team statistics
game.iterate 'game', 'teams', (team) !->
neutralized = team.peek('neutralized')
if neutralized?
totalNeutralizes += neutralized
# Eventlist statistics
game.iterate 'game', 'eventlist', (gameEvent) !->
totalEvents++
if gameEvent.key() isnt 'maxId'
type = gameEvent.peek('type')
if type == 'capture'
totalCaptures++
timestampToDay(gameEvent.peek('timestamp'))
else if type == 'captureAll'
totalCaptures++
timestampToDay(gameEvent.peek('timestamp'))
# Beacon statistics
game.iterate 'game', 'beacons', (beacon) !->
if gameState == 1 or gameState == 2
beacons++
#allLatLng += beacon.peek('location', 'lat') + ',' + beacon.peek('location', 'lng') + ';' # lat/lng string
if gameState == 1 or gameState == 2
lat1 = game.peek('game', 'bounds', 'one', 'lat')
lat2 = game.peek('game', 'bounds', 'two', 'lat')
lng1 = game.peek('game', 'bounds', 'one', 'lng')
lng2 = game.peek('game', 'bounds', 'two', 'lng')
if lat1? and lat2? and lng1? and lng2?
validBounds++
distY = distance(lat1, lng1, lat2, lng1)
if distY? and distY != NaN
boundsTotalY += distY
distX = distance(lat1, lng1, lat1, lng2)
if distX? and distX != NaN
boundsTotalX += distX
# Beacon statistics
Db.shared.set('beacons', beacons)
Db.shared.set('validBounds', validBounds)
Db.shared.set('boundsX', boundsTotalX/validBounds)
Db.shared.set('boundsY', boundsTotalY/validBounds)
#Db.shared.set 'allLatLng', allLatLng # lat/lng string
# General statistics
Db.shared.set('totalPlayers', totalPlayers)
Db.shared.set('averagePlayers', totalPlayers / parseInt(Db.shared.peek('registeredPlugins')))
# Game statistics
Db.shared.set('gamesSetup', endedSetup)
Db.shared.set('gamesRunning', endedRunning)
Db.shared.set('gamesEnded', endedProper)
Db.shared.set('removedPlugins', inactive)
# Team statistics
Db.shared.set('totalNeutralizes', totalNeutralizes)
# Eventlist statistics
Db.shared.set('totalGames', totalGames)
Db.shared.set('totalCaptures', totalCaptures)
Db.shared.set('totalEvents', totalEvents)
# Update number of events per day
for day, number of eventsPerDay
if day? and number? and day >= 0
Db.shared.set('eventsPerDay', day, number)
# Update groups per groupsize
for groupsize, count of groupsPerGroupSize
if groupsize? and count?
Db.shared.set('groupsPerGroupSize', groupsize, count)
# Update to current time, will only update if above went okey
Db.shared.set 'lastStatisticUpdate', new Date()/1000
Db.shared.set('updatingStatistics', 'false')
# Add one point to the captures for the day of the timestamp
timestampToDay = (timestamp) ->
if timestamp?
timestamp = timestamp - Config.startTimestamp
days = Math.floor(Math.round(timestamp) / 86400) + ''
events = eventsPerDay[days]
if events isnt undefined and events? and events isnt null
eventsPerDay[days] = events+1
else
eventsPerDay[days] = 1
return 0
# Calculate distance
distance = (inputLat1, inputLng1, inputLat2, inputLng2) ->
r = 6378137
rad = 3.141592653589793 / 180
lat1 = inputLat1 * rad
lat2 = inputLat2 * rad
a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((inputLng2 - inputLng1) * rad);
return r * Math.acos(Math.min(a, 1)); | true | Db = require 'db'
Http = require 'http'
Timer = require 'timer'
Config = {
updateCompletionDelay: 500 # milliseconds between updating the doneCount for the client while gathering data
gatheringTimeout: 120*1000 # timeout of the gathering (time after receiving last result) non-updated plugins will be marked as inactive after this
gatherRequestsPerSecond: 100 # how many HTTP data gather requests will be send each second
startTimestamp: 1434405600.0 # Timestamp which is used as day 0 for the statistics
}
eventsPerDay = {}
groupsPerGroupSize = {}
# Upgrade of the plugin
exports.onUpgrade = ->
log '[onUpgrade()] at '+new Date()
Db.shared.set 'lastDeploy', new Date()+''
# Call from Conquest plugin for registering itself to this Data plugin
exports.onHttp = (request) ->
# special entrypoint for the Http API: called whenever a request is made to our plugin's inbound URL
log '[onHTTP()] Plugin ' + request.data + ' registered'
Db.backend.set 'pluginInfo', request.data, {'updateNumber': 0, 'active': 'true', 'upToDate': 'true'}
request.respond 200, 'Registered successfully'
updateNumberOfPlugins()
return 0
# Client call to update databases
exports.client_gatherHistory = ->
log '[gatherHistory()] Starting to request'
Timer.cancel 'gatheringTimeout', {}
Timer.cancel 'updateCompletion', {}
Db.shared.set 'doneCount', 0
Db.shared.set 'lastDoneCount', 0
Db.shared.set 'updating', 'true'
Db.shared.set "doneSendingRequests", 'no'
Db.backend.set 'pluginInfoCopy', Db.backend.peek('pluginInfo')
currentRequest = 0
Db.backend.iterate 'pluginInfo' , (group) !->
if group.peek('active') == 'true'
Db.backend.set 'pluginInfoCopy', group.key(), Db.backend.peek('pluginInfo', group.key())
Db.backend.set 'pluginInfoCopy', group.key(), 'upToDate', 'false'
currentRequest++
Db.shared.set 'currentRequest', currentRequest
Timer.set 0, 'doGatherStep', {}
Timer.set Config.gatheringTimeout, 'gatheringTimeout', {}
Timer.set Config.updateCompletionDelay, 'updateCompletion', {}
return 0
exports.doGatherStep = (args) ->
current = 0
currentRequest = Db.shared.peek('currentRequest')
Db.backend.iterate 'pluginInfoCopy' , (group) !->
if current >= currentRequest and current < (currentRequest+Config.gatherRequestsPerSecond)
log ' Requesting from: '+group.key()
Http.post
url: 'https://happening.im/x/' + group.key()
data: 'PI:KEY:<KEY>END_PI'
name: 'historyResult'
current++
currentRequest = currentRequest-Config.gatherRequestsPerSecond
Db.shared.set 'currentRequest', currentRequest
if currentRequest > 0
Timer.set 1000, 'doGatherStep', {}
else
Db.shared.set "doneSendingRequests", 'yes'
log '[doGatherStep()] Done sending requests'
return 0
# Client call for updating statistics
exports.client_updateStatistics = ->
recalculateStatistics()
# Update the donecount to be shown to the client, finishes the gathering if done
exports.updateCompletion = (args) ->
done = true
doneCount = 0
Db.backend.iterate 'pluginInfoCopy', (group) !->
if Db.backend.peek('pluginInfoCopy', group.key(), 'upToDate') is 'false'
done = false
else
doneCount++
Db.shared.set 'doneCount', doneCount
if done
finishGathering()
else
if Db.shared.peek('lastDoneCount') != doneCount
Timer.cancel 'gatheringTimeout', {}
Timer.set Config.gatheringTimeout, 'gatheringTimeout', {}
Timer.set Config.updateCompletionDelay, 'updateCompletion', {}
Db.shared.set 'lastDoneCount', doneCount
# End the gathring, trigger statistics update
finishGathering = ->
Timer.cancel 'gatheringTimeout', {}
Timer.cancel 'updateCompletion', {}
Db.shared.set('latestUpdate', new Date()/1000)
Db.shared.set 'updating', 'false'
Db.backend.remove 'pluginInfoCopy'
recalculateStatistics()
exports.historyResult = (data) !->
if data? and data isnt ''
if data.indexOf("<html><head><title>404 no such group app</title></head>") <= -1
result = JSON.parse(data)
if result?
log '[historyResult()] Recieved history from plugin: code='+result.groupCode
if result.groupCode? and result.groupCode isnt ''
Db.backend.remove 'recievedData', result.groupCode
Db.backend.set('recievedData', result.groupCode, 'history', result)
Db.backend.remove('recievedData', result.groupCode, 'history', 'groupCode')
Db.backend.set('recievedData', result.groupCode, 'players', result.players)
Db.backend.remove('recievedData', result.groupCode, 'history', 'players')
if Db.backend.peek('pluginInfoCopy', result.groupCode, 'upToDate') is 'false'
Db.backend.set 'pluginInfoCopy', result.groupCode, 'upToDate', 'true'
Db.backend.incr 'pluginInfo', result.groupCode, 'updateNumber'
else
log "[historyResult()] NO groupcode!"
else
log "[historyResult()] JSON parsing failed!"
else
log "[historyResult()] Group app not found!"
else
log '[historyResult()] Data not available!'
# Triggers when not all plugins responded in time, sets plugins to inactive
exports.gatheringTimeout = (args) ->
#Db.backend.iterate 'pluginInfo', (group) !-> TODO reenable
# if Db.backend.peek('pluginInfo', group.key(), 'upToDate') is 'false'
# Db.backend.set 'pluginInfo', group.key(), 'active', 'false'
finishGathering()
# Update number of plugins registered
updateNumberOfPlugins = ->
numberOfRegisters = 0
Db.backend.iterate 'pluginInfo', () !->
numberOfRegisters++
Db.shared.set 'registeredPlugins', numberOfRegisters
# Statistic calculations
recalculateStatistics = ->
log "[recalculateStatistics()]"
Db.shared.set('updatingStatistics', 'true')
# Set general numbers
totalPlayers = 0
totalEvents = 0
totalCaptures = 0
totalNeutralizes = 0
totalGames = 0
endedSetup = 0
endedRunning = 0
endedProper = 0
inactive = 0
beacons = 0
validBounds = 0
boundsTotalX = 0
boundsTotalY = 0
Db.shared.remove('eventsPerDay')
#allLatLng = '' # lat/lng string
eventsPerDay = {}
groupsPerGroupSize = {}
# THE BIG LOOP
Db.backend.iterate 'recievedData', (group) !->
players = group.peek('players')
if players?
players = parseInt(players)
totalPlayers += players
playersString = players + ''
if groupsPerGroupSize[playersString]?
groupsPerGroupSize[playersString] = groupsPerGroupSize[playersString]+1
else
groupsPerGroupSize[playersString] = 1
if Db.backend.peek('pluginInfo', group.key(), 'active') is 'false'
inactive++
group.iterate 'history', (game) !->
# Game statistics
totalGames++
gameState = game.peek('gameState')
if gameState?
if gameState == 0
endedSetup++
else if gameState == 1
endedRunning++
else if gameState == 2
endedProper++
# Team statistics
game.iterate 'game', 'teams', (team) !->
neutralized = team.peek('neutralized')
if neutralized?
totalNeutralizes += neutralized
# Eventlist statistics
game.iterate 'game', 'eventlist', (gameEvent) !->
totalEvents++
if gameEvent.key() isnt 'maxId'
type = gameEvent.peek('type')
if type == 'capture'
totalCaptures++
timestampToDay(gameEvent.peek('timestamp'))
else if type == 'captureAll'
totalCaptures++
timestampToDay(gameEvent.peek('timestamp'))
# Beacon statistics
game.iterate 'game', 'beacons', (beacon) !->
if gameState == 1 or gameState == 2
beacons++
#allLatLng += beacon.peek('location', 'lat') + ',' + beacon.peek('location', 'lng') + ';' # lat/lng string
if gameState == 1 or gameState == 2
lat1 = game.peek('game', 'bounds', 'one', 'lat')
lat2 = game.peek('game', 'bounds', 'two', 'lat')
lng1 = game.peek('game', 'bounds', 'one', 'lng')
lng2 = game.peek('game', 'bounds', 'two', 'lng')
if lat1? and lat2? and lng1? and lng2?
validBounds++
distY = distance(lat1, lng1, lat2, lng1)
if distY? and distY != NaN
boundsTotalY += distY
distX = distance(lat1, lng1, lat1, lng2)
if distX? and distX != NaN
boundsTotalX += distX
# Beacon statistics
Db.shared.set('beacons', beacons)
Db.shared.set('validBounds', validBounds)
Db.shared.set('boundsX', boundsTotalX/validBounds)
Db.shared.set('boundsY', boundsTotalY/validBounds)
#Db.shared.set 'allLatLng', allLatLng # lat/lng string
# General statistics
Db.shared.set('totalPlayers', totalPlayers)
Db.shared.set('averagePlayers', totalPlayers / parseInt(Db.shared.peek('registeredPlugins')))
# Game statistics
Db.shared.set('gamesSetup', endedSetup)
Db.shared.set('gamesRunning', endedRunning)
Db.shared.set('gamesEnded', endedProper)
Db.shared.set('removedPlugins', inactive)
# Team statistics
Db.shared.set('totalNeutralizes', totalNeutralizes)
# Eventlist statistics
Db.shared.set('totalGames', totalGames)
Db.shared.set('totalCaptures', totalCaptures)
Db.shared.set('totalEvents', totalEvents)
# Update number of events per day
for day, number of eventsPerDay
if day? and number? and day >= 0
Db.shared.set('eventsPerDay', day, number)
# Update groups per groupsize
for groupsize, count of groupsPerGroupSize
if groupsize? and count?
Db.shared.set('groupsPerGroupSize', groupsize, count)
# Update to current time, will only update if above went okey
Db.shared.set 'lastStatisticUpdate', new Date()/1000
Db.shared.set('updatingStatistics', 'false')
# Add one point to the captures for the day of the timestamp
timestampToDay = (timestamp) ->
if timestamp?
timestamp = timestamp - Config.startTimestamp
days = Math.floor(Math.round(timestamp) / 86400) + ''
events = eventsPerDay[days]
if events isnt undefined and events? and events isnt null
eventsPerDay[days] = events+1
else
eventsPerDay[days] = 1
return 0
# Calculate distance
distance = (inputLat1, inputLng1, inputLat2, inputLng2) ->
r = 6378137
rad = 3.141592653589793 / 180
lat1 = inputLat1 * rad
lat2 = inputLat2 * rad
a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((inputLng2 - inputLng1) * rad);
return r * Math.acos(Math.min(a, 1)); |
[
{
"context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed unde",
"end": 23,
"score": 0.9995310306549072,
"start": 17,
"tag": "NAME",
"value": "SASAKI"
},
{
"context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed under the Apac",
"end": 33,
"score": 0.9326545000076294,
"start": 25,
"tag": "NAME",
"value": "Shunsuke"
}
] | test/test_searcher.coffee | erukiti/cerebrums | 7 | # Copyright 2015 SASAKI, Shunsuke. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
assert = require 'power-assert'
sinon = require 'sinon'
Searcher = require '../src/searcher.coffee'
describe 'Searcher', ->
it '#search', ->
meta1 = {uuid: 'hoge1', title: 'hogefuga', updatedAt: Date.parse('2015-07-14T00:00:00.000Z')}
meta2 = {uuid: 'hoge2', title: 'abracadabra', updatedAt: Date.parse('2015-07-15T00:00:00.000Z')}
meta3 = {uuid: 'hoge3', title: 'ほげふが', updatedAt: Date.parse('2015-07-12T00:00:00.000Z')}
docs = [
{meta: meta1, text: 'hoge fuga piyo'}
{meta: meta2, text: 'abracadabra'}
]
searcher = new Searcher(docs)
assert.deepEqual searcher.search('h'), [meta1]
assert.deepEqual searcher.search('a'), [meta1, meta2]
assert.deepEqual searcher.search('ほ'), []
searcher.add(meta3, 'ほげ ふが ぴよ')
console.dir searcher.search('')
it '#recent', ->
meta1 = {uuid: 'hoge1', title: 'hogefuga', updatedAt: Date.parse('2015-07-14T00:00:00.000Z')}
meta2 = {uuid: 'hoge2', title: 'abracadabra', updatedAt: Date.parse('2015-07-15T00:00:00.000Z')}
meta3 = {uuid: 'hoge3', title: 'ほげふが', updatedAt: Date.parse('2015-07-12T00:00:00.000Z')}
docs = [
{meta: meta1, text: 'hoge fuga piyo'}
{meta: meta2, text: 'abracadabra'}
{meta: meta3, text: 'ほげ ふが ぴよ'}
]
searcher = new Searcher(docs)
assert.deepEqual searcher.getRecent(), [meta2, meta1, meta3]
| 210551 | # Copyright 2015 <NAME>, <NAME>. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
assert = require 'power-assert'
sinon = require 'sinon'
Searcher = require '../src/searcher.coffee'
describe 'Searcher', ->
it '#search', ->
meta1 = {uuid: 'hoge1', title: 'hogefuga', updatedAt: Date.parse('2015-07-14T00:00:00.000Z')}
meta2 = {uuid: 'hoge2', title: 'abracadabra', updatedAt: Date.parse('2015-07-15T00:00:00.000Z')}
meta3 = {uuid: 'hoge3', title: 'ほげふが', updatedAt: Date.parse('2015-07-12T00:00:00.000Z')}
docs = [
{meta: meta1, text: 'hoge fuga piyo'}
{meta: meta2, text: 'abracadabra'}
]
searcher = new Searcher(docs)
assert.deepEqual searcher.search('h'), [meta1]
assert.deepEqual searcher.search('a'), [meta1, meta2]
assert.deepEqual searcher.search('ほ'), []
searcher.add(meta3, 'ほげ ふが ぴよ')
console.dir searcher.search('')
it '#recent', ->
meta1 = {uuid: 'hoge1', title: 'hogefuga', updatedAt: Date.parse('2015-07-14T00:00:00.000Z')}
meta2 = {uuid: 'hoge2', title: 'abracadabra', updatedAt: Date.parse('2015-07-15T00:00:00.000Z')}
meta3 = {uuid: 'hoge3', title: 'ほげふが', updatedAt: Date.parse('2015-07-12T00:00:00.000Z')}
docs = [
{meta: meta1, text: 'hoge fuga piyo'}
{meta: meta2, text: 'abracadabra'}
{meta: meta3, text: 'ほげ ふが ぴよ'}
]
searcher = new Searcher(docs)
assert.deepEqual searcher.getRecent(), [meta2, meta1, meta3]
| true | # Copyright 2015 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# 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.
assert = require 'power-assert'
sinon = require 'sinon'
Searcher = require '../src/searcher.coffee'
describe 'Searcher', ->
it '#search', ->
meta1 = {uuid: 'hoge1', title: 'hogefuga', updatedAt: Date.parse('2015-07-14T00:00:00.000Z')}
meta2 = {uuid: 'hoge2', title: 'abracadabra', updatedAt: Date.parse('2015-07-15T00:00:00.000Z')}
meta3 = {uuid: 'hoge3', title: 'ほげふが', updatedAt: Date.parse('2015-07-12T00:00:00.000Z')}
docs = [
{meta: meta1, text: 'hoge fuga piyo'}
{meta: meta2, text: 'abracadabra'}
]
searcher = new Searcher(docs)
assert.deepEqual searcher.search('h'), [meta1]
assert.deepEqual searcher.search('a'), [meta1, meta2]
assert.deepEqual searcher.search('ほ'), []
searcher.add(meta3, 'ほげ ふが ぴよ')
console.dir searcher.search('')
it '#recent', ->
meta1 = {uuid: 'hoge1', title: 'hogefuga', updatedAt: Date.parse('2015-07-14T00:00:00.000Z')}
meta2 = {uuid: 'hoge2', title: 'abracadabra', updatedAt: Date.parse('2015-07-15T00:00:00.000Z')}
meta3 = {uuid: 'hoge3', title: 'ほげふが', updatedAt: Date.parse('2015-07-12T00:00:00.000Z')}
docs = [
{meta: meta1, text: 'hoge fuga piyo'}
{meta: meta2, text: 'abracadabra'}
{meta: meta3, text: 'ほげ ふが ぴよ'}
]
searcher = new Searcher(docs)
assert.deepEqual searcher.getRecent(), [meta2, meta1, meta3]
|
[
{
"context": " uri: \"#{apiUrl}#{query}\"\n auth:\n user: \"coconut\"\n pass: \"Coconut@2019\"\n json: true\n qs",
"end": 714,
"score": 0.9994065165519714,
"start": 707,
"tag": "USERNAME",
"value": "coconut"
},
{
"context": "ry}\"\n auth:\n user: \"coconut\"\n pass: \"Coconut@2019\"\n json: true\n qs:\n paging: false\n\nupda",
"end": 741,
"score": 0.998164176940918,
"start": 729,
"tag": "PASSWORD",
"value": "Coconut@2019"
}
] | scripts/Dhis2OrgUnitsToGeographicHierarchy.coffee | jongoz/coconut-analytice | 3 | PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
PouchDB.plugin(require('pouchdb-upsert'))
Request = require 'request-promise-native'
_ = require 'underscore'
moment = require 'moment'
fs = require 'fs'
exec = require('child_process').execSync
GeographicHierarchy =
isApplicationDoc: true
dateCreated: new moment().format("YYYY-MM-DD")
levels: []
groups: []
units: []
privateGroupId = null
resultsById = {}
dhis2Request = (query) =>
#apiUrl = "http://173.255.223.117/api/"
apiUrl = "https://mohzn.go.tz/api/"
console.error "#{apiUrl}#{query}"
Request.get
uri: "#{apiUrl}#{query}"
auth:
user: "coconut"
pass: "Coconut@2019"
json: true
qs:
paging: false
updateUnit = (unitId) =>
unit = await dhis2Request "organisationUnits/#{unitId}"
if unit.level is 7
console.warn "Skipping: #{unit.name}"
return
console.warn unit.name
result =
name: unit.name
parentId: unit.parent?.id
level: unit.level
id: unit.id
if resultsById[unit.id] # Not sure why we get duplicate units for the same ID, sometimes the names are the same sometimes they are variations
if resultsById[unit.id].name is unit.name # If it's the same name for the same ID nothing left to do
console.warn "Duplicate name: #{unit.name}"
else if resultsById[unit].aliases.find (alias) => alias.name is unit.name # If we already have an alias for this name return
console.warn "Duplicate alias: #{alias.name}"
else
resultsById[unit.id].aliases or= []
resultsById[unit.id].aliases.push
name: unit.shortName
description: "Other name"
return
# Find private units and put them in the private group
if _(unit.organisationUnitGroups).find (group) => group.id is privateGroupId
privateGroup = GeographicHierarchy.groups.find (group) =>
group.groupId is privateGroupId
privateGroup.unitIds.push unit.id if privateGroup
if unit.name isnt unit.shortName
result.aliases or= []
result.aliases.push
name: unit.shortName
description: "Short Name"
resultsById[unit.id] = result
getLevels = =>
# Get all Levels
for level in await dhis2Request "filledOrganisationUnitLevels"
GeographicHierarchy.levels.push
name: level.name
number: level.level
id: level.id
getGroups = =>
# Only interested in PRIVATE health facilities for now
for group in (await dhis2Request "organisationUnitGroups.json").organisationUnitGroups
console.error group.displayName
if group.displayName is "Private"
privateGroupId = group.id
GeographicHierarchy.groups.push
name: "PRIVATE"
groupId: group.id
unitIds: []
createGeographicHierarchy = =>
console.warn "Messages appear on STDERR, while the actual result is on STDOUT, so use > out.json to capture the result of this script"
console.warn "Getting Levels"
await getLevels()
console.warn "Getting Groups"
await getGroups()
console.warn "Getting Org Units"
units = (await dhis2Request "organisationUnits.json").organisationUnits
i=0
numberToGetInParallel = 20
while i < units.length
console.warn "#{i}/#{units.length}"
await Promise.all(units[i..i+=numberToGetInParallel].map (unitId) =>
updateUnit(unitId.id)
)
GeographicHierarchy.units = _(resultsById).sortBy (result, id) => result.name # returns array of units sorted by name to make it easier to look through
GeographicHierarchy
(=>
if process.argv[2] is "--update" and target = process.argv[3]
console.warn "Creating new geographic hierarchy and then updating"
splitTarget = target.split(/\//)
docName = splitTarget.pop()
db = splitTarget.join("/")
database = new PouchDB(db)
console.log await(database.info())
console.log docName
geographicHierarchy = await createGeographicHierarchy()
await database.upsert docName, (doc) => geographicHierarchy
.catch (error) => console.error error
console.warn "#{docName} updated at #{db}."
else if process.argv[2] is "--diff" and target = process.argv[3]
fs.writeFileSync "/tmp/currentUnformatted.json", (await Request.get
uri: target
), (error) -> console.error error
exec "cat /tmp/currentUnformatted.json | /usr/bin/jq . > /tmp/current.json", (error) => console.error error
console.warn "/tmp/current.json written"
fs.writeFileSync "/tmp/newUnformatted.json", JSON.stringify(await createGeographicHierarchy()), (error) -> console.error error
exec "cat /tmp/newUnformatted.json | jq . > /tmp/new.json"
console.warn "/tmp/new.json written"
console.warn "use diff or meld to compare, e.g. meld /tmp/current.json /tmp/new.json"
else
JSON.stringify createGeographicHierarchy()
)()
| 59241 | PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
PouchDB.plugin(require('pouchdb-upsert'))
Request = require 'request-promise-native'
_ = require 'underscore'
moment = require 'moment'
fs = require 'fs'
exec = require('child_process').execSync
GeographicHierarchy =
isApplicationDoc: true
dateCreated: new moment().format("YYYY-MM-DD")
levels: []
groups: []
units: []
privateGroupId = null
resultsById = {}
dhis2Request = (query) =>
#apiUrl = "http://173.255.223.117/api/"
apiUrl = "https://mohzn.go.tz/api/"
console.error "#{apiUrl}#{query}"
Request.get
uri: "#{apiUrl}#{query}"
auth:
user: "coconut"
pass: "<PASSWORD>"
json: true
qs:
paging: false
updateUnit = (unitId) =>
unit = await dhis2Request "organisationUnits/#{unitId}"
if unit.level is 7
console.warn "Skipping: #{unit.name}"
return
console.warn unit.name
result =
name: unit.name
parentId: unit.parent?.id
level: unit.level
id: unit.id
if resultsById[unit.id] # Not sure why we get duplicate units for the same ID, sometimes the names are the same sometimes they are variations
if resultsById[unit.id].name is unit.name # If it's the same name for the same ID nothing left to do
console.warn "Duplicate name: #{unit.name}"
else if resultsById[unit].aliases.find (alias) => alias.name is unit.name # If we already have an alias for this name return
console.warn "Duplicate alias: #{alias.name}"
else
resultsById[unit.id].aliases or= []
resultsById[unit.id].aliases.push
name: unit.shortName
description: "Other name"
return
# Find private units and put them in the private group
if _(unit.organisationUnitGroups).find (group) => group.id is privateGroupId
privateGroup = GeographicHierarchy.groups.find (group) =>
group.groupId is privateGroupId
privateGroup.unitIds.push unit.id if privateGroup
if unit.name isnt unit.shortName
result.aliases or= []
result.aliases.push
name: unit.shortName
description: "Short Name"
resultsById[unit.id] = result
getLevels = =>
# Get all Levels
for level in await dhis2Request "filledOrganisationUnitLevels"
GeographicHierarchy.levels.push
name: level.name
number: level.level
id: level.id
getGroups = =>
# Only interested in PRIVATE health facilities for now
for group in (await dhis2Request "organisationUnitGroups.json").organisationUnitGroups
console.error group.displayName
if group.displayName is "Private"
privateGroupId = group.id
GeographicHierarchy.groups.push
name: "PRIVATE"
groupId: group.id
unitIds: []
createGeographicHierarchy = =>
console.warn "Messages appear on STDERR, while the actual result is on STDOUT, so use > out.json to capture the result of this script"
console.warn "Getting Levels"
await getLevels()
console.warn "Getting Groups"
await getGroups()
console.warn "Getting Org Units"
units = (await dhis2Request "organisationUnits.json").organisationUnits
i=0
numberToGetInParallel = 20
while i < units.length
console.warn "#{i}/#{units.length}"
await Promise.all(units[i..i+=numberToGetInParallel].map (unitId) =>
updateUnit(unitId.id)
)
GeographicHierarchy.units = _(resultsById).sortBy (result, id) => result.name # returns array of units sorted by name to make it easier to look through
GeographicHierarchy
(=>
if process.argv[2] is "--update" and target = process.argv[3]
console.warn "Creating new geographic hierarchy and then updating"
splitTarget = target.split(/\//)
docName = splitTarget.pop()
db = splitTarget.join("/")
database = new PouchDB(db)
console.log await(database.info())
console.log docName
geographicHierarchy = await createGeographicHierarchy()
await database.upsert docName, (doc) => geographicHierarchy
.catch (error) => console.error error
console.warn "#{docName} updated at #{db}."
else if process.argv[2] is "--diff" and target = process.argv[3]
fs.writeFileSync "/tmp/currentUnformatted.json", (await Request.get
uri: target
), (error) -> console.error error
exec "cat /tmp/currentUnformatted.json | /usr/bin/jq . > /tmp/current.json", (error) => console.error error
console.warn "/tmp/current.json written"
fs.writeFileSync "/tmp/newUnformatted.json", JSON.stringify(await createGeographicHierarchy()), (error) -> console.error error
exec "cat /tmp/newUnformatted.json | jq . > /tmp/new.json"
console.warn "/tmp/new.json written"
console.warn "use diff or meld to compare, e.g. meld /tmp/current.json /tmp/new.json"
else
JSON.stringify createGeographicHierarchy()
)()
| true | PouchDB = require 'pouchdb-core'
PouchDB.plugin(require('pouchdb-adapter-http'))
PouchDB.plugin(require('pouchdb-mapreduce'))
PouchDB.plugin(require('pouchdb-upsert'))
Request = require 'request-promise-native'
_ = require 'underscore'
moment = require 'moment'
fs = require 'fs'
exec = require('child_process').execSync
GeographicHierarchy =
isApplicationDoc: true
dateCreated: new moment().format("YYYY-MM-DD")
levels: []
groups: []
units: []
privateGroupId = null
resultsById = {}
dhis2Request = (query) =>
#apiUrl = "http://173.255.223.117/api/"
apiUrl = "https://mohzn.go.tz/api/"
console.error "#{apiUrl}#{query}"
Request.get
uri: "#{apiUrl}#{query}"
auth:
user: "coconut"
pass: "PI:PASSWORD:<PASSWORD>END_PI"
json: true
qs:
paging: false
updateUnit = (unitId) =>
unit = await dhis2Request "organisationUnits/#{unitId}"
if unit.level is 7
console.warn "Skipping: #{unit.name}"
return
console.warn unit.name
result =
name: unit.name
parentId: unit.parent?.id
level: unit.level
id: unit.id
if resultsById[unit.id] # Not sure why we get duplicate units for the same ID, sometimes the names are the same sometimes they are variations
if resultsById[unit.id].name is unit.name # If it's the same name for the same ID nothing left to do
console.warn "Duplicate name: #{unit.name}"
else if resultsById[unit].aliases.find (alias) => alias.name is unit.name # If we already have an alias for this name return
console.warn "Duplicate alias: #{alias.name}"
else
resultsById[unit.id].aliases or= []
resultsById[unit.id].aliases.push
name: unit.shortName
description: "Other name"
return
# Find private units and put them in the private group
if _(unit.organisationUnitGroups).find (group) => group.id is privateGroupId
privateGroup = GeographicHierarchy.groups.find (group) =>
group.groupId is privateGroupId
privateGroup.unitIds.push unit.id if privateGroup
if unit.name isnt unit.shortName
result.aliases or= []
result.aliases.push
name: unit.shortName
description: "Short Name"
resultsById[unit.id] = result
getLevels = =>
# Get all Levels
for level in await dhis2Request "filledOrganisationUnitLevels"
GeographicHierarchy.levels.push
name: level.name
number: level.level
id: level.id
getGroups = =>
# Only interested in PRIVATE health facilities for now
for group in (await dhis2Request "organisationUnitGroups.json").organisationUnitGroups
console.error group.displayName
if group.displayName is "Private"
privateGroupId = group.id
GeographicHierarchy.groups.push
name: "PRIVATE"
groupId: group.id
unitIds: []
createGeographicHierarchy = =>
console.warn "Messages appear on STDERR, while the actual result is on STDOUT, so use > out.json to capture the result of this script"
console.warn "Getting Levels"
await getLevels()
console.warn "Getting Groups"
await getGroups()
console.warn "Getting Org Units"
units = (await dhis2Request "organisationUnits.json").organisationUnits
i=0
numberToGetInParallel = 20
while i < units.length
console.warn "#{i}/#{units.length}"
await Promise.all(units[i..i+=numberToGetInParallel].map (unitId) =>
updateUnit(unitId.id)
)
GeographicHierarchy.units = _(resultsById).sortBy (result, id) => result.name # returns array of units sorted by name to make it easier to look through
GeographicHierarchy
(=>
if process.argv[2] is "--update" and target = process.argv[3]
console.warn "Creating new geographic hierarchy and then updating"
splitTarget = target.split(/\//)
docName = splitTarget.pop()
db = splitTarget.join("/")
database = new PouchDB(db)
console.log await(database.info())
console.log docName
geographicHierarchy = await createGeographicHierarchy()
await database.upsert docName, (doc) => geographicHierarchy
.catch (error) => console.error error
console.warn "#{docName} updated at #{db}."
else if process.argv[2] is "--diff" and target = process.argv[3]
fs.writeFileSync "/tmp/currentUnformatted.json", (await Request.get
uri: target
), (error) -> console.error error
exec "cat /tmp/currentUnformatted.json | /usr/bin/jq . > /tmp/current.json", (error) => console.error error
console.warn "/tmp/current.json written"
fs.writeFileSync "/tmp/newUnformatted.json", JSON.stringify(await createGeographicHierarchy()), (error) -> console.error error
exec "cat /tmp/newUnformatted.json | jq . > /tmp/new.json"
console.warn "/tmp/new.json written"
console.warn "use diff or meld to compare, e.g. meld /tmp/current.json /tmp/new.json"
else
JSON.stringify createGeographicHierarchy()
)()
|
[
{
"context": "m')\nxpath = require('xpath')\n\nxml = \"<book><title>Harry Potter</title></book>\"\ndoc = new DOMParser().parseFromSt",
"end": 230,
"score": 0.9992510676383972,
"start": 218,
"tag": "NAME",
"value": "Harry Potter"
}
] | axes.coffee | KamilSzot/nicelanguage | 0 |
Entity = {
as: {
}
}
App = Object.create(Entity)
Router = Object.create(Entity)
App.as.web = 1;
console.log Router.as
{DOMParser, XMLSerializer} = require('xmldom')
xpath = require('xpath')
xml = "<book><title>Harry Potter</title></book>"
doc = new DOMParser().parseFromString(xml)
nodes = xpath.select(".//title", doc)
console.log(nodes[0].localName + ": " + nodes[0].firstChild.data)
console.log("node: " + nodes[0].toString())
ui = new DOMParser().parseFromString("<ui />")
root = xpath.select("/ui", ui)[0]
fns = {}
bind = (ob) ->
uid = (""+Math.random()).substr(2)
fns[uid] = ob
uid
root.setAttribute("bind", bind(-> console.log "wow"))
console.log fns[root.getAttribute("bind")]();
console.log new XMLSerializer().serializeToString(ui)
| 121480 |
Entity = {
as: {
}
}
App = Object.create(Entity)
Router = Object.create(Entity)
App.as.web = 1;
console.log Router.as
{DOMParser, XMLSerializer} = require('xmldom')
xpath = require('xpath')
xml = "<book><title><NAME></title></book>"
doc = new DOMParser().parseFromString(xml)
nodes = xpath.select(".//title", doc)
console.log(nodes[0].localName + ": " + nodes[0].firstChild.data)
console.log("node: " + nodes[0].toString())
ui = new DOMParser().parseFromString("<ui />")
root = xpath.select("/ui", ui)[0]
fns = {}
bind = (ob) ->
uid = (""+Math.random()).substr(2)
fns[uid] = ob
uid
root.setAttribute("bind", bind(-> console.log "wow"))
console.log fns[root.getAttribute("bind")]();
console.log new XMLSerializer().serializeToString(ui)
| true |
Entity = {
as: {
}
}
App = Object.create(Entity)
Router = Object.create(Entity)
App.as.web = 1;
console.log Router.as
{DOMParser, XMLSerializer} = require('xmldom')
xpath = require('xpath')
xml = "<book><title>PI:NAME:<NAME>END_PI</title></book>"
doc = new DOMParser().parseFromString(xml)
nodes = xpath.select(".//title", doc)
console.log(nodes[0].localName + ": " + nodes[0].firstChild.data)
console.log("node: " + nodes[0].toString())
ui = new DOMParser().parseFromString("<ui />")
root = xpath.select("/ui", ui)[0]
fns = {}
bind = (ob) ->
uid = (""+Math.random()).substr(2)
fns[uid] = ob
uid
root.setAttribute("bind", bind(-> console.log "wow"))
console.log fns[root.getAttribute("bind")]();
console.log new XMLSerializer().serializeToString(ui)
|
[
{
"context": "-ifVFkNLoe1TSUrNFQVj6jRbK1L8V-eZa-ngsZLM\"\n d: \"dI5TRpZrVLpTr_xxYK-n8FgTBpe5Uer-8QgHu5gx9Ds\"\nsampleKey2",
"end": 308,
"score": 0.8146893978118896,
"start": 303,
"tag": "KEY",
"value": "dI5TR"
},
{
"context": "NLoe1TSUrNFQVj6jRbK1L8V-eZa-ngsZLM\"\n d: \"dI5TRpZrVLpTr_xxYK-n8FgTBpe5Uer-8QgHu5gx9Ds\"\nsampleKey2 =\n",
"end": 311,
"score": 0.5062457919120789,
"start": 309,
"tag": "KEY",
"value": "Zr"
},
{
"context": "6jRbK1L8V-eZa-ngsZLM\"\n d: \"dI5TRpZrVLpTr_xxYK-n8FgTBpe5Uer-8QgHu5gx9Ds\"\nsampleKey2 =\n kty: \"oct\"\n",
"end": 326,
"score": 0.6655008792877197,
"start": 323,
"tag": "KEY",
"value": "8Fg"
},
{
"context": "testKey2\"\n use: \"sig\"\n alg: \"HS256\"\n k: \"l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg\"\nsampleKey3 =\n kty: \"oct\"\n kid: \"testKey3\"\n",
"end": 490,
"score": 0.9997571110725403,
"start": 436,
"tag": "KEY",
"value": "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg"
},
{
"context": "testKey3\"\n use: \"enc\"\n alg: \"HS256\"\n k: \"l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg\"\nsampleKeySet = keys: [ sampleKey1 ]\n\ntestLoaderK",
"end": 634,
"score": 0.9997549653053284,
"start": 580,
"tag": "KEY",
"value": "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg"
}
] | test/jwksTest.coffee | yoans/jwk | 0 | expect = require("chai").expect
JWKS = require "../lib"
path = require "path"
Promise = require "bluebird"
jose = JWKS.jose
sampleKey1 =
kty: "EC"
kid: "testKey1"
crv: "P-256"
x: "uiOfViX69jYwnygrkPkuM0XqUlvW65WEs_7rgT3eaak"
y: "v8S-ifVFkNLoe1TSUrNFQVj6jRbK1L8V-eZa-ngsZLM"
d: "dI5TRpZrVLpTr_xxYK-n8FgTBpe5Uer-8QgHu5gx9Ds"
sampleKey2 =
kty: "oct"
kid: "testKey2"
use: "sig"
alg: "HS256"
k: "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg"
sampleKey3 =
kty: "oct"
kid: "testKey3"
use: "enc"
alg: "HS256"
k: "l3nZEgZCeX8XRwJdWyK3rGB8qwjhdY8vOkbIvh4lxTuMao9Y_--hdg"
sampleKeySet = keys: [ sampleKey1 ]
testLoaderKeySet = null
testLoader =
loadAsync: (check) -> return Promise.resolve value: testLoaderKeySet, loaded: check
reset: () ->
verifySampleKeySet = (keyset) ->
keys = keyset.all()
expect(keys.length).to.equal(1)
key = keys[0]
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey1)
describe "JWKS", () ->
it "should construct with correct defaults", () ->
t = new JWKS
expect(t.rememberedKeys).to.deep.equal([])
expect(t.doNotReloadOnMissingKey).to.equal(false)
it "should construct with correct overrides", () ->
t = new JWKS
doNotReloadOnMissingKey: true
expect(t.rememberedKeys).to.deep.equal([])
expect(t.doNotReloadOnMissingKey).to.equal(true)
it "should construct with a url", () ->
t = new JWKS url: "https://jwks.example.com/foo"
# todo: More complete verification here
expect(t.loader.childLoader.url).to.equal("https://jwks.example.com/foo")
it "should construct with a file", () ->
t = new JWKS file: "foo.txt"
# todo: More complete verification here
expect(t.loader.file).to.equal(path.resolve("foo.txt"))
it "should allow us to override json to false for URLs (processor required)", () ->
t = new JWKS url: "https://jwks.example.com/foo", loaderOptions: requestDefaults: json: false
# todo: More complete verification here
expect(t.loader.childLoader.url).to.equal("https://jwks.example.com/foo")
describe "Remembered Keys", () ->
it "Should remember tagged keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
keys = t.jwks.get kid: "testKey2"
expect(keys).to.equal(key)
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey2)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) ->
keys = keystore.all()
expect(keys.length).to.equal(2)
newKey = keystore.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
newKey = keystore.get kid: "testKey1"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should forget remembered keys on reset if requested", (done) ->
t = new JWKS
t.loadAsync()
.then () -> t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
t.reset(true)
expect(t.jwks).to.equal(null)
expect(t.rememberedKeys).to.deep.equal([])
.then () -> done()
.catch done
it "Should not forget remembered keys on reset if not requested", (done) ->
t = new JWKS
t.loadAsync()
.then () -> t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
t.reset()
expect(t.jwks).to.equal(null)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should remember not remember untagged keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2, false
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) -> verifySampleKeySet keystore
.then () -> done()
.catch done
it "Should not remember removed keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.removeKeyAsync key
.then () ->
expect(t.jwks.all().length).to.equal(0)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) -> verifySampleKeySet keystore
.then () -> done()
.catch done
it "Should keep remember value during replace (remember=true)", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.replaceKeyAsync key, sampleKey3
.then (key) ->
newKey = t.jwks.get kid: "testKey3"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey3)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should keep remember value during replace (remember=false)", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2, false
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.replaceKeyAsync key, sampleKey3
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey3"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey3)
.then () -> done()
.catch done
describe "Retrieve Key", () ->
it "Should be able to get a key", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then () -> t.getKeyAsync kid: "testKey2"
.then (key) ->
expect(key).to.be.ok
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey2)
.then () -> done()
.catch done
it "Should return falsey if key not found", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then () -> t.getKeyAsync kid: "testKey999999"
.then (key) -> expect(key).to.not.be.ok
.then () -> done()
.catch done
it "Should attempt to reload keystore if the key is not found", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.getKeyAsync kid: "testKey1"
.then (key) ->
expect(key).to.be.ok
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should NOT attempt to reload keystore if doNotReloadOnMissingKey is set", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader, doNotReloadOnMissingKey: true
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.getKeyAsync kid: "testKey1"
.then (key) -> expect(key).to.not.be.ok
.then () -> done()
.catch done
describe "Retrieve All Matching Key", () ->
it "Should be able to get matching key", (done) ->
t = new JWKS
k1 = k2 = null
t.addKeyAsync sampleKey2
.then (rv) ->
k1 = rv
t.addKeyAsync sampleKey3
.then (rv) ->
k2 = rv
t.allKeysAsync kid: "testKey2"
.then (keys) ->
expect(keys).to.deep.equals([k1])
t.allKeysAsync kty: "oct"
.then (keys) ->
expect(keys).to.deep.equals([k1, k2])
t.allKeysAsync kid: "testKey999999"
.then (keys) ->
expect(keys).to.deep.equals([])
.then () -> done()
.catch done
it "Should attempt to reload keystore if the key is not found", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.allKeysAsync kid: "testKey1"
.then (keys) ->
expect(keys).to.be.ok
expect(keys.length).to.equal(1)
expect(jose.JWK.isKey(keys[0])).to.be.true
expect(keys[0].toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should NOT attempt to reload keystore if doNotReloadOnMissingKey is set", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader, doNotReloadOnMissingKey: true
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.allKeysAsync kid: "testKey1"
.then (keys) -> expect(keys).to.deep.equal([])
.then () -> done()
.catch done
it "Should generate remembered keys", (done) ->
t = new JWKS
t.generateKeyAsync "oct", 256, kid: "testGen1"
.then (key) ->
t.getKeyAsync kid: "testGen1"
.then (key2) ->
expect(key2).to.equal(key)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should generate non-remembered keys", (done) ->
t = new JWKS
t.generateKeyAsync "oct", 256, kid: "testGen1", false
.then (key) ->
t.getKeyAsync kid: "testGen1"
.then (key2) ->
expect(key2).to.equal(key)
expect(t.rememberedKeys).to.deep.equal([])
.then () -> done()
.catch done
it "Should export to JSON", (done) ->
t = new JWKS jwks: sampleKeySet
t.toJsonAsync true
.then (rv) -> expect(rv).to.deep.equal(sampleKeySet)
.then () -> done()
.catch done
| 128556 | expect = require("chai").expect
JWKS = require "../lib"
path = require "path"
Promise = require "bluebird"
jose = JWKS.jose
sampleKey1 =
kty: "EC"
kid: "testKey1"
crv: "P-256"
x: "uiOfViX69jYwnygrkPkuM0XqUlvW65WEs_7rgT3eaak"
y: "v8S-ifVFkNLoe1TSUrNFQVj6jRbK1L8V-eZa-ngsZLM"
d: "<KEY>p<KEY>VLpTr_xxYK-n<KEY>TBpe5Uer-8QgHu5gx9Ds"
sampleKey2 =
kty: "oct"
kid: "testKey2"
use: "sig"
alg: "HS256"
k: "<KEY>"
sampleKey3 =
kty: "oct"
kid: "testKey3"
use: "enc"
alg: "HS256"
k: "<KEY>"
sampleKeySet = keys: [ sampleKey1 ]
testLoaderKeySet = null
testLoader =
loadAsync: (check) -> return Promise.resolve value: testLoaderKeySet, loaded: check
reset: () ->
verifySampleKeySet = (keyset) ->
keys = keyset.all()
expect(keys.length).to.equal(1)
key = keys[0]
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey1)
describe "JWKS", () ->
it "should construct with correct defaults", () ->
t = new JWKS
expect(t.rememberedKeys).to.deep.equal([])
expect(t.doNotReloadOnMissingKey).to.equal(false)
it "should construct with correct overrides", () ->
t = new JWKS
doNotReloadOnMissingKey: true
expect(t.rememberedKeys).to.deep.equal([])
expect(t.doNotReloadOnMissingKey).to.equal(true)
it "should construct with a url", () ->
t = new JWKS url: "https://jwks.example.com/foo"
# todo: More complete verification here
expect(t.loader.childLoader.url).to.equal("https://jwks.example.com/foo")
it "should construct with a file", () ->
t = new JWKS file: "foo.txt"
# todo: More complete verification here
expect(t.loader.file).to.equal(path.resolve("foo.txt"))
it "should allow us to override json to false for URLs (processor required)", () ->
t = new JWKS url: "https://jwks.example.com/foo", loaderOptions: requestDefaults: json: false
# todo: More complete verification here
expect(t.loader.childLoader.url).to.equal("https://jwks.example.com/foo")
describe "Remembered Keys", () ->
it "Should remember tagged keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
keys = t.jwks.get kid: "testKey2"
expect(keys).to.equal(key)
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey2)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) ->
keys = keystore.all()
expect(keys.length).to.equal(2)
newKey = keystore.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
newKey = keystore.get kid: "testKey1"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should forget remembered keys on reset if requested", (done) ->
t = new JWKS
t.loadAsync()
.then () -> t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
t.reset(true)
expect(t.jwks).to.equal(null)
expect(t.rememberedKeys).to.deep.equal([])
.then () -> done()
.catch done
it "Should not forget remembered keys on reset if not requested", (done) ->
t = new JWKS
t.loadAsync()
.then () -> t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
t.reset()
expect(t.jwks).to.equal(null)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should remember not remember untagged keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2, false
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) -> verifySampleKeySet keystore
.then () -> done()
.catch done
it "Should not remember removed keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.removeKeyAsync key
.then () ->
expect(t.jwks.all().length).to.equal(0)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) -> verifySampleKeySet keystore
.then () -> done()
.catch done
it "Should keep remember value during replace (remember=true)", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.replaceKeyAsync key, sampleKey3
.then (key) ->
newKey = t.jwks.get kid: "testKey3"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey3)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should keep remember value during replace (remember=false)", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2, false
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.replaceKeyAsync key, sampleKey3
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey3"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey3)
.then () -> done()
.catch done
describe "Retrieve Key", () ->
it "Should be able to get a key", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then () -> t.getKeyAsync kid: "testKey2"
.then (key) ->
expect(key).to.be.ok
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey2)
.then () -> done()
.catch done
it "Should return falsey if key not found", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then () -> t.getKeyAsync kid: "testKey999999"
.then (key) -> expect(key).to.not.be.ok
.then () -> done()
.catch done
it "Should attempt to reload keystore if the key is not found", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.getKeyAsync kid: "testKey1"
.then (key) ->
expect(key).to.be.ok
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should NOT attempt to reload keystore if doNotReloadOnMissingKey is set", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader, doNotReloadOnMissingKey: true
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.getKeyAsync kid: "testKey1"
.then (key) -> expect(key).to.not.be.ok
.then () -> done()
.catch done
describe "Retrieve All Matching Key", () ->
it "Should be able to get matching key", (done) ->
t = new JWKS
k1 = k2 = null
t.addKeyAsync sampleKey2
.then (rv) ->
k1 = rv
t.addKeyAsync sampleKey3
.then (rv) ->
k2 = rv
t.allKeysAsync kid: "testKey2"
.then (keys) ->
expect(keys).to.deep.equals([k1])
t.allKeysAsync kty: "oct"
.then (keys) ->
expect(keys).to.deep.equals([k1, k2])
t.allKeysAsync kid: "testKey999999"
.then (keys) ->
expect(keys).to.deep.equals([])
.then () -> done()
.catch done
it "Should attempt to reload keystore if the key is not found", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.allKeysAsync kid: "testKey1"
.then (keys) ->
expect(keys).to.be.ok
expect(keys.length).to.equal(1)
expect(jose.JWK.isKey(keys[0])).to.be.true
expect(keys[0].toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should NOT attempt to reload keystore if doNotReloadOnMissingKey is set", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader, doNotReloadOnMissingKey: true
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.allKeysAsync kid: "testKey1"
.then (keys) -> expect(keys).to.deep.equal([])
.then () -> done()
.catch done
it "Should generate remembered keys", (done) ->
t = new JWKS
t.generateKeyAsync "oct", 256, kid: "testGen1"
.then (key) ->
t.getKeyAsync kid: "testGen1"
.then (key2) ->
expect(key2).to.equal(key)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should generate non-remembered keys", (done) ->
t = new JWKS
t.generateKeyAsync "oct", 256, kid: "testGen1", false
.then (key) ->
t.getKeyAsync kid: "testGen1"
.then (key2) ->
expect(key2).to.equal(key)
expect(t.rememberedKeys).to.deep.equal([])
.then () -> done()
.catch done
it "Should export to JSON", (done) ->
t = new JWKS jwks: sampleKeySet
t.toJsonAsync true
.then (rv) -> expect(rv).to.deep.equal(sampleKeySet)
.then () -> done()
.catch done
| true | expect = require("chai").expect
JWKS = require "../lib"
path = require "path"
Promise = require "bluebird"
jose = JWKS.jose
sampleKey1 =
kty: "EC"
kid: "testKey1"
crv: "P-256"
x: "uiOfViX69jYwnygrkPkuM0XqUlvW65WEs_7rgT3eaak"
y: "v8S-ifVFkNLoe1TSUrNFQVj6jRbK1L8V-eZa-ngsZLM"
d: "PI:KEY:<KEY>END_PIpPI:KEY:<KEY>END_PIVLpTr_xxYK-nPI:KEY:<KEY>END_PITBpe5Uer-8QgHu5gx9Ds"
sampleKey2 =
kty: "oct"
kid: "testKey2"
use: "sig"
alg: "HS256"
k: "PI:KEY:<KEY>END_PI"
sampleKey3 =
kty: "oct"
kid: "testKey3"
use: "enc"
alg: "HS256"
k: "PI:KEY:<KEY>END_PI"
sampleKeySet = keys: [ sampleKey1 ]
testLoaderKeySet = null
testLoader =
loadAsync: (check) -> return Promise.resolve value: testLoaderKeySet, loaded: check
reset: () ->
verifySampleKeySet = (keyset) ->
keys = keyset.all()
expect(keys.length).to.equal(1)
key = keys[0]
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey1)
describe "JWKS", () ->
it "should construct with correct defaults", () ->
t = new JWKS
expect(t.rememberedKeys).to.deep.equal([])
expect(t.doNotReloadOnMissingKey).to.equal(false)
it "should construct with correct overrides", () ->
t = new JWKS
doNotReloadOnMissingKey: true
expect(t.rememberedKeys).to.deep.equal([])
expect(t.doNotReloadOnMissingKey).to.equal(true)
it "should construct with a url", () ->
t = new JWKS url: "https://jwks.example.com/foo"
# todo: More complete verification here
expect(t.loader.childLoader.url).to.equal("https://jwks.example.com/foo")
it "should construct with a file", () ->
t = new JWKS file: "foo.txt"
# todo: More complete verification here
expect(t.loader.file).to.equal(path.resolve("foo.txt"))
it "should allow us to override json to false for URLs (processor required)", () ->
t = new JWKS url: "https://jwks.example.com/foo", loaderOptions: requestDefaults: json: false
# todo: More complete verification here
expect(t.loader.childLoader.url).to.equal("https://jwks.example.com/foo")
describe "Remembered Keys", () ->
it "Should remember tagged keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
keys = t.jwks.get kid: "testKey2"
expect(keys).to.equal(key)
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey2)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) ->
keys = keystore.all()
expect(keys.length).to.equal(2)
newKey = keystore.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
newKey = keystore.get kid: "testKey1"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should forget remembered keys on reset if requested", (done) ->
t = new JWKS
t.loadAsync()
.then () -> t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
t.reset(true)
expect(t.jwks).to.equal(null)
expect(t.rememberedKeys).to.deep.equal([])
.then () -> done()
.catch done
it "Should not forget remembered keys on reset if not requested", (done) ->
t = new JWKS
t.loadAsync()
.then () -> t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
t.reset()
expect(t.jwks).to.equal(null)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should remember not remember untagged keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2, false
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) -> verifySampleKeySet keystore
.then () -> done()
.catch done
it "Should not remember removed keys", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.removeKeyAsync key
.then () ->
expect(t.jwks.all().length).to.equal(0)
testLoaderKeySet = sampleKeySet
t.loadAsync true
.then (keystore) -> verifySampleKeySet keystore
.then () -> done()
.catch done
it "Should keep remember value during replace (remember=true)", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([key])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.replaceKeyAsync key, sampleKey3
.then (key) ->
newKey = t.jwks.get kid: "testKey3"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey3)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should keep remember value during replace (remember=false)", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2, false
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey2"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey2)
t.replaceKeyAsync key, sampleKey3
.then (key) ->
expect(t.rememberedKeys).to.deep.equal([])
newKey = t.jwks.get kid: "testKey3"
expect(newKey).to.be.ok
expect(jose.JWK.isKey(newKey)).to.be.true
expect(newKey.toJSON(true)).to.deep.equals(sampleKey3)
.then () -> done()
.catch done
describe "Retrieve Key", () ->
it "Should be able to get a key", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then () -> t.getKeyAsync kid: "testKey2"
.then (key) ->
expect(key).to.be.ok
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey2)
.then () -> done()
.catch done
it "Should return falsey if key not found", (done) ->
t = new JWKS
t.addKeyAsync sampleKey2
.then () -> t.getKeyAsync kid: "testKey999999"
.then (key) -> expect(key).to.not.be.ok
.then () -> done()
.catch done
it "Should attempt to reload keystore if the key is not found", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.getKeyAsync kid: "testKey1"
.then (key) ->
expect(key).to.be.ok
expect(jose.JWK.isKey(key)).to.be.true
expect(key.toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should NOT attempt to reload keystore if doNotReloadOnMissingKey is set", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader, doNotReloadOnMissingKey: true
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.getKeyAsync kid: "testKey1"
.then (key) -> expect(key).to.not.be.ok
.then () -> done()
.catch done
describe "Retrieve All Matching Key", () ->
it "Should be able to get matching key", (done) ->
t = new JWKS
k1 = k2 = null
t.addKeyAsync sampleKey2
.then (rv) ->
k1 = rv
t.addKeyAsync sampleKey3
.then (rv) ->
k2 = rv
t.allKeysAsync kid: "testKey2"
.then (keys) ->
expect(keys).to.deep.equals([k1])
t.allKeysAsync kty: "oct"
.then (keys) ->
expect(keys).to.deep.equals([k1, k2])
t.allKeysAsync kid: "testKey999999"
.then (keys) ->
expect(keys).to.deep.equals([])
.then () -> done()
.catch done
it "Should attempt to reload keystore if the key is not found", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.allKeysAsync kid: "testKey1"
.then (keys) ->
expect(keys).to.be.ok
expect(keys.length).to.equal(1)
expect(jose.JWK.isKey(keys[0])).to.be.true
expect(keys[0].toJSON(true)).to.deep.equals(sampleKey1)
.then () -> done()
.catch done
it "Should NOT attempt to reload keystore if doNotReloadOnMissingKey is set", (done) ->
testLoaderKeySet = keys: []
t = new JWKS loader: testLoader, doNotReloadOnMissingKey: true
t.loadAsync()
.then () ->
testLoaderKeySet = sampleKeySet
# This should now not find the key, refresh, and then find the key
t.allKeysAsync kid: "testKey1"
.then (keys) -> expect(keys).to.deep.equal([])
.then () -> done()
.catch done
it "Should generate remembered keys", (done) ->
t = new JWKS
t.generateKeyAsync "oct", 256, kid: "testGen1"
.then (key) ->
t.getKeyAsync kid: "testGen1"
.then (key2) ->
expect(key2).to.equal(key)
expect(t.rememberedKeys).to.deep.equal([key])
.then () -> done()
.catch done
it "Should generate non-remembered keys", (done) ->
t = new JWKS
t.generateKeyAsync "oct", 256, kid: "testGen1", false
.then (key) ->
t.getKeyAsync kid: "testGen1"
.then (key2) ->
expect(key2).to.equal(key)
expect(t.rememberedKeys).to.deep.equal([])
.then () -> done()
.catch done
it "Should export to JSON", (done) ->
t = new JWKS jwks: sampleKeySet
t.toJsonAsync true
.then (rv) -> expect(rv).to.deep.equal(sampleKeySet)
.then () -> done()
.catch done
|
[
{
"context": "null\ndeliverStub = null\n\nbefore () ->\n apiKey = \"71ab53572c7b45316fb894d496f2e11d\"\n Bugsnag.register apiKey, notifyReleaseStages: ",
"end": 247,
"score": 0.9997733235359192,
"start": 215,
"tag": "KEY",
"value": "71ab53572c7b45316fb894d496f2e11d"
}
] | test/bugsnag.coffee | wennergr2/bugsnag-node | 0 | domain = require "domain"
should = require("chai").should()
sinon = require("sinon")
Bugsnag = require "../"
Notification = require "../lib/notification"
apiKey = null
deliverStub = null
before () ->
apiKey = "71ab53572c7b45316fb894d496f2e11d"
Bugsnag.register apiKey, notifyReleaseStages: ["production", "development"]
describe "Bugsnag", ->
beforeEach () -> deliverStub = sinon.stub(Notification.prototype, "deliver")
afterEach () -> Notification.prototype.deliver.restore()
it "should call deliver when notifying a caught error", ->
try
throw new Error("This is the message")
catch e
Bugsnag.notify(e)
deliverStub.calledOnce.should.equal true
it "should call deliver when notifying an event emitter error", ->
eventEmitter = new (require('events').EventEmitter)()
eventEmitter.on "error", Bugsnag.notify
eventEmitter.emit "error", "Something went wrong"
deliverStub.calledOnce.should.equal true
it "should call deliver when notifying with a domain, using event emitter", ->
mainDomain = domain.create()
mainDomain.on "error", Bugsnag.notify
mainDomain.run ->
eventEmitter = new (require('events').EventEmitter)()
eventEmitter.emit "error", new Error("Something went wrong")
deliverStub.calledOnce.should.equal true
describe "Bugsnag", ->
describe "Notification.deliver", ->
it "should call the callback after notifying bugsnag", (done) ->
Bugsnag.notify("error message", done)
it "should call callback when releaseStage isnt configured in notifyReleaseStages", (done) ->
oldNotifyReleaseStagesValue = Bugsnag.notifyReleaseStages
Bugsnag.notifyReleaseStages = ["production"]
Bugsnag.notify("This is the message", done)
Bugsnag.notifyReleaseStages = oldNotifyReleaseStagesValue
| 205330 | domain = require "domain"
should = require("chai").should()
sinon = require("sinon")
Bugsnag = require "../"
Notification = require "../lib/notification"
apiKey = null
deliverStub = null
before () ->
apiKey = "<KEY>"
Bugsnag.register apiKey, notifyReleaseStages: ["production", "development"]
describe "Bugsnag", ->
beforeEach () -> deliverStub = sinon.stub(Notification.prototype, "deliver")
afterEach () -> Notification.prototype.deliver.restore()
it "should call deliver when notifying a caught error", ->
try
throw new Error("This is the message")
catch e
Bugsnag.notify(e)
deliverStub.calledOnce.should.equal true
it "should call deliver when notifying an event emitter error", ->
eventEmitter = new (require('events').EventEmitter)()
eventEmitter.on "error", Bugsnag.notify
eventEmitter.emit "error", "Something went wrong"
deliverStub.calledOnce.should.equal true
it "should call deliver when notifying with a domain, using event emitter", ->
mainDomain = domain.create()
mainDomain.on "error", Bugsnag.notify
mainDomain.run ->
eventEmitter = new (require('events').EventEmitter)()
eventEmitter.emit "error", new Error("Something went wrong")
deliverStub.calledOnce.should.equal true
describe "Bugsnag", ->
describe "Notification.deliver", ->
it "should call the callback after notifying bugsnag", (done) ->
Bugsnag.notify("error message", done)
it "should call callback when releaseStage isnt configured in notifyReleaseStages", (done) ->
oldNotifyReleaseStagesValue = Bugsnag.notifyReleaseStages
Bugsnag.notifyReleaseStages = ["production"]
Bugsnag.notify("This is the message", done)
Bugsnag.notifyReleaseStages = oldNotifyReleaseStagesValue
| true | domain = require "domain"
should = require("chai").should()
sinon = require("sinon")
Bugsnag = require "../"
Notification = require "../lib/notification"
apiKey = null
deliverStub = null
before () ->
apiKey = "PI:KEY:<KEY>END_PI"
Bugsnag.register apiKey, notifyReleaseStages: ["production", "development"]
describe "Bugsnag", ->
beforeEach () -> deliverStub = sinon.stub(Notification.prototype, "deliver")
afterEach () -> Notification.prototype.deliver.restore()
it "should call deliver when notifying a caught error", ->
try
throw new Error("This is the message")
catch e
Bugsnag.notify(e)
deliverStub.calledOnce.should.equal true
it "should call deliver when notifying an event emitter error", ->
eventEmitter = new (require('events').EventEmitter)()
eventEmitter.on "error", Bugsnag.notify
eventEmitter.emit "error", "Something went wrong"
deliverStub.calledOnce.should.equal true
it "should call deliver when notifying with a domain, using event emitter", ->
mainDomain = domain.create()
mainDomain.on "error", Bugsnag.notify
mainDomain.run ->
eventEmitter = new (require('events').EventEmitter)()
eventEmitter.emit "error", new Error("Something went wrong")
deliverStub.calledOnce.should.equal true
describe "Bugsnag", ->
describe "Notification.deliver", ->
it "should call the callback after notifying bugsnag", (done) ->
Bugsnag.notify("error message", done)
it "should call callback when releaseStage isnt configured in notifyReleaseStages", (done) ->
oldNotifyReleaseStagesValue = Bugsnag.notifyReleaseStages
Bugsnag.notifyReleaseStages = ["production"]
Bugsnag.notify("This is the message", done)
Bugsnag.notifyReleaseStages = oldNotifyReleaseStagesValue
|
[
{
"context": "provide ACL Token via private message.\n\n\ntoken = \"Consul Master Token\"\nurl = \"http://consul_url:8500\"\n\nmodule.exports =",
"end": 179,
"score": 0.8215358853340149,
"start": 160,
"tag": "PASSWORD",
"value": "Consul Master Token"
}
] | consul.coffee | apsega/hubot-consul | 0 | # To register new ACL:
# @hubot register nginx on nginx001
# Hubot will register ACL defined in #{data} and provide ACL Token via private message.
token = "Consul Master Token"
url = "http://consul_url:8500"
module.exports = (robot) ->
robot.hear /@hubot register (.*) on (.*)/i, (res) ->
res.reply "Registering `#{res.match[1]}` service for nodes that are starting with `#{res.match[2]}*`. Token will be sent to you via PM."
sender = res.message.user.name.toLowerCase()
data = JSON.stringify({
"Name": "#{res.match[1]} - #{sender}",
"Type": "client",
"Rules": "agent \"#{res.match[2]}\" {\n policy = \"write\"\n}\nservice \"#{res.match[1]}\" {\n policy = \"write\"\n}\nnode \"#{res.match[2]}\" {\n policy = \"write\"\n}"
});
robot.http("#{url}/v1/acl/create?token=#{token}")
.put(data) (err, response, body) ->
token = JSON.parse body
robot.messageRoom("@#{sender}", "Your token for `#{res.match[1]}` service is `#{token.ID}`")
| 108983 | # To register new ACL:
# @hubot register nginx on nginx001
# Hubot will register ACL defined in #{data} and provide ACL Token via private message.
token = "<PASSWORD>"
url = "http://consul_url:8500"
module.exports = (robot) ->
robot.hear /@hubot register (.*) on (.*)/i, (res) ->
res.reply "Registering `#{res.match[1]}` service for nodes that are starting with `#{res.match[2]}*`. Token will be sent to you via PM."
sender = res.message.user.name.toLowerCase()
data = JSON.stringify({
"Name": "#{res.match[1]} - #{sender}",
"Type": "client",
"Rules": "agent \"#{res.match[2]}\" {\n policy = \"write\"\n}\nservice \"#{res.match[1]}\" {\n policy = \"write\"\n}\nnode \"#{res.match[2]}\" {\n policy = \"write\"\n}"
});
robot.http("#{url}/v1/acl/create?token=#{token}")
.put(data) (err, response, body) ->
token = JSON.parse body
robot.messageRoom("@#{sender}", "Your token for `#{res.match[1]}` service is `#{token.ID}`")
| true | # To register new ACL:
# @hubot register nginx on nginx001
# Hubot will register ACL defined in #{data} and provide ACL Token via private message.
token = "PI:PASSWORD:<PASSWORD>END_PI"
url = "http://consul_url:8500"
module.exports = (robot) ->
robot.hear /@hubot register (.*) on (.*)/i, (res) ->
res.reply "Registering `#{res.match[1]}` service for nodes that are starting with `#{res.match[2]}*`. Token will be sent to you via PM."
sender = res.message.user.name.toLowerCase()
data = JSON.stringify({
"Name": "#{res.match[1]} - #{sender}",
"Type": "client",
"Rules": "agent \"#{res.match[2]}\" {\n policy = \"write\"\n}\nservice \"#{res.match[1]}\" {\n policy = \"write\"\n}\nnode \"#{res.match[2]}\" {\n policy = \"write\"\n}"
});
robot.http("#{url}/v1/acl/create?token=#{token}")
.put(data) (err, response, body) ->
token = JSON.parse body
robot.messageRoom("@#{sender}", "Your token for `#{res.match[1]}` service is `#{token.ID}`")
|
[
{
"context": "() * 1000000000).toString()\n\n params.password = params.attendeePW\n joinAtt = @urlFor(\"join\", params)\n joinAtt",
"end": 2750,
"score": 0.9988980293273926,
"start": 2733,
"tag": "PASSWORD",
"value": "params.attendeePW"
},
{
"context": "eplaceMobileProtocol joinAtt\n params.password = params.moderatorPW\n joinMod = @urlFor(\"join\", params)\n joinMod",
"end": 2880,
"score": 0.9992448091506958,
"start": 2862,
"tag": "PASSWORD",
"value": "params.moderatorPW"
},
{
"context": "Mod\n # for all other urls, the password will be moderatorPW\n\n ret =\n\n # standard API\n 'create': ",
"end": 3028,
"score": 0.8763388991355896,
"start": 3017,
"tag": "PASSWORD",
"value": "moderatorPW"
}
] | src/bigbluebutton-api.coffee | bigbluebutton/bigbluebutton-api-js | 1 | root = exports ? this
class BigBlueButtonApi
constructor: (url, salt, mobileKey) ->
@url = url
@salt = salt
@mobileKey = mobileKey
# Returns a list of supported parameters for a given API method
# The return is an array of arrays composed by:
# [0] - RegEx or string with the parameter name
# [1] - true if the parameter is required
paramsFor: (param) ->
switch param
when "create"
[ [ "meetingID", true ]
[ "name", true ],
[ "attendeePW", false ] ,
[ "moderatorPW", false ],
[ "welcome", false ],
[ "dialNumber", false ],
[ "voiceBridge", false ],
[ "webVoice", false ],
[ "logoutURL", false ],
[ "maxParticipants", false ],
[ "record", false ],
[ "duration", false ]
[ /meta_\w+/, false ],
]
when "join"
[ [ "fullName", true ]
[ "meetingID", true ],
[ "password", true ] ,
[ "createTime", false ],
[ "userID", false ],
[ "webVoiceConf", false ],
]
when "isMeetingRunning"
[ [ "meetingID", true ] ]
when "end"
[ [ "meetingID", true ]
[ "password", true ],
]
when "getMeetingInfo"
[ [ "meetingID", true ]
[ "password", true ],
]
when "getMeetings"
[ [ "random", true ] ]
when "getRecordings"
[ [ "meetingID", true ] ]
when "publishRecordings"
[ [ "recordID", true ],
[ "publish", true ]
]
when "deleteRecordings"
[ [ "recordID", true ] ]
# Filter `params` to allow only parameters that can be passed
# to the method `method`.
# To allow custom parameters, name them `custom_parameterName`.
# The `custom_` prefix will be removed when generating the urls.
filterParams: (params, method) ->
filters = @paramsFor(method)
if not filters? or filters.length is 0
{}
else
r = include params, (key, value) ->
for filter in filters
if filter[0] instanceof RegExp
return true if key.match(filter[0]) or key.match(/^custom_/)
else
return true if key.match("^#{filter[0]}$") or key.match(/^custom_/)
return false
# creates keys without "custom_" and deletes the ones with it
for key, v of r
r[key.replace(/^custom_/, "")] = v if key.match(/^custom_/)
for key of r
delete r[key] if key.match(/^custom_/)
r
# Returns an object with URLs to all methods in BigBlueButton' API.
getUrls: (params) ->
params ?= {}
params.random = Math.floor(Math.random() * 1000000000).toString()
params.password = params.attendeePW
joinAtt = @urlFor("join", params)
joinAttMobile = @replaceMobileProtocol joinAtt
params.password = params.moderatorPW
joinMod = @urlFor("join", params)
joinModMobile = @replaceMobileProtocol joinMod
# for all other urls, the password will be moderatorPW
ret =
# standard API
'create': @urlFor("create", params)
'join (as moderator)': joinMod
'join (as attendee)': joinAtt
'isMeetingRunning': @urlFor("isMeetingRunning", params)
'getMeetingInfo': @urlFor("getMeetingInfo", params)
'end': @urlFor("end", params)
'getMeetings': @urlFor("getMeetings", params)
'getRecordings': @urlFor("getRecordings", params)
'publishRecordings': @urlFor("publishRecordings", params)
'deleteRecordings': @urlFor("deleteRecordings", params)
# link to use in mobile devices
'join from mobile (as moderator)': joinModMobile
'join from mobile (as attendee)': joinAttMobile
# mobile API
'mobile: getTimestamp': @urlForMobileApi("getTimestamp", params)
'mobile: getMeetings': @urlForMobileApi("getMeetings", params)
'mobile: create': @urlForMobileApi("create", params)
# Returns a url for any `method` available in the BigBlueButton API
# using the parameters in `params`.
urlFor: (method, params) ->
params = @filterParams(params, method)
url = @url
# list of params
paramList = []
for key, param of params
if key? and param?
paramList.push "#{encodeURIComponent(key)}=#{encodeURIComponent(param)}"
query = paramList.join("&") if paramList.length > 0
# calculate the checksum
checksum = @checksum(method, query)
# add the missing elements in the query
if paramList.length > 0
query = method + "?" + query
query += "&"
else
query = method + "?"
query += "checksum=" + checksum
url + "/" + query
# Calls `urlFor` and changes the generated url to point
# to the mobile API.
urlForMobileApi: (method, params) ->
url = @urlFor method, params, true
# change the path
oldPat = new RegExp("bigbluebutton\\/api\\/" + method + "\\?")
url = url.replace(oldPat, "demo/mobile.jsp?action=" + method + "&")
# removes the old checksum to add a new one later
url = url.replace(/[&]?checksum=.*$/, "")
# add the timestamp and the checksum
unless url.match(/action=getTimestamp/)
url = url + "×tamp=" + new Date().getTime()
query = ""
matched = url.match(/\?(.*)$/)
query = matched[1] if matched? and matched[1]?
url = url + "&checksum=" + @checksum(method, query, true)
# Replaces the protocol for `bigbluebutton://`.
replaceMobileProtocol: (url) ->
url.replace(/http[s]?\:\/\//, "bigbluebutton://")
# Calculates the checksum for an API call `method` with
# the params in `query`.
checksum: (method, query, forMobile) ->
query ||= ""
if forMobile? and forMobile
str = query + @mobileKey
else
str = method + query + @salt
Crypto.SHA1(str)
# Ruby-like include() method for Objects
include = (input, _function) ->
_obj = new Object
_match = null
for key, value of input
if _function.call(input, key, value)
_obj[key] = value
_obj
root.BigBlueButtonApi = BigBlueButtonApi
| 67625 | root = exports ? this
class BigBlueButtonApi
constructor: (url, salt, mobileKey) ->
@url = url
@salt = salt
@mobileKey = mobileKey
# Returns a list of supported parameters for a given API method
# The return is an array of arrays composed by:
# [0] - RegEx or string with the parameter name
# [1] - true if the parameter is required
paramsFor: (param) ->
switch param
when "create"
[ [ "meetingID", true ]
[ "name", true ],
[ "attendeePW", false ] ,
[ "moderatorPW", false ],
[ "welcome", false ],
[ "dialNumber", false ],
[ "voiceBridge", false ],
[ "webVoice", false ],
[ "logoutURL", false ],
[ "maxParticipants", false ],
[ "record", false ],
[ "duration", false ]
[ /meta_\w+/, false ],
]
when "join"
[ [ "fullName", true ]
[ "meetingID", true ],
[ "password", true ] ,
[ "createTime", false ],
[ "userID", false ],
[ "webVoiceConf", false ],
]
when "isMeetingRunning"
[ [ "meetingID", true ] ]
when "end"
[ [ "meetingID", true ]
[ "password", true ],
]
when "getMeetingInfo"
[ [ "meetingID", true ]
[ "password", true ],
]
when "getMeetings"
[ [ "random", true ] ]
when "getRecordings"
[ [ "meetingID", true ] ]
when "publishRecordings"
[ [ "recordID", true ],
[ "publish", true ]
]
when "deleteRecordings"
[ [ "recordID", true ] ]
# Filter `params` to allow only parameters that can be passed
# to the method `method`.
# To allow custom parameters, name them `custom_parameterName`.
# The `custom_` prefix will be removed when generating the urls.
filterParams: (params, method) ->
filters = @paramsFor(method)
if not filters? or filters.length is 0
{}
else
r = include params, (key, value) ->
for filter in filters
if filter[0] instanceof RegExp
return true if key.match(filter[0]) or key.match(/^custom_/)
else
return true if key.match("^#{filter[0]}$") or key.match(/^custom_/)
return false
# creates keys without "custom_" and deletes the ones with it
for key, v of r
r[key.replace(/^custom_/, "")] = v if key.match(/^custom_/)
for key of r
delete r[key] if key.match(/^custom_/)
r
# Returns an object with URLs to all methods in BigBlueButton' API.
getUrls: (params) ->
params ?= {}
params.random = Math.floor(Math.random() * 1000000000).toString()
params.password = <PASSWORD>
joinAtt = @urlFor("join", params)
joinAttMobile = @replaceMobileProtocol joinAtt
params.password = <PASSWORD>
joinMod = @urlFor("join", params)
joinModMobile = @replaceMobileProtocol joinMod
# for all other urls, the password will be <PASSWORD>
ret =
# standard API
'create': @urlFor("create", params)
'join (as moderator)': joinMod
'join (as attendee)': joinAtt
'isMeetingRunning': @urlFor("isMeetingRunning", params)
'getMeetingInfo': @urlFor("getMeetingInfo", params)
'end': @urlFor("end", params)
'getMeetings': @urlFor("getMeetings", params)
'getRecordings': @urlFor("getRecordings", params)
'publishRecordings': @urlFor("publishRecordings", params)
'deleteRecordings': @urlFor("deleteRecordings", params)
# link to use in mobile devices
'join from mobile (as moderator)': joinModMobile
'join from mobile (as attendee)': joinAttMobile
# mobile API
'mobile: getTimestamp': @urlForMobileApi("getTimestamp", params)
'mobile: getMeetings': @urlForMobileApi("getMeetings", params)
'mobile: create': @urlForMobileApi("create", params)
# Returns a url for any `method` available in the BigBlueButton API
# using the parameters in `params`.
urlFor: (method, params) ->
params = @filterParams(params, method)
url = @url
# list of params
paramList = []
for key, param of params
if key? and param?
paramList.push "#{encodeURIComponent(key)}=#{encodeURIComponent(param)}"
query = paramList.join("&") if paramList.length > 0
# calculate the checksum
checksum = @checksum(method, query)
# add the missing elements in the query
if paramList.length > 0
query = method + "?" + query
query += "&"
else
query = method + "?"
query += "checksum=" + checksum
url + "/" + query
# Calls `urlFor` and changes the generated url to point
# to the mobile API.
urlForMobileApi: (method, params) ->
url = @urlFor method, params, true
# change the path
oldPat = new RegExp("bigbluebutton\\/api\\/" + method + "\\?")
url = url.replace(oldPat, "demo/mobile.jsp?action=" + method + "&")
# removes the old checksum to add a new one later
url = url.replace(/[&]?checksum=.*$/, "")
# add the timestamp and the checksum
unless url.match(/action=getTimestamp/)
url = url + "×tamp=" + new Date().getTime()
query = ""
matched = url.match(/\?(.*)$/)
query = matched[1] if matched? and matched[1]?
url = url + "&checksum=" + @checksum(method, query, true)
# Replaces the protocol for `bigbluebutton://`.
replaceMobileProtocol: (url) ->
url.replace(/http[s]?\:\/\//, "bigbluebutton://")
# Calculates the checksum for an API call `method` with
# the params in `query`.
checksum: (method, query, forMobile) ->
query ||= ""
if forMobile? and forMobile
str = query + @mobileKey
else
str = method + query + @salt
Crypto.SHA1(str)
# Ruby-like include() method for Objects
include = (input, _function) ->
_obj = new Object
_match = null
for key, value of input
if _function.call(input, key, value)
_obj[key] = value
_obj
root.BigBlueButtonApi = BigBlueButtonApi
| true | root = exports ? this
class BigBlueButtonApi
constructor: (url, salt, mobileKey) ->
@url = url
@salt = salt
@mobileKey = mobileKey
# Returns a list of supported parameters for a given API method
# The return is an array of arrays composed by:
# [0] - RegEx or string with the parameter name
# [1] - true if the parameter is required
paramsFor: (param) ->
switch param
when "create"
[ [ "meetingID", true ]
[ "name", true ],
[ "attendeePW", false ] ,
[ "moderatorPW", false ],
[ "welcome", false ],
[ "dialNumber", false ],
[ "voiceBridge", false ],
[ "webVoice", false ],
[ "logoutURL", false ],
[ "maxParticipants", false ],
[ "record", false ],
[ "duration", false ]
[ /meta_\w+/, false ],
]
when "join"
[ [ "fullName", true ]
[ "meetingID", true ],
[ "password", true ] ,
[ "createTime", false ],
[ "userID", false ],
[ "webVoiceConf", false ],
]
when "isMeetingRunning"
[ [ "meetingID", true ] ]
when "end"
[ [ "meetingID", true ]
[ "password", true ],
]
when "getMeetingInfo"
[ [ "meetingID", true ]
[ "password", true ],
]
when "getMeetings"
[ [ "random", true ] ]
when "getRecordings"
[ [ "meetingID", true ] ]
when "publishRecordings"
[ [ "recordID", true ],
[ "publish", true ]
]
when "deleteRecordings"
[ [ "recordID", true ] ]
# Filter `params` to allow only parameters that can be passed
# to the method `method`.
# To allow custom parameters, name them `custom_parameterName`.
# The `custom_` prefix will be removed when generating the urls.
filterParams: (params, method) ->
filters = @paramsFor(method)
if not filters? or filters.length is 0
{}
else
r = include params, (key, value) ->
for filter in filters
if filter[0] instanceof RegExp
return true if key.match(filter[0]) or key.match(/^custom_/)
else
return true if key.match("^#{filter[0]}$") or key.match(/^custom_/)
return false
# creates keys without "custom_" and deletes the ones with it
for key, v of r
r[key.replace(/^custom_/, "")] = v if key.match(/^custom_/)
for key of r
delete r[key] if key.match(/^custom_/)
r
# Returns an object with URLs to all methods in BigBlueButton' API.
getUrls: (params) ->
params ?= {}
params.random = Math.floor(Math.random() * 1000000000).toString()
params.password = PI:PASSWORD:<PASSWORD>END_PI
joinAtt = @urlFor("join", params)
joinAttMobile = @replaceMobileProtocol joinAtt
params.password = PI:PASSWORD:<PASSWORD>END_PI
joinMod = @urlFor("join", params)
joinModMobile = @replaceMobileProtocol joinMod
# for all other urls, the password will be PI:PASSWORD:<PASSWORD>END_PI
ret =
# standard API
'create': @urlFor("create", params)
'join (as moderator)': joinMod
'join (as attendee)': joinAtt
'isMeetingRunning': @urlFor("isMeetingRunning", params)
'getMeetingInfo': @urlFor("getMeetingInfo", params)
'end': @urlFor("end", params)
'getMeetings': @urlFor("getMeetings", params)
'getRecordings': @urlFor("getRecordings", params)
'publishRecordings': @urlFor("publishRecordings", params)
'deleteRecordings': @urlFor("deleteRecordings", params)
# link to use in mobile devices
'join from mobile (as moderator)': joinModMobile
'join from mobile (as attendee)': joinAttMobile
# mobile API
'mobile: getTimestamp': @urlForMobileApi("getTimestamp", params)
'mobile: getMeetings': @urlForMobileApi("getMeetings", params)
'mobile: create': @urlForMobileApi("create", params)
# Returns a url for any `method` available in the BigBlueButton API
# using the parameters in `params`.
urlFor: (method, params) ->
params = @filterParams(params, method)
url = @url
# list of params
paramList = []
for key, param of params
if key? and param?
paramList.push "#{encodeURIComponent(key)}=#{encodeURIComponent(param)}"
query = paramList.join("&") if paramList.length > 0
# calculate the checksum
checksum = @checksum(method, query)
# add the missing elements in the query
if paramList.length > 0
query = method + "?" + query
query += "&"
else
query = method + "?"
query += "checksum=" + checksum
url + "/" + query
# Calls `urlFor` and changes the generated url to point
# to the mobile API.
urlForMobileApi: (method, params) ->
url = @urlFor method, params, true
# change the path
oldPat = new RegExp("bigbluebutton\\/api\\/" + method + "\\?")
url = url.replace(oldPat, "demo/mobile.jsp?action=" + method + "&")
# removes the old checksum to add a new one later
url = url.replace(/[&]?checksum=.*$/, "")
# add the timestamp and the checksum
unless url.match(/action=getTimestamp/)
url = url + "×tamp=" + new Date().getTime()
query = ""
matched = url.match(/\?(.*)$/)
query = matched[1] if matched? and matched[1]?
url = url + "&checksum=" + @checksum(method, query, true)
# Replaces the protocol for `bigbluebutton://`.
replaceMobileProtocol: (url) ->
url.replace(/http[s]?\:\/\//, "bigbluebutton://")
# Calculates the checksum for an API call `method` with
# the params in `query`.
checksum: (method, query, forMobile) ->
query ||= ""
if forMobile? and forMobile
str = query + @mobileKey
else
str = method + query + @salt
Crypto.SHA1(str)
# Ruby-like include() method for Objects
include = (input, _function) ->
_obj = new Object
_match = null
for key, value of input
if _function.call(input, key, value)
_obj[key] = value
_obj
root.BigBlueButtonApi = BigBlueButtonApi
|
[
{
"context": "page: \"homepage\"\n autohr: \"author\"\n autor: \"author\"\n contributers: \"contributors\"\n publication",
"end": 1744,
"score": 0.9451157450675964,
"start": 1738,
"tag": "USERNAME",
"value": "author"
},
{
"context": "Messages.missingReadme\n ]\n normalize\n name: \"name\"\n version: \"1.2.5\"\n bugs:\n web: \"url\"\n",
"end": 2259,
"score": 0.6538673043251038,
"start": 2255,
"tag": "NAME",
"value": "name"
},
{
"context": "e(\"script\", \"scripts\")\n ]\n normalize\n name: \"name\"\n version: \"1.2.5\"\n script:\n server: \"",
"end": 2576,
"score": 0.647947371006012,
"start": 2572,
"tag": "NAME",
"value": "name"
},
{
"context": "Messages.missingReadme\n ]\n normalize\n name: \"name\"\n version: \"1.2.5\"\n scripts:\n server: ",
"end": 2977,
"score": 0.6155446767807007,
"start": 2973,
"tag": "NAME",
"value": "name"
},
{
"context": "ect = []\n normalize\n private: true\n name: \"name\"\n version: \"1.2.5\"\n scripts:\n server: ",
"end": 3171,
"score": 0.7208510637283325,
"start": 3167,
"tag": "NAME",
"value": "name"
}
] | deps/npm/node_modules/normalize-package-data/test/typo.coffee | lxe/io.coffee | 0 | test = require("tap").test
normalize = require("../")
typos = require("../lib/typos.json")
warningMessages = require("../lib/warning_messages.json")
safeFormat = require("../lib/safe_format")
test "typos", (t) ->
warn = (m) ->
warnings.push m
return
warnings = []
typoMessage = safeFormat.bind(`undefined`, warningMessages.typo)
expect = [
warningMessages.missingRepository
typoMessage("dependancies", "dependencies")
typoMessage("dependecies", "dependencies")
typoMessage("depdenencies", "dependencies")
typoMessage("devEependencies", "devDependencies")
typoMessage("depends", "dependencies")
typoMessage("dev-dependencies", "devDependencies")
typoMessage("devDependences", "devDependencies")
typoMessage("devDepenencies", "devDependencies")
typoMessage("devdependencies", "devDependencies")
typoMessage("repostitory", "repository")
typoMessage("repo", "repository")
typoMessage("prefereGlobal", "preferGlobal")
typoMessage("hompage", "homepage")
typoMessage("hampage", "homepage")
typoMessage("autohr", "author")
typoMessage("autor", "author")
typoMessage("contributers", "contributors")
typoMessage("publicationConfig", "publishConfig")
]
normalize
dependancies: "dependencies"
dependecies: "dependencies"
depdenencies: "dependencies"
devEependencies: "devDependencies"
depends: "dependencies"
"dev-dependencies": "devDependencies"
devDependences: "devDependencies"
devDepenencies: "devDependencies"
devdependencies: "devDependencies"
repostitory: "repository"
repo: "repository"
prefereGlobal: "preferGlobal"
hompage: "homepage"
hampage: "homepage"
autohr: "author"
autor: "author"
contributers: "contributors"
publicationConfig: "publishConfig"
readme: "asdf"
name: "name"
version: "1.2.5"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
typoMessage("bugs['web']", "bugs['url']")
typoMessage("bugs['name']", "bugs['url']")
warningMessages.nonUrlBugsUrlField
warningMessages.emptyNormalizedBugs
warningMessages.missingReadme
]
normalize
name: "name"
version: "1.2.5"
bugs:
web: "url"
name: "url"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
typoMessage("script", "scripts")
]
normalize
name: "name"
version: "1.2.5"
script:
server: "start"
tests: "test"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
typoMessage("scripts['server']", "scripts['start']")
typoMessage("scripts['tests']", "scripts['test']")
warningMessages.missingReadme
]
normalize
name: "name"
version: "1.2.5"
scripts:
server: "start"
tests: "test"
, warn
t.same warnings, expect
warnings.length = 0
expect = []
normalize
private: true
name: "name"
version: "1.2.5"
scripts:
server: "start"
tests: "test"
, warn
t.same warnings, expect
t.end()
return
| 192944 | test = require("tap").test
normalize = require("../")
typos = require("../lib/typos.json")
warningMessages = require("../lib/warning_messages.json")
safeFormat = require("../lib/safe_format")
test "typos", (t) ->
warn = (m) ->
warnings.push m
return
warnings = []
typoMessage = safeFormat.bind(`undefined`, warningMessages.typo)
expect = [
warningMessages.missingRepository
typoMessage("dependancies", "dependencies")
typoMessage("dependecies", "dependencies")
typoMessage("depdenencies", "dependencies")
typoMessage("devEependencies", "devDependencies")
typoMessage("depends", "dependencies")
typoMessage("dev-dependencies", "devDependencies")
typoMessage("devDependences", "devDependencies")
typoMessage("devDepenencies", "devDependencies")
typoMessage("devdependencies", "devDependencies")
typoMessage("repostitory", "repository")
typoMessage("repo", "repository")
typoMessage("prefereGlobal", "preferGlobal")
typoMessage("hompage", "homepage")
typoMessage("hampage", "homepage")
typoMessage("autohr", "author")
typoMessage("autor", "author")
typoMessage("contributers", "contributors")
typoMessage("publicationConfig", "publishConfig")
]
normalize
dependancies: "dependencies"
dependecies: "dependencies"
depdenencies: "dependencies"
devEependencies: "devDependencies"
depends: "dependencies"
"dev-dependencies": "devDependencies"
devDependences: "devDependencies"
devDepenencies: "devDependencies"
devdependencies: "devDependencies"
repostitory: "repository"
repo: "repository"
prefereGlobal: "preferGlobal"
hompage: "homepage"
hampage: "homepage"
autohr: "author"
autor: "author"
contributers: "contributors"
publicationConfig: "publishConfig"
readme: "asdf"
name: "name"
version: "1.2.5"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
typoMessage("bugs['web']", "bugs['url']")
typoMessage("bugs['name']", "bugs['url']")
warningMessages.nonUrlBugsUrlField
warningMessages.emptyNormalizedBugs
warningMessages.missingReadme
]
normalize
name: "<NAME>"
version: "1.2.5"
bugs:
web: "url"
name: "url"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
typoMessage("script", "scripts")
]
normalize
name: "<NAME>"
version: "1.2.5"
script:
server: "start"
tests: "test"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
typoMessage("scripts['server']", "scripts['start']")
typoMessage("scripts['tests']", "scripts['test']")
warningMessages.missingReadme
]
normalize
name: "<NAME>"
version: "1.2.5"
scripts:
server: "start"
tests: "test"
, warn
t.same warnings, expect
warnings.length = 0
expect = []
normalize
private: true
name: "<NAME>"
version: "1.2.5"
scripts:
server: "start"
tests: "test"
, warn
t.same warnings, expect
t.end()
return
| true | test = require("tap").test
normalize = require("../")
typos = require("../lib/typos.json")
warningMessages = require("../lib/warning_messages.json")
safeFormat = require("../lib/safe_format")
test "typos", (t) ->
warn = (m) ->
warnings.push m
return
warnings = []
typoMessage = safeFormat.bind(`undefined`, warningMessages.typo)
expect = [
warningMessages.missingRepository
typoMessage("dependancies", "dependencies")
typoMessage("dependecies", "dependencies")
typoMessage("depdenencies", "dependencies")
typoMessage("devEependencies", "devDependencies")
typoMessage("depends", "dependencies")
typoMessage("dev-dependencies", "devDependencies")
typoMessage("devDependences", "devDependencies")
typoMessage("devDepenencies", "devDependencies")
typoMessage("devdependencies", "devDependencies")
typoMessage("repostitory", "repository")
typoMessage("repo", "repository")
typoMessage("prefereGlobal", "preferGlobal")
typoMessage("hompage", "homepage")
typoMessage("hampage", "homepage")
typoMessage("autohr", "author")
typoMessage("autor", "author")
typoMessage("contributers", "contributors")
typoMessage("publicationConfig", "publishConfig")
]
normalize
dependancies: "dependencies"
dependecies: "dependencies"
depdenencies: "dependencies"
devEependencies: "devDependencies"
depends: "dependencies"
"dev-dependencies": "devDependencies"
devDependences: "devDependencies"
devDepenencies: "devDependencies"
devdependencies: "devDependencies"
repostitory: "repository"
repo: "repository"
prefereGlobal: "preferGlobal"
hompage: "homepage"
hampage: "homepage"
autohr: "author"
autor: "author"
contributers: "contributors"
publicationConfig: "publishConfig"
readme: "asdf"
name: "name"
version: "1.2.5"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
typoMessage("bugs['web']", "bugs['url']")
typoMessage("bugs['name']", "bugs['url']")
warningMessages.nonUrlBugsUrlField
warningMessages.emptyNormalizedBugs
warningMessages.missingReadme
]
normalize
name: "PI:NAME:<NAME>END_PI"
version: "1.2.5"
bugs:
web: "url"
name: "url"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
typoMessage("script", "scripts")
]
normalize
name: "PI:NAME:<NAME>END_PI"
version: "1.2.5"
script:
server: "start"
tests: "test"
, warn
t.same warnings, expect
warnings.length = 0
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
typoMessage("scripts['server']", "scripts['start']")
typoMessage("scripts['tests']", "scripts['test']")
warningMessages.missingReadme
]
normalize
name: "PI:NAME:<NAME>END_PI"
version: "1.2.5"
scripts:
server: "start"
tests: "test"
, warn
t.same warnings, expect
warnings.length = 0
expect = []
normalize
private: true
name: "PI:NAME:<NAME>END_PI"
version: "1.2.5"
scripts:
server: "start"
tests: "test"
, warn
t.same warnings, expect
t.end()
return
|
[
{
"context": "les\n# \n# validate.form $(\"form\"),\n# \"[name='username']\": ($el, callback) ->\n# val = $el.val()",
"end": 1247,
"score": 0.9980452060699463,
"start": 1239,
"tag": "USERNAME",
"value": "username"
},
{
"context": "h \"Your password is too weak.\"\n# if val == \"123456\"\n# errors.push \"That is the dumbest pass",
"end": 1592,
"score": 0.5932334065437317,
"start": 1587,
"tag": "PASSWORD",
"value": "12345"
},
{
"context": "is the dumbest password ever.\"\n# if val == \"hellokitty\"\n# errors.push \"Your password is way too ",
"end": 1683,
"score": 0.9925098419189453,
"start": 1673,
"tag": "PASSWORD",
"value": "hellokitty"
}
] | src/validate.coffee | stratuseditor/stratus-ui | 1 | ###
Validation forms.
validate $("input[name='password']"), ($el, callback) ->
errors = []
errors.push "Password is a required field" if !$el.val()
return callback errors
validate.form $form,
selector: ($el, callblack) ->
selector: ($el, callblack) ->
selector: ($el, callblack) ->
###
CSS_CLASSES =
SUCCESS: "success"
FAILURE: "failure"
LOADING: "loading"
# Validate a form field.
#
# $input - An input element.
# valid - A function which receives the input element and a callback
# to which should be passed an array of errors.
#
# Examples
#
# validate $("input"), ($el, callback) ->
# val = $el.val()
# errors = if val then [] else "Username is required."
# return callback errors
#
validate = ($input, valid) ->
new Validation $input, valid
# Validate a form.
#
# $form - a jQuery element: either a form or an input.
# validations - A hash where the keys are selectors of form inputs, and
# the values are functions. Each function receives
# ($el, callback). The callback should be passed an array
# of errors on the field, or a single string error.
#
# Examples
#
# validate.form $("form"),
# "[name='username']": ($el, callback) ->
# val = $el.val()
# errors = if val then [] else "Username is required."
# return callback errors
#
# "[name='password']": ($el, callback) ->
# val = $el.val()
# errors = []
# if val.length <= 4
# errors.push "Your password is too weak."
# if val == "123456"
# errors.push "That is the dumbest password ever."
# if val == "hellokitty"
# errors.push "Your password is way too immature."
# return callback errors
#
validate.form = ($form, validations) ->
vs = []
for selector, valid of validations
vs.push new Validation $form.find(selector), valid
$form.submit (event) ->
fail = _.once ->
event.preventDefault()
for validation in vs
switch validation.state
when "failure"
fail()
when null
fail()
validation.check (success) ->
$form.submit() if success
class Validation
constructor: (@$el, @valid) ->
@state = null
@$p = @$el.parent()
@$p.append @$icon = "<span class='icon'></span>"
@$el.blur =>
@check()
# Public:
# Validate. The optional callback receives a boolean success parameter.
check: (callback) ->
@loading()
@valid @$el, (errors) =>
errors ?= []
errors = [errors] if typeof(errors) == "string"
# There are some errors to handle...
if errors.length
callback? false
@failure()
@setErrors errors
# Success!
else
callback? true
@success()
@clearErrors()
# Show a spinner. Usually displayed when the server is being queried,
# for example while checking if a username is taken.
loading: ->
@state = "loading"
@_arr @$p,
CSS_CLASSES.LOADING,
CSS_CLASSES.FAILURE,
CSS_CLASSES.SUCCESS
# All validations passing.
success: ->
@state = "success"
@_arr @$p,
CSS_CLASSES.SUCCESS,
CSS_CLASSES.FAILURE,
CSS_CLASSES.LOADING
# One or more errors prevent passing.
failure: ->
@state = "failure"
@_arr @$p,
CSS_CLASSES.FAILURE,
CSS_CLASSES.SUCCESS,
CSS_CLASSES.LOADING
# Update the UI to display the given errors.
#
# errors - an array of error strings to be displayed.
#
setErrors: (errors) ->
@$p.children("ul.errors").remove()
$input = @$p.find("input")
$errors = $ "<ul class='errors'>
<li>#{ errors.join("</li><li>") }</li>
</ul>"
@$p.append $errors
top = $input.position().top +
$input.outerHeight(true) -
+$input.css("margin-bottom").replace(/px/, "")
$errors.css {top}
# Hide the errors being displayed.
clearErrors: ->
@$p.children("ul").slideUp "fast", ->
$(this).remove()
# Add Remove Remove class.
_arr: ($el, a, r1, r2) ->
$el.addClass(a).removeClass "#{ r1 } #{ r2 }"
module.exports = validate
| 150512 | ###
Validation forms.
validate $("input[name='password']"), ($el, callback) ->
errors = []
errors.push "Password is a required field" if !$el.val()
return callback errors
validate.form $form,
selector: ($el, callblack) ->
selector: ($el, callblack) ->
selector: ($el, callblack) ->
###
CSS_CLASSES =
SUCCESS: "success"
FAILURE: "failure"
LOADING: "loading"
# Validate a form field.
#
# $input - An input element.
# valid - A function which receives the input element and a callback
# to which should be passed an array of errors.
#
# Examples
#
# validate $("input"), ($el, callback) ->
# val = $el.val()
# errors = if val then [] else "Username is required."
# return callback errors
#
validate = ($input, valid) ->
new Validation $input, valid
# Validate a form.
#
# $form - a jQuery element: either a form or an input.
# validations - A hash where the keys are selectors of form inputs, and
# the values are functions. Each function receives
# ($el, callback). The callback should be passed an array
# of errors on the field, or a single string error.
#
# Examples
#
# validate.form $("form"),
# "[name='username']": ($el, callback) ->
# val = $el.val()
# errors = if val then [] else "Username is required."
# return callback errors
#
# "[name='password']": ($el, callback) ->
# val = $el.val()
# errors = []
# if val.length <= 4
# errors.push "Your password is too weak."
# if val == "<PASSWORD>6"
# errors.push "That is the dumbest password ever."
# if val == "<PASSWORD>"
# errors.push "Your password is way too immature."
# return callback errors
#
validate.form = ($form, validations) ->
vs = []
for selector, valid of validations
vs.push new Validation $form.find(selector), valid
$form.submit (event) ->
fail = _.once ->
event.preventDefault()
for validation in vs
switch validation.state
when "failure"
fail()
when null
fail()
validation.check (success) ->
$form.submit() if success
class Validation
constructor: (@$el, @valid) ->
@state = null
@$p = @$el.parent()
@$p.append @$icon = "<span class='icon'></span>"
@$el.blur =>
@check()
# Public:
# Validate. The optional callback receives a boolean success parameter.
check: (callback) ->
@loading()
@valid @$el, (errors) =>
errors ?= []
errors = [errors] if typeof(errors) == "string"
# There are some errors to handle...
if errors.length
callback? false
@failure()
@setErrors errors
# Success!
else
callback? true
@success()
@clearErrors()
# Show a spinner. Usually displayed when the server is being queried,
# for example while checking if a username is taken.
loading: ->
@state = "loading"
@_arr @$p,
CSS_CLASSES.LOADING,
CSS_CLASSES.FAILURE,
CSS_CLASSES.SUCCESS
# All validations passing.
success: ->
@state = "success"
@_arr @$p,
CSS_CLASSES.SUCCESS,
CSS_CLASSES.FAILURE,
CSS_CLASSES.LOADING
# One or more errors prevent passing.
failure: ->
@state = "failure"
@_arr @$p,
CSS_CLASSES.FAILURE,
CSS_CLASSES.SUCCESS,
CSS_CLASSES.LOADING
# Update the UI to display the given errors.
#
# errors - an array of error strings to be displayed.
#
setErrors: (errors) ->
@$p.children("ul.errors").remove()
$input = @$p.find("input")
$errors = $ "<ul class='errors'>
<li>#{ errors.join("</li><li>") }</li>
</ul>"
@$p.append $errors
top = $input.position().top +
$input.outerHeight(true) -
+$input.css("margin-bottom").replace(/px/, "")
$errors.css {top}
# Hide the errors being displayed.
clearErrors: ->
@$p.children("ul").slideUp "fast", ->
$(this).remove()
# Add Remove Remove class.
_arr: ($el, a, r1, r2) ->
$el.addClass(a).removeClass "#{ r1 } #{ r2 }"
module.exports = validate
| true | ###
Validation forms.
validate $("input[name='password']"), ($el, callback) ->
errors = []
errors.push "Password is a required field" if !$el.val()
return callback errors
validate.form $form,
selector: ($el, callblack) ->
selector: ($el, callblack) ->
selector: ($el, callblack) ->
###
CSS_CLASSES =
SUCCESS: "success"
FAILURE: "failure"
LOADING: "loading"
# Validate a form field.
#
# $input - An input element.
# valid - A function which receives the input element and a callback
# to which should be passed an array of errors.
#
# Examples
#
# validate $("input"), ($el, callback) ->
# val = $el.val()
# errors = if val then [] else "Username is required."
# return callback errors
#
validate = ($input, valid) ->
new Validation $input, valid
# Validate a form.
#
# $form - a jQuery element: either a form or an input.
# validations - A hash where the keys are selectors of form inputs, and
# the values are functions. Each function receives
# ($el, callback). The callback should be passed an array
# of errors on the field, or a single string error.
#
# Examples
#
# validate.form $("form"),
# "[name='username']": ($el, callback) ->
# val = $el.val()
# errors = if val then [] else "Username is required."
# return callback errors
#
# "[name='password']": ($el, callback) ->
# val = $el.val()
# errors = []
# if val.length <= 4
# errors.push "Your password is too weak."
# if val == "PI:PASSWORD:<PASSWORD>END_PI6"
# errors.push "That is the dumbest password ever."
# if val == "PI:PASSWORD:<PASSWORD>END_PI"
# errors.push "Your password is way too immature."
# return callback errors
#
validate.form = ($form, validations) ->
vs = []
for selector, valid of validations
vs.push new Validation $form.find(selector), valid
$form.submit (event) ->
fail = _.once ->
event.preventDefault()
for validation in vs
switch validation.state
when "failure"
fail()
when null
fail()
validation.check (success) ->
$form.submit() if success
class Validation
constructor: (@$el, @valid) ->
@state = null
@$p = @$el.parent()
@$p.append @$icon = "<span class='icon'></span>"
@$el.blur =>
@check()
# Public:
# Validate. The optional callback receives a boolean success parameter.
check: (callback) ->
@loading()
@valid @$el, (errors) =>
errors ?= []
errors = [errors] if typeof(errors) == "string"
# There are some errors to handle...
if errors.length
callback? false
@failure()
@setErrors errors
# Success!
else
callback? true
@success()
@clearErrors()
# Show a spinner. Usually displayed when the server is being queried,
# for example while checking if a username is taken.
loading: ->
@state = "loading"
@_arr @$p,
CSS_CLASSES.LOADING,
CSS_CLASSES.FAILURE,
CSS_CLASSES.SUCCESS
# All validations passing.
success: ->
@state = "success"
@_arr @$p,
CSS_CLASSES.SUCCESS,
CSS_CLASSES.FAILURE,
CSS_CLASSES.LOADING
# One or more errors prevent passing.
failure: ->
@state = "failure"
@_arr @$p,
CSS_CLASSES.FAILURE,
CSS_CLASSES.SUCCESS,
CSS_CLASSES.LOADING
# Update the UI to display the given errors.
#
# errors - an array of error strings to be displayed.
#
setErrors: (errors) ->
@$p.children("ul.errors").remove()
$input = @$p.find("input")
$errors = $ "<ul class='errors'>
<li>#{ errors.join("</li><li>") }</li>
</ul>"
@$p.append $errors
top = $input.position().top +
$input.outerHeight(true) -
+$input.css("margin-bottom").replace(/px/, "")
$errors.css {top}
# Hide the errors being displayed.
clearErrors: ->
@$p.children("ul").slideUp "fast", ->
$(this).remove()
# Add Remove Remove class.
_arr: ($el, a, r1, r2) ->
$el.addClass(a).removeClass "#{ r1 } #{ r2 }"
module.exports = validate
|
[
{
"context": "dCronHandler or DEBUGGING\n\n res.send('Great work, Captain Cron! I can take it from here.')\n res.end()\n # TODO:",
"end": 2209,
"score": 0.9973501563072205,
"start": 2197,
"tag": "NAME",
"value": "Captain Cron"
},
{
"context": "en \"#{user.firstName}\" else user.name\n name = \"Wizard\" if not name or name is \"Anoner\"\n\n # Fetch the",
"end": 4294,
"score": 0.5062404274940491,
"start": 4288,
"tag": "NAME",
"value": "Wizard"
},
{
"context": ".name\n name = \"Wizard\" if not name or name is \"Anoner\"\n\n # Fetch the most recent defeat and victory,",
"end": 4326,
"score": 0.9933924674987793,
"start": 4320,
"tag": "NAME",
"value": "Anoner"
},
{
"context": " recipient:\n address: if DEBUGGING then 'nick@codecombat.com' else user.email\n name: name\n ema",
"end": 5676,
"score": 0.99992436170578,
"start": 5657,
"tag": "EMAIL",
"value": "nick@codecombat.com"
},
{
"context": "ck@codecombat.com' else user.email\n name: name\n email_data:\n name: name\n ",
"end": 5714,
"score": 0.9979985356330872,
"start": 5710,
"tag": "NAME",
"value": "name"
},
{
"context": " name: name\n email_data:\n name: name\n days_ago: daysAgo\n wins: victo",
"end": 5755,
"score": 0.9688419103622437,
"start": 5751,
"tag": "NAME",
"value": "name"
},
{
"context": "ntext = {opponent_name: defeatedOpponent?.name ? \"Anoner\", url: urlForMatch(victory)} if victory\n\n on",
"end": 7058,
"score": 0.9594294428825378,
"start": 7052,
"tag": "NAME",
"value": "Anoner"
},
{
"context": "ext = {opponent_name: victoriousOpponent?.name ? \"Anoner\", url: urlForMatch(defeat)} if defeat\n sen",
"end": 7354,
"score": 0.9997058510780334,
"start": 7348,
"tag": "NAME",
"value": "Anoner"
}
] | server/routes/mail.coffee | q276188500/codecombat | 1 | mail = require '../commons/mail'
map = _.invert mail.MAILCHIMP_GROUP_MAP
User = require '../users/User.coffee'
errors = require '../commons/errors'
#request = require 'request'
config = require '../../server_config'
LevelSession = require '../levels/sessions/LevelSession.coffee'
Level = require '../levels/Level.coffee'
log = require 'winston'
sendwithus = require '../sendwithus'
#badLog = (text) ->
# console.log text
# request.post 'http://requestb.in/1brdpaz1', { form: {log: text} }
module.exports.setup = (app) ->
app.all config.mail.mailchimpWebhook, handleMailchimpWebHook
app.get '/mail/cron/ladder-update', handleLadderUpdate
getAllLadderScores = (next) ->
query = Level.find({type: 'ladder'})
.select('levelID')
.lean()
query.exec (err, levels) ->
if err
log.error "Couldn't fetch ladder levels. Error: ", err
return next []
for level in levels
for team in ['humans', 'ogres']
'I ... am not doing this.'
# Query to get sessions to make histogram
# db.level.sessions.find({"submitted":true,"levelID":"brawlwood",team:"ogres"},{"_id":0,"totalScore":1})
DEBUGGING = false
LADDER_PREGAME_INTERVAL = 2 * 3600 * 1000 # Send emails two hours before players last submitted.
getTimeFromDaysAgo = (now, daysAgo) ->
t = now - 86400 * 1000 * daysAgo - LADDER_PREGAME_INTERVAL
isRequestFromDesignatedCronHandler = (req, res) ->
requestIP = req.headers['x-forwarded-for'][0]
if requestIP isnt config.mail.cronHandlerPublicIP and requestIP isnt config.mail.cronHandlerPrivateIP
console.log "RECEIVED REQUEST FROM IP #{requestIP}(headers indicate #{req.headers['x-forwarded-for']}"
console.log "UNAUTHORIZED ATTEMPT TO SEND TRANSACTIONAL LADDER EMAIL THROUGH CRON MAIL HANDLER"
res.send("You aren't authorized to perform that action. Only the specified Cron handler may perform that action.")
res.end()
return false
return true
handleLadderUpdate = (req, res) ->
log.info("Going to see about sending ladder update emails.")
requestIsFromDesignatedCronHandler = isRequestFromDesignatedCronHandler req, res
return unless requestIsFromDesignatedCronHandler or DEBUGGING
res.send('Great work, Captain Cron! I can take it from here.')
res.end()
# TODO: somehow fetch the histograms
emailDays = [1, 2, 4, 7, 14, 30]
now = new Date()
for daysAgo in emailDays
# Get every session that was submitted in a 5-minute window after the time.
startTime = getTimeFromDaysAgo now, daysAgo
endTime = startTime + 5 * 60 * 1000
if DEBUGGING
endTime = startTime + 15 * 60 * 1000 # Debugging: make sure there's something to send
findParameters = {submitted: true, submitDate: {$gt: new Date(startTime), $lte: new Date(endTime)}}
# TODO: think about putting screenshots in the email
selectString = "creator team levelName levelID totalScore matches submitted submitDate scoreHistory"
query = LevelSession.find(findParameters)
.select(selectString)
.lean()
do (daysAgo) ->
query.exec (err, results) ->
if err
log.error "Couldn't fetch ladder updates for #{findParameters}\nError: #{err}"
return errors.serverError res, "Ladder update email query failed: #{JSON.stringify(err)}"
log.info "Found #{results.length} ladder sessions to email updates about for #{daysAgo} day(s) ago."
sendLadderUpdateEmail result, now, daysAgo for result in results
sendLadderUpdateEmail = (session, now, daysAgo) ->
User.findOne({_id: session.creator}).select("name email firstName lastName emailSubscriptions preferredLanguage").lean().exec (err, user) ->
if err
log.error "Couldn't find user for #{session.creator} from session #{session._id}"
return
unless user.email and ('notification' in user.emailSubscriptions) and not session.unsubscribed
log.info "Not sending email to #{user.email} #{user.name} because they only want emails about #{user.emailSubscriptions} - session unsubscribed: #{session.unsubscribed}"
return
unless session.levelName
log.info "Not sending email to #{user.email} #{user.name} because the session had no levelName in it."
return
name = if user.firstName and user.lastName then "#{user.firstName}" else user.name
name = "Wizard" if not name or name is "Anoner"
# Fetch the most recent defeat and victory, if there are any.
# (We could look at strongest/weakest, but we'd have to fetch everyone, or denormalize more.)
matches = _.filter session.matches, (match) -> match.date >= getTimeFromDaysAgo now, daysAgo
defeats = _.filter matches, (match) -> match.metrics.rank is 1 and match.opponents[0].metrics.rank is 0
victories = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 1
#ties = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 0
defeat = _.last defeats
victory = _.last victories
#log.info "#{user.name} had #{matches.length} matches from last #{daysAgo} days out of #{session.matches.length} total matches. #{defeats.length} defeats, #{victories.length} victories, and #{ties.length} ties."
#matchInfos = ("\t#{match.date}\t#{match.date >= getTimeFromDaysAgo(now, daysAgo)}\t#{match.metrics.rank}\t#{match.opponents[0].metrics.rank}" for match in session.matches)
#log.info "Matches:\n#{matchInfos.join('\n')}"
sendEmail = (defeatContext, victoryContext) ->
# TODO: do something with the preferredLanguage?
context =
email_id: sendwithus.templates.ladder_update_email
recipient:
address: if DEBUGGING then 'nick@codecombat.com' else user.email
name: name
email_data:
name: name
days_ago: daysAgo
wins: victories.length
losses: defeats.length
total_score: Math.round(session.totalScore * 100)
team: session.team
team_name: session.team[0].toUpperCase() + session.team.substr(1)
level_name: session.levelName
session_id: session._id
ladder_url: "http://codecombat.com/play/ladder/#{session.levelID}#my-matches"
score_history_graph_url: getScoreHistoryGraphURL session, daysAgo
defeat: defeatContext
victory: victoryContext
log.info "Sending ladder update email to #{context.recipient.address} with #{context.email_data.wins} wins and #{context.email_data.losses} losses since #{daysAgo} day(s) ago."
sendwithus.api.send context, (err, result) ->
log.error "Error sending ladder update email: #{err} with result #{result}" if err
urlForMatch = (match) ->
"http://codecombat.com/play/level/#{session.levelID}?team=#{session.team}&session=#{session._id}&opponent=#{match.opponents[0].sessionID}"
onFetchedDefeatedOpponent = (err, defeatedOpponent) ->
if err
log.error "Couldn't find defeateded opponent: #{err}"
defeatedOpponent = null
victoryContext = {opponent_name: defeatedOpponent?.name ? "Anoner", url: urlForMatch(victory)} if victory
onFetchedVictoriousOpponent = (err, victoriousOpponent) ->
if err
log.error "Couldn't find victorious opponent: #{err}"
victoriousOpponent = null
defeatContext = {opponent_name: victoriousOpponent?.name ? "Anoner", url: urlForMatch(defeat)} if defeat
sendEmail defeatContext, victoryContext
if defeat
User.findOne({_id: defeat.opponents[0].userID}).select("name").lean().exec onFetchedVictoriousOpponent
else
onFetchedVictoriousOpponent null, null
if victory
User.findOne({_id: victory.opponents[0].userID}).select("name").lean().exec onFetchedDefeatedOpponent
else
onFetchedDefeatedOpponent null, null
getScoreHistoryGraphURL = (session, daysAgo) ->
# Totally duplicated in My Matches tab for now until we figure out what we're doing.
since = new Date() - 86400 * 1000 * daysAgo
scoreHistory = (s for s in session.scoreHistory ? [] when s[0] >= since)
return '' unless scoreHistory.length > 1
scoreHistory = _.last scoreHistory, 100 # Chart URL needs to be under 2048 characters for GET
times = (s[0] for s in scoreHistory)
times = ((100 * (t - times[0]) / (times[times.length - 1] - times[0])).toFixed(1) for t in times)
scores = (s[1] for s in scoreHistory)
lowest = _.min scores #.concat([0])
highest = _.max scores #.concat(50)
scores = (Math.round(100 * (s - lowest) / (highest - lowest)) for s in scores)
currentScore = Math.round scoreHistory[scoreHistory.length - 1][1] * 100
minScore = Math.round(100 * lowest)
maxScore = Math.round(100 * highest)
chartData = times.join(',') + '|' + scores.join(',')
"https://chart.googleapis.com/chart?chs=600x75&cht=lxy&chtt=Score%3A+#{currentScore}&chts=222222,12,r&chf=a,s,000000FF&chls=2&chd=t:#{chartData}&chxt=y&chxr=0,#{minScore},#{maxScore}"
handleMailchimpWebHook = (req, res) ->
post = req.body
#badLog("Got post data: #{JSON.stringify(post, null, '\t')}")
unless post.type in ['unsubscribe', 'profile']
res.send 'Bad post type'
return res.end()
unless post.data.email
res.send 'No email provided'
return res.end()
query = {'mailChimp.leid':post.data.web_id}
User.findOne query, (err, user) ->
return errors.serverError(res) if err
if not user
return errors.notFound(res)
handleProfileUpdate(user, post) if post.type is 'profile'
handleUnsubscribe(user) if post.type is 'unsubscribe'
user.updatedMailChimp = true # so as not to echo back to mailchimp
user.save (err) ->
return errors.serverError(res) if err
res.end('Success')
handleProfileUpdate = (user, post) ->
groups = post.data.merges.INTERESTS.split(', ')
groups = (map[g] for g in groups when map[g])
otherSubscriptions = (g for g in user.get('emailSubscriptions') when not mail.MAILCHIMP_GROUP_MAP[g])
groups = groups.concat otherSubscriptions
user.set 'emailSubscriptions', groups
fname = post.data.merges.FNAME
user.set('firstName', fname) if fname
lname = post.data.merges.LNAME
user.set('lastName', lname) if lname
user.set 'mailChimp.email', post.data.email
user.set 'mailChimp.euid', post.data.id
# badLog("Updating user object to: #{JSON.stringify(user.toObject(), null, '\t')}")
handleUnsubscribe = (user) ->
user.set 'emailSubscriptions', []
# badLog("Unsubscribing user object to: #{JSON.stringify(user.toObject(), null, '\t')}")
| 31888 | mail = require '../commons/mail'
map = _.invert mail.MAILCHIMP_GROUP_MAP
User = require '../users/User.coffee'
errors = require '../commons/errors'
#request = require 'request'
config = require '../../server_config'
LevelSession = require '../levels/sessions/LevelSession.coffee'
Level = require '../levels/Level.coffee'
log = require 'winston'
sendwithus = require '../sendwithus'
#badLog = (text) ->
# console.log text
# request.post 'http://requestb.in/1brdpaz1', { form: {log: text} }
module.exports.setup = (app) ->
app.all config.mail.mailchimpWebhook, handleMailchimpWebHook
app.get '/mail/cron/ladder-update', handleLadderUpdate
getAllLadderScores = (next) ->
query = Level.find({type: 'ladder'})
.select('levelID')
.lean()
query.exec (err, levels) ->
if err
log.error "Couldn't fetch ladder levels. Error: ", err
return next []
for level in levels
for team in ['humans', 'ogres']
'I ... am not doing this.'
# Query to get sessions to make histogram
# db.level.sessions.find({"submitted":true,"levelID":"brawlwood",team:"ogres"},{"_id":0,"totalScore":1})
DEBUGGING = false
LADDER_PREGAME_INTERVAL = 2 * 3600 * 1000 # Send emails two hours before players last submitted.
getTimeFromDaysAgo = (now, daysAgo) ->
t = now - 86400 * 1000 * daysAgo - LADDER_PREGAME_INTERVAL
isRequestFromDesignatedCronHandler = (req, res) ->
requestIP = req.headers['x-forwarded-for'][0]
if requestIP isnt config.mail.cronHandlerPublicIP and requestIP isnt config.mail.cronHandlerPrivateIP
console.log "RECEIVED REQUEST FROM IP #{requestIP}(headers indicate #{req.headers['x-forwarded-for']}"
console.log "UNAUTHORIZED ATTEMPT TO SEND TRANSACTIONAL LADDER EMAIL THROUGH CRON MAIL HANDLER"
res.send("You aren't authorized to perform that action. Only the specified Cron handler may perform that action.")
res.end()
return false
return true
handleLadderUpdate = (req, res) ->
log.info("Going to see about sending ladder update emails.")
requestIsFromDesignatedCronHandler = isRequestFromDesignatedCronHandler req, res
return unless requestIsFromDesignatedCronHandler or DEBUGGING
res.send('Great work, <NAME>! I can take it from here.')
res.end()
# TODO: somehow fetch the histograms
emailDays = [1, 2, 4, 7, 14, 30]
now = new Date()
for daysAgo in emailDays
# Get every session that was submitted in a 5-minute window after the time.
startTime = getTimeFromDaysAgo now, daysAgo
endTime = startTime + 5 * 60 * 1000
if DEBUGGING
endTime = startTime + 15 * 60 * 1000 # Debugging: make sure there's something to send
findParameters = {submitted: true, submitDate: {$gt: new Date(startTime), $lte: new Date(endTime)}}
# TODO: think about putting screenshots in the email
selectString = "creator team levelName levelID totalScore matches submitted submitDate scoreHistory"
query = LevelSession.find(findParameters)
.select(selectString)
.lean()
do (daysAgo) ->
query.exec (err, results) ->
if err
log.error "Couldn't fetch ladder updates for #{findParameters}\nError: #{err}"
return errors.serverError res, "Ladder update email query failed: #{JSON.stringify(err)}"
log.info "Found #{results.length} ladder sessions to email updates about for #{daysAgo} day(s) ago."
sendLadderUpdateEmail result, now, daysAgo for result in results
sendLadderUpdateEmail = (session, now, daysAgo) ->
User.findOne({_id: session.creator}).select("name email firstName lastName emailSubscriptions preferredLanguage").lean().exec (err, user) ->
if err
log.error "Couldn't find user for #{session.creator} from session #{session._id}"
return
unless user.email and ('notification' in user.emailSubscriptions) and not session.unsubscribed
log.info "Not sending email to #{user.email} #{user.name} because they only want emails about #{user.emailSubscriptions} - session unsubscribed: #{session.unsubscribed}"
return
unless session.levelName
log.info "Not sending email to #{user.email} #{user.name} because the session had no levelName in it."
return
name = if user.firstName and user.lastName then "#{user.firstName}" else user.name
name = "<NAME>" if not name or name is "<NAME>"
# Fetch the most recent defeat and victory, if there are any.
# (We could look at strongest/weakest, but we'd have to fetch everyone, or denormalize more.)
matches = _.filter session.matches, (match) -> match.date >= getTimeFromDaysAgo now, daysAgo
defeats = _.filter matches, (match) -> match.metrics.rank is 1 and match.opponents[0].metrics.rank is 0
victories = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 1
#ties = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 0
defeat = _.last defeats
victory = _.last victories
#log.info "#{user.name} had #{matches.length} matches from last #{daysAgo} days out of #{session.matches.length} total matches. #{defeats.length} defeats, #{victories.length} victories, and #{ties.length} ties."
#matchInfos = ("\t#{match.date}\t#{match.date >= getTimeFromDaysAgo(now, daysAgo)}\t#{match.metrics.rank}\t#{match.opponents[0].metrics.rank}" for match in session.matches)
#log.info "Matches:\n#{matchInfos.join('\n')}"
sendEmail = (defeatContext, victoryContext) ->
# TODO: do something with the preferredLanguage?
context =
email_id: sendwithus.templates.ladder_update_email
recipient:
address: if DEBUGGING then '<EMAIL>' else user.email
name: <NAME>
email_data:
name: <NAME>
days_ago: daysAgo
wins: victories.length
losses: defeats.length
total_score: Math.round(session.totalScore * 100)
team: session.team
team_name: session.team[0].toUpperCase() + session.team.substr(1)
level_name: session.levelName
session_id: session._id
ladder_url: "http://codecombat.com/play/ladder/#{session.levelID}#my-matches"
score_history_graph_url: getScoreHistoryGraphURL session, daysAgo
defeat: defeatContext
victory: victoryContext
log.info "Sending ladder update email to #{context.recipient.address} with #{context.email_data.wins} wins and #{context.email_data.losses} losses since #{daysAgo} day(s) ago."
sendwithus.api.send context, (err, result) ->
log.error "Error sending ladder update email: #{err} with result #{result}" if err
urlForMatch = (match) ->
"http://codecombat.com/play/level/#{session.levelID}?team=#{session.team}&session=#{session._id}&opponent=#{match.opponents[0].sessionID}"
onFetchedDefeatedOpponent = (err, defeatedOpponent) ->
if err
log.error "Couldn't find defeateded opponent: #{err}"
defeatedOpponent = null
victoryContext = {opponent_name: defeatedOpponent?.name ? "<NAME>", url: urlForMatch(victory)} if victory
onFetchedVictoriousOpponent = (err, victoriousOpponent) ->
if err
log.error "Couldn't find victorious opponent: #{err}"
victoriousOpponent = null
defeatContext = {opponent_name: victoriousOpponent?.name ? "<NAME>", url: urlForMatch(defeat)} if defeat
sendEmail defeatContext, victoryContext
if defeat
User.findOne({_id: defeat.opponents[0].userID}).select("name").lean().exec onFetchedVictoriousOpponent
else
onFetchedVictoriousOpponent null, null
if victory
User.findOne({_id: victory.opponents[0].userID}).select("name").lean().exec onFetchedDefeatedOpponent
else
onFetchedDefeatedOpponent null, null
getScoreHistoryGraphURL = (session, daysAgo) ->
# Totally duplicated in My Matches tab for now until we figure out what we're doing.
since = new Date() - 86400 * 1000 * daysAgo
scoreHistory = (s for s in session.scoreHistory ? [] when s[0] >= since)
return '' unless scoreHistory.length > 1
scoreHistory = _.last scoreHistory, 100 # Chart URL needs to be under 2048 characters for GET
times = (s[0] for s in scoreHistory)
times = ((100 * (t - times[0]) / (times[times.length - 1] - times[0])).toFixed(1) for t in times)
scores = (s[1] for s in scoreHistory)
lowest = _.min scores #.concat([0])
highest = _.max scores #.concat(50)
scores = (Math.round(100 * (s - lowest) / (highest - lowest)) for s in scores)
currentScore = Math.round scoreHistory[scoreHistory.length - 1][1] * 100
minScore = Math.round(100 * lowest)
maxScore = Math.round(100 * highest)
chartData = times.join(',') + '|' + scores.join(',')
"https://chart.googleapis.com/chart?chs=600x75&cht=lxy&chtt=Score%3A+#{currentScore}&chts=222222,12,r&chf=a,s,000000FF&chls=2&chd=t:#{chartData}&chxt=y&chxr=0,#{minScore},#{maxScore}"
handleMailchimpWebHook = (req, res) ->
post = req.body
#badLog("Got post data: #{JSON.stringify(post, null, '\t')}")
unless post.type in ['unsubscribe', 'profile']
res.send 'Bad post type'
return res.end()
unless post.data.email
res.send 'No email provided'
return res.end()
query = {'mailChimp.leid':post.data.web_id}
User.findOne query, (err, user) ->
return errors.serverError(res) if err
if not user
return errors.notFound(res)
handleProfileUpdate(user, post) if post.type is 'profile'
handleUnsubscribe(user) if post.type is 'unsubscribe'
user.updatedMailChimp = true # so as not to echo back to mailchimp
user.save (err) ->
return errors.serverError(res) if err
res.end('Success')
handleProfileUpdate = (user, post) ->
groups = post.data.merges.INTERESTS.split(', ')
groups = (map[g] for g in groups when map[g])
otherSubscriptions = (g for g in user.get('emailSubscriptions') when not mail.MAILCHIMP_GROUP_MAP[g])
groups = groups.concat otherSubscriptions
user.set 'emailSubscriptions', groups
fname = post.data.merges.FNAME
user.set('firstName', fname) if fname
lname = post.data.merges.LNAME
user.set('lastName', lname) if lname
user.set 'mailChimp.email', post.data.email
user.set 'mailChimp.euid', post.data.id
# badLog("Updating user object to: #{JSON.stringify(user.toObject(), null, '\t')}")
handleUnsubscribe = (user) ->
user.set 'emailSubscriptions', []
# badLog("Unsubscribing user object to: #{JSON.stringify(user.toObject(), null, '\t')}")
| true | mail = require '../commons/mail'
map = _.invert mail.MAILCHIMP_GROUP_MAP
User = require '../users/User.coffee'
errors = require '../commons/errors'
#request = require 'request'
config = require '../../server_config'
LevelSession = require '../levels/sessions/LevelSession.coffee'
Level = require '../levels/Level.coffee'
log = require 'winston'
sendwithus = require '../sendwithus'
#badLog = (text) ->
# console.log text
# request.post 'http://requestb.in/1brdpaz1', { form: {log: text} }
module.exports.setup = (app) ->
app.all config.mail.mailchimpWebhook, handleMailchimpWebHook
app.get '/mail/cron/ladder-update', handleLadderUpdate
getAllLadderScores = (next) ->
query = Level.find({type: 'ladder'})
.select('levelID')
.lean()
query.exec (err, levels) ->
if err
log.error "Couldn't fetch ladder levels. Error: ", err
return next []
for level in levels
for team in ['humans', 'ogres']
'I ... am not doing this.'
# Query to get sessions to make histogram
# db.level.sessions.find({"submitted":true,"levelID":"brawlwood",team:"ogres"},{"_id":0,"totalScore":1})
DEBUGGING = false
LADDER_PREGAME_INTERVAL = 2 * 3600 * 1000 # Send emails two hours before players last submitted.
getTimeFromDaysAgo = (now, daysAgo) ->
t = now - 86400 * 1000 * daysAgo - LADDER_PREGAME_INTERVAL
isRequestFromDesignatedCronHandler = (req, res) ->
requestIP = req.headers['x-forwarded-for'][0]
if requestIP isnt config.mail.cronHandlerPublicIP and requestIP isnt config.mail.cronHandlerPrivateIP
console.log "RECEIVED REQUEST FROM IP #{requestIP}(headers indicate #{req.headers['x-forwarded-for']}"
console.log "UNAUTHORIZED ATTEMPT TO SEND TRANSACTIONAL LADDER EMAIL THROUGH CRON MAIL HANDLER"
res.send("You aren't authorized to perform that action. Only the specified Cron handler may perform that action.")
res.end()
return false
return true
handleLadderUpdate = (req, res) ->
log.info("Going to see about sending ladder update emails.")
requestIsFromDesignatedCronHandler = isRequestFromDesignatedCronHandler req, res
return unless requestIsFromDesignatedCronHandler or DEBUGGING
res.send('Great work, PI:NAME:<NAME>END_PI! I can take it from here.')
res.end()
# TODO: somehow fetch the histograms
emailDays = [1, 2, 4, 7, 14, 30]
now = new Date()
for daysAgo in emailDays
# Get every session that was submitted in a 5-minute window after the time.
startTime = getTimeFromDaysAgo now, daysAgo
endTime = startTime + 5 * 60 * 1000
if DEBUGGING
endTime = startTime + 15 * 60 * 1000 # Debugging: make sure there's something to send
findParameters = {submitted: true, submitDate: {$gt: new Date(startTime), $lte: new Date(endTime)}}
# TODO: think about putting screenshots in the email
selectString = "creator team levelName levelID totalScore matches submitted submitDate scoreHistory"
query = LevelSession.find(findParameters)
.select(selectString)
.lean()
do (daysAgo) ->
query.exec (err, results) ->
if err
log.error "Couldn't fetch ladder updates for #{findParameters}\nError: #{err}"
return errors.serverError res, "Ladder update email query failed: #{JSON.stringify(err)}"
log.info "Found #{results.length} ladder sessions to email updates about for #{daysAgo} day(s) ago."
sendLadderUpdateEmail result, now, daysAgo for result in results
sendLadderUpdateEmail = (session, now, daysAgo) ->
User.findOne({_id: session.creator}).select("name email firstName lastName emailSubscriptions preferredLanguage").lean().exec (err, user) ->
if err
log.error "Couldn't find user for #{session.creator} from session #{session._id}"
return
unless user.email and ('notification' in user.emailSubscriptions) and not session.unsubscribed
log.info "Not sending email to #{user.email} #{user.name} because they only want emails about #{user.emailSubscriptions} - session unsubscribed: #{session.unsubscribed}"
return
unless session.levelName
log.info "Not sending email to #{user.email} #{user.name} because the session had no levelName in it."
return
name = if user.firstName and user.lastName then "#{user.firstName}" else user.name
name = "PI:NAME:<NAME>END_PI" if not name or name is "PI:NAME:<NAME>END_PI"
# Fetch the most recent defeat and victory, if there are any.
# (We could look at strongest/weakest, but we'd have to fetch everyone, or denormalize more.)
matches = _.filter session.matches, (match) -> match.date >= getTimeFromDaysAgo now, daysAgo
defeats = _.filter matches, (match) -> match.metrics.rank is 1 and match.opponents[0].metrics.rank is 0
victories = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 1
#ties = _.filter matches, (match) -> match.metrics.rank is 0 and match.opponents[0].metrics.rank is 0
defeat = _.last defeats
victory = _.last victories
#log.info "#{user.name} had #{matches.length} matches from last #{daysAgo} days out of #{session.matches.length} total matches. #{defeats.length} defeats, #{victories.length} victories, and #{ties.length} ties."
#matchInfos = ("\t#{match.date}\t#{match.date >= getTimeFromDaysAgo(now, daysAgo)}\t#{match.metrics.rank}\t#{match.opponents[0].metrics.rank}" for match in session.matches)
#log.info "Matches:\n#{matchInfos.join('\n')}"
sendEmail = (defeatContext, victoryContext) ->
# TODO: do something with the preferredLanguage?
context =
email_id: sendwithus.templates.ladder_update_email
recipient:
address: if DEBUGGING then 'PI:EMAIL:<EMAIL>END_PI' else user.email
name: PI:NAME:<NAME>END_PI
email_data:
name: PI:NAME:<NAME>END_PI
days_ago: daysAgo
wins: victories.length
losses: defeats.length
total_score: Math.round(session.totalScore * 100)
team: session.team
team_name: session.team[0].toUpperCase() + session.team.substr(1)
level_name: session.levelName
session_id: session._id
ladder_url: "http://codecombat.com/play/ladder/#{session.levelID}#my-matches"
score_history_graph_url: getScoreHistoryGraphURL session, daysAgo
defeat: defeatContext
victory: victoryContext
log.info "Sending ladder update email to #{context.recipient.address} with #{context.email_data.wins} wins and #{context.email_data.losses} losses since #{daysAgo} day(s) ago."
sendwithus.api.send context, (err, result) ->
log.error "Error sending ladder update email: #{err} with result #{result}" if err
urlForMatch = (match) ->
"http://codecombat.com/play/level/#{session.levelID}?team=#{session.team}&session=#{session._id}&opponent=#{match.opponents[0].sessionID}"
onFetchedDefeatedOpponent = (err, defeatedOpponent) ->
if err
log.error "Couldn't find defeateded opponent: #{err}"
defeatedOpponent = null
victoryContext = {opponent_name: defeatedOpponent?.name ? "PI:NAME:<NAME>END_PI", url: urlForMatch(victory)} if victory
onFetchedVictoriousOpponent = (err, victoriousOpponent) ->
if err
log.error "Couldn't find victorious opponent: #{err}"
victoriousOpponent = null
defeatContext = {opponent_name: victoriousOpponent?.name ? "PI:NAME:<NAME>END_PI", url: urlForMatch(defeat)} if defeat
sendEmail defeatContext, victoryContext
if defeat
User.findOne({_id: defeat.opponents[0].userID}).select("name").lean().exec onFetchedVictoriousOpponent
else
onFetchedVictoriousOpponent null, null
if victory
User.findOne({_id: victory.opponents[0].userID}).select("name").lean().exec onFetchedDefeatedOpponent
else
onFetchedDefeatedOpponent null, null
getScoreHistoryGraphURL = (session, daysAgo) ->
# Totally duplicated in My Matches tab for now until we figure out what we're doing.
since = new Date() - 86400 * 1000 * daysAgo
scoreHistory = (s for s in session.scoreHistory ? [] when s[0] >= since)
return '' unless scoreHistory.length > 1
scoreHistory = _.last scoreHistory, 100 # Chart URL needs to be under 2048 characters for GET
times = (s[0] for s in scoreHistory)
times = ((100 * (t - times[0]) / (times[times.length - 1] - times[0])).toFixed(1) for t in times)
scores = (s[1] for s in scoreHistory)
lowest = _.min scores #.concat([0])
highest = _.max scores #.concat(50)
scores = (Math.round(100 * (s - lowest) / (highest - lowest)) for s in scores)
currentScore = Math.round scoreHistory[scoreHistory.length - 1][1] * 100
minScore = Math.round(100 * lowest)
maxScore = Math.round(100 * highest)
chartData = times.join(',') + '|' + scores.join(',')
"https://chart.googleapis.com/chart?chs=600x75&cht=lxy&chtt=Score%3A+#{currentScore}&chts=222222,12,r&chf=a,s,000000FF&chls=2&chd=t:#{chartData}&chxt=y&chxr=0,#{minScore},#{maxScore}"
handleMailchimpWebHook = (req, res) ->
post = req.body
#badLog("Got post data: #{JSON.stringify(post, null, '\t')}")
unless post.type in ['unsubscribe', 'profile']
res.send 'Bad post type'
return res.end()
unless post.data.email
res.send 'No email provided'
return res.end()
query = {'mailChimp.leid':post.data.web_id}
User.findOne query, (err, user) ->
return errors.serverError(res) if err
if not user
return errors.notFound(res)
handleProfileUpdate(user, post) if post.type is 'profile'
handleUnsubscribe(user) if post.type is 'unsubscribe'
user.updatedMailChimp = true # so as not to echo back to mailchimp
user.save (err) ->
return errors.serverError(res) if err
res.end('Success')
handleProfileUpdate = (user, post) ->
groups = post.data.merges.INTERESTS.split(', ')
groups = (map[g] for g in groups when map[g])
otherSubscriptions = (g for g in user.get('emailSubscriptions') when not mail.MAILCHIMP_GROUP_MAP[g])
groups = groups.concat otherSubscriptions
user.set 'emailSubscriptions', groups
fname = post.data.merges.FNAME
user.set('firstName', fname) if fname
lname = post.data.merges.LNAME
user.set('lastName', lname) if lname
user.set 'mailChimp.email', post.data.email
user.set 'mailChimp.euid', post.data.id
# badLog("Updating user object to: #{JSON.stringify(user.toObject(), null, '\t')}")
handleUnsubscribe = (user) ->
user.set 'emailSubscriptions', []
# badLog("Unsubscribing user object to: #{JSON.stringify(user.toObject(), null, '\t')}")
|
[
{
"context": " console.log \"#{key} init\"\n @key = key or 'unfamiliarBook'\n @wordBook = wordBook\n\n #设置当前文件指针\n",
"end": 323,
"score": 0.6868137717247009,
"start": 313,
"tag": "PASSWORD",
"value": "unfamiliar"
},
{
"context": "og \"#{key} init\"\n @key = key or 'unfamiliarBook'\n @wordBook = wordBook\n\n #设置当前文件指针\n ",
"end": 327,
"score": 0.6359822750091553,
"start": 323,
"tag": "KEY",
"value": "Book"
}
] | public/src/coffee/common/WordBook.coffee | chenqunfeng/CQFWord | 0 | Component = require '../common/Component'
wordBook = require '../../../main/fileController'
class WordBook extends Component.Components
# 构造函数
constructor: (selector, key) ->
super selector
@init key
# 初始化
init: (key) ->
console.log "#{key} init"
@key = key or 'unfamiliarBook'
@wordBook = wordBook
#设置当前文件指针
getWords: () ->
console.log "#{@key} getWords"
# 能否进入学习
canLearn: () ->
return @currentBook and @currentBook.allCount > @currentBook.hasLearningWordCount
# 渲染
render: () ->
@getWords().append().eventBind()
# 添加节点到contain中
append: () ->
@contain.appendChild @template()
return @
# 模版
template: () ->
console.log "#{@key} template"
# 事件绑定
eventBind: () ->
c = @contain.querySelector(".#{@key} .beginLearning")
c and c.addEventListener 'click', () =>
if @canLearn()
localStorage.setItem "currentBook", @key
ipcRenderer.send 'change-learning-window'
else
alert '该单词本没有单词'
return @
module.exports = WordBook
| 31834 | Component = require '../common/Component'
wordBook = require '../../../main/fileController'
class WordBook extends Component.Components
# 构造函数
constructor: (selector, key) ->
super selector
@init key
# 初始化
init: (key) ->
console.log "#{key} init"
@key = key or '<PASSWORD> <KEY>'
@wordBook = wordBook
#设置当前文件指针
getWords: () ->
console.log "#{@key} getWords"
# 能否进入学习
canLearn: () ->
return @currentBook and @currentBook.allCount > @currentBook.hasLearningWordCount
# 渲染
render: () ->
@getWords().append().eventBind()
# 添加节点到contain中
append: () ->
@contain.appendChild @template()
return @
# 模版
template: () ->
console.log "#{@key} template"
# 事件绑定
eventBind: () ->
c = @contain.querySelector(".#{@key} .beginLearning")
c and c.addEventListener 'click', () =>
if @canLearn()
localStorage.setItem "currentBook", @key
ipcRenderer.send 'change-learning-window'
else
alert '该单词本没有单词'
return @
module.exports = WordBook
| true | Component = require '../common/Component'
wordBook = require '../../../main/fileController'
class WordBook extends Component.Components
# 构造函数
constructor: (selector, key) ->
super selector
@init key
# 初始化
init: (key) ->
console.log "#{key} init"
@key = key or 'PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI'
@wordBook = wordBook
#设置当前文件指针
getWords: () ->
console.log "#{@key} getWords"
# 能否进入学习
canLearn: () ->
return @currentBook and @currentBook.allCount > @currentBook.hasLearningWordCount
# 渲染
render: () ->
@getWords().append().eventBind()
# 添加节点到contain中
append: () ->
@contain.appendChild @template()
return @
# 模版
template: () ->
console.log "#{@key} template"
# 事件绑定
eventBind: () ->
c = @contain.querySelector(".#{@key} .beginLearning")
c and c.addEventListener 'click', () =>
if @canLearn()
localStorage.setItem "currentBook", @key
ipcRenderer.send 'change-learning-window'
else
alert '该单词本没有单词'
return @
module.exports = WordBook
|
[
{
"context": "->\n nikita\n my_global:\n my_key: 'my value'\n , ->\n @call ->\n @call $global: '",
"end": 196,
"score": 0.6020017266273499,
"start": 191,
"tag": "KEY",
"value": "value"
},
{
"context": "value'\n config.should.eql\n my_key: 'my value'\n \n",
"end": 1173,
"score": 0.5498168468475342,
"start": 1168,
"tag": "KEY",
"value": "value"
}
] | packages/core/test/plugins/global.coffee | shivaylamba/meilisearch-gatsby-plugin-guide | 31 |
{tags} = require '../test'
nikita = require '../../src'
describe 'plugins.global', ->
return unless tags.api
it 'merge from root', ->
nikita
my_global:
my_key: 'my value'
, ->
@call ->
@call $global: 'my_global', ({config}) ->
config.should.eql
my_key: 'my value'
it 'merge from parent', ->
nikita ->
@call
my_global:
my_key: 'my value'
, ->
@call $global: 'my_global', ({config}) ->
config.should.eql
my_key: 'my value'
it 'merge from current', ->
nikita ->
@call
$global: 'my_global'
my_global:
my_key: 'my value'
, ({config}) ->
config.should.eql
my_key: 'my value'
it 'declared at action registration', ->
nikita ({registry})->
registry.register ['my_action'],
metadata:
name: 'test'
global: 'my_global'
handler: ({config}) ->
config: config
{config} = await @my_action
my_global:
my_key: 'my value'
config.should.eql
my_key: 'my value'
| 36930 |
{tags} = require '../test'
nikita = require '../../src'
describe 'plugins.global', ->
return unless tags.api
it 'merge from root', ->
nikita
my_global:
my_key: 'my <KEY>'
, ->
@call ->
@call $global: 'my_global', ({config}) ->
config.should.eql
my_key: 'my value'
it 'merge from parent', ->
nikita ->
@call
my_global:
my_key: 'my value'
, ->
@call $global: 'my_global', ({config}) ->
config.should.eql
my_key: 'my value'
it 'merge from current', ->
nikita ->
@call
$global: 'my_global'
my_global:
my_key: 'my value'
, ({config}) ->
config.should.eql
my_key: 'my value'
it 'declared at action registration', ->
nikita ({registry})->
registry.register ['my_action'],
metadata:
name: 'test'
global: 'my_global'
handler: ({config}) ->
config: config
{config} = await @my_action
my_global:
my_key: 'my value'
config.should.eql
my_key: 'my <KEY>'
| true |
{tags} = require '../test'
nikita = require '../../src'
describe 'plugins.global', ->
return unless tags.api
it 'merge from root', ->
nikita
my_global:
my_key: 'my PI:KEY:<KEY>END_PI'
, ->
@call ->
@call $global: 'my_global', ({config}) ->
config.should.eql
my_key: 'my value'
it 'merge from parent', ->
nikita ->
@call
my_global:
my_key: 'my value'
, ->
@call $global: 'my_global', ({config}) ->
config.should.eql
my_key: 'my value'
it 'merge from current', ->
nikita ->
@call
$global: 'my_global'
my_global:
my_key: 'my value'
, ({config}) ->
config.should.eql
my_key: 'my value'
it 'declared at action registration', ->
nikita ({registry})->
registry.register ['my_action'],
metadata:
name: 'test'
global: 'my_global'
handler: ({config}) ->
config: config
{config} = await @my_action
my_global:
my_key: 'my value'
config.should.eql
my_key: 'my PI:KEY:<KEY>END_PI'
|
[
{
"context": "#\n# Project's main unit\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Zoom extends Modal\n include: Options\n e",
"end": 64,
"score": 0.9998767375946045,
"start": 47,
"tag": "NAME",
"value": "Nikolay Nemshilov"
}
] | ui/zoom/src/zoom.coffee | lovely-io/lovely.io-stl | 2 | #
# Project's main unit
#
# Copyright (C) 2012 Nikolay Nemshilov
#
class Zoom extends Modal
include: Options
extend:
Options: # default options
nolock: false
fxDuration: 'normal'
current: null
#
# Default constructor
#
# @param {Object} options
# @return {Zoom} self
#
constructor: (options)->
@$super(options).addClass('lui-zoom')
@locker = new Locker()
@icon = new Icon('remove')
@image = new Element('img')
@dialog.append(@image, @icon)
@icon.on('click', => @hide())
Element.prototype.insert.call(@, @locker)
#
# Downloads and shows the image from the link
#
# @param {Element} link
# @return {Zoom} self
#
show: (link)->
@setOptions(link.data('zoom')).addClass('lui-modal-nolock').addClass('lui-zoom-loading')
@dialog.style('display: none')
super() # needs to be done _before_ the @locker resize calls
if @thumb = link.first('img')
@locker.show().position(@thumb.position()).size(@thumb.size())
@image = @image.clone().insertTo(@image, 'instead').attr('src', null)
@image.on('load', =>@loaded()).attr('src', link.attr('href'))
return @
# private
#
# Handles the image-load events
#
loaded: ->
@removeClass('lui-zoom-loading').emit 'load'
@dialog.style('display: inline-block; opacity: 0')
@[if @options.nolock is true then 'addClass' else 'removeClass']('lui-modal-nolock')
if @thumb && @options.fxDuration
@zoom()
else
@dialog.style(opacity: 1)
@emit 'zoom'
@locker.hide()
#
# Makes the smooth zoom visual effect
#
zoom: ()->
start_pos = @thumb.position()
start_size = @thumb.size()
end_size = @dialog.size()
end_pos = @dialog.position()
@dialog.addClass('lui-zoom-resizing').size(start_size).position(start_pos)
pos_diff = @dialog.style('top,left')
pos_diff = x: parseInt(pos_diff.left), y: parseInt(pos_diff.top)
@dialog.style(opacity: 1).animate({
top: pos_diff.y + (end_pos.y - start_pos.y) + 'px'
left: pos_diff.x + (end_pos.x - start_pos.x) + 'px'
width: end_size.x + 'px'
height: end_size.y + 'px'
}, duration: @options.fxDuration, finish: =>
@dialog.removeClass('lui-zoom-resizing').style(top: '', left: '', width: '', height: '')
@emit 'zoom'
)
#
# Sets the size limits for the image
#
# @param {Object} x: N, y: N size
# @return {Zoom} this
#
Zoom::limit_size = (size)->
@image._.style.maxWidth = @dialog._.style.maxWidth = size.x - 20 + 'px'
@image._.style.maxHeight = @dialog._.style.maxHeight = size.y - 5 + 'px'
return @ | 41097 | #
# Project's main unit
#
# Copyright (C) 2012 <NAME>
#
class Zoom extends Modal
include: Options
extend:
Options: # default options
nolock: false
fxDuration: 'normal'
current: null
#
# Default constructor
#
# @param {Object} options
# @return {Zoom} self
#
constructor: (options)->
@$super(options).addClass('lui-zoom')
@locker = new Locker()
@icon = new Icon('remove')
@image = new Element('img')
@dialog.append(@image, @icon)
@icon.on('click', => @hide())
Element.prototype.insert.call(@, @locker)
#
# Downloads and shows the image from the link
#
# @param {Element} link
# @return {Zoom} self
#
show: (link)->
@setOptions(link.data('zoom')).addClass('lui-modal-nolock').addClass('lui-zoom-loading')
@dialog.style('display: none')
super() # needs to be done _before_ the @locker resize calls
if @thumb = link.first('img')
@locker.show().position(@thumb.position()).size(@thumb.size())
@image = @image.clone().insertTo(@image, 'instead').attr('src', null)
@image.on('load', =>@loaded()).attr('src', link.attr('href'))
return @
# private
#
# Handles the image-load events
#
loaded: ->
@removeClass('lui-zoom-loading').emit 'load'
@dialog.style('display: inline-block; opacity: 0')
@[if @options.nolock is true then 'addClass' else 'removeClass']('lui-modal-nolock')
if @thumb && @options.fxDuration
@zoom()
else
@dialog.style(opacity: 1)
@emit 'zoom'
@locker.hide()
#
# Makes the smooth zoom visual effect
#
zoom: ()->
start_pos = @thumb.position()
start_size = @thumb.size()
end_size = @dialog.size()
end_pos = @dialog.position()
@dialog.addClass('lui-zoom-resizing').size(start_size).position(start_pos)
pos_diff = @dialog.style('top,left')
pos_diff = x: parseInt(pos_diff.left), y: parseInt(pos_diff.top)
@dialog.style(opacity: 1).animate({
top: pos_diff.y + (end_pos.y - start_pos.y) + 'px'
left: pos_diff.x + (end_pos.x - start_pos.x) + 'px'
width: end_size.x + 'px'
height: end_size.y + 'px'
}, duration: @options.fxDuration, finish: =>
@dialog.removeClass('lui-zoom-resizing').style(top: '', left: '', width: '', height: '')
@emit 'zoom'
)
#
# Sets the size limits for the image
#
# @param {Object} x: N, y: N size
# @return {Zoom} this
#
Zoom::limit_size = (size)->
@image._.style.maxWidth = @dialog._.style.maxWidth = size.x - 20 + 'px'
@image._.style.maxHeight = @dialog._.style.maxHeight = size.y - 5 + 'px'
return @ | true | #
# Project's main unit
#
# Copyright (C) 2012 PI:NAME:<NAME>END_PI
#
class Zoom extends Modal
include: Options
extend:
Options: # default options
nolock: false
fxDuration: 'normal'
current: null
#
# Default constructor
#
# @param {Object} options
# @return {Zoom} self
#
constructor: (options)->
@$super(options).addClass('lui-zoom')
@locker = new Locker()
@icon = new Icon('remove')
@image = new Element('img')
@dialog.append(@image, @icon)
@icon.on('click', => @hide())
Element.prototype.insert.call(@, @locker)
#
# Downloads and shows the image from the link
#
# @param {Element} link
# @return {Zoom} self
#
show: (link)->
@setOptions(link.data('zoom')).addClass('lui-modal-nolock').addClass('lui-zoom-loading')
@dialog.style('display: none')
super() # needs to be done _before_ the @locker resize calls
if @thumb = link.first('img')
@locker.show().position(@thumb.position()).size(@thumb.size())
@image = @image.clone().insertTo(@image, 'instead').attr('src', null)
@image.on('load', =>@loaded()).attr('src', link.attr('href'))
return @
# private
#
# Handles the image-load events
#
loaded: ->
@removeClass('lui-zoom-loading').emit 'load'
@dialog.style('display: inline-block; opacity: 0')
@[if @options.nolock is true then 'addClass' else 'removeClass']('lui-modal-nolock')
if @thumb && @options.fxDuration
@zoom()
else
@dialog.style(opacity: 1)
@emit 'zoom'
@locker.hide()
#
# Makes the smooth zoom visual effect
#
zoom: ()->
start_pos = @thumb.position()
start_size = @thumb.size()
end_size = @dialog.size()
end_pos = @dialog.position()
@dialog.addClass('lui-zoom-resizing').size(start_size).position(start_pos)
pos_diff = @dialog.style('top,left')
pos_diff = x: parseInt(pos_diff.left), y: parseInt(pos_diff.top)
@dialog.style(opacity: 1).animate({
top: pos_diff.y + (end_pos.y - start_pos.y) + 'px'
left: pos_diff.x + (end_pos.x - start_pos.x) + 'px'
width: end_size.x + 'px'
height: end_size.y + 'px'
}, duration: @options.fxDuration, finish: =>
@dialog.removeClass('lui-zoom-resizing').style(top: '', left: '', width: '', height: '')
@emit 'zoom'
)
#
# Sets the size limits for the image
#
# @param {Object} x: N, y: N size
# @return {Zoom} this
#
Zoom::limit_size = (size)->
@image._.style.maxWidth = @dialog._.style.maxWidth = size.x - 20 + 'px'
@image._.style.maxHeight = @dialog._.style.maxHeight = size.y - 5 + 'px'
return @ |
[
{
"context": "feEval} = require 'loophole'\nanalyticsWriteKey = \"bp0dj6lufc\"\npkg = require \"../package\"\nversion = pkg.versio",
"end": 483,
"score": 0.9973888397216797,
"start": 473,
"tag": "KEY",
"value": "bp0dj6lufc"
}
] | lib/preview-view.coffee | nemoDreamer/atom-preview | 47 | {Emitter, Disposable, CompositeDisposable, TextEditor} = require 'atom'
{$, $$, $$$, View, ScrollView, TextEditorView} = require 'atom-space-pen-views'
util = require 'util'
path = require 'path'
_ = require 'underscore-plus'
renderers = require './renderer'
PreviewMessageView = require './preview-message-view'
OptionsView = require './options-view'
SelectRendererView = require './select-renderer-view.coffee'
{allowUnsafeEval} = require 'loophole'
analyticsWriteKey = "bp0dj6lufc"
pkg = require "../package"
version = pkg.version
class PreviewView extends HTMLElement
textEditor: document.createElement('atom-text-editor')
messageView = null
optionsView = null
selectRendererView = null
htmlPreviewContainer = null
lastEditor: null
lastRendererName: null # TODO: implement the tracking of this
matchedRenderersCache: {}
# Setup Observers
emitter: new Emitter
disposables: new CompositeDisposable
# Public: Initializes the indicator.
initialize: ->
@classList.add('atom-preview-container')
# Update on Tab Change
@activeItemSubscription = atom.workspace.onDidChangeActivePaneItem =>
@handleTabChanges()
# Setup debounced renderer
atom.config.observe 'preview.refreshDebouncePeriod', \
(wait) =>
# console.log "update debounce to #{wait} ms"
@debouncedRenderPreview = _.debounce @renderPreview.bind(@), wait
@self = $(@)
@editorContents = $(@textEditor)
# Add Text Editor
@appendChild(@textEditor)
# Create container for Previewing Rendered HTML
@htmlPreviewContainer = $$ ->
@div =>
@div "Empty HTML Preview..."
# Add HTML Previewer
@self.append @htmlPreviewContainer
@htmlPreviewContainer.hide() # hide by default
# Attach the MessageView
@messageView = new PreviewMessageView()
@self.append(@messageView)
# Attach the OptionsView
@optionsView = new OptionsView(@)
# Create SelectRendererView
@selectRendererView = new SelectRendererView(@)
@showLoading()
# Setup Analytics
Analytics = null
allowUnsafeEval ->
Analytics = require 'analytics-node'
@analytics = new Analytics analyticsWriteKey
# set a unique identifier
if not atom.config.get 'preview._analyticsUserId'
uuid = require 'node-uuid'
atom.config.set 'preview._analyticsUserId', uuid.v4()
# identify the user
atom.config.observe 'preview._analyticsUserId', {}, (userId) =>
# console.log 'userId :', userId
@analytics.identify {
userId: userId
}
# Start rendering
@renderPreview()
return @
changeHandler: () =>
@debouncedRenderPreview()
onDidChangeTitle: (callback) ->
@emitter.on 'did-change-title', callback
handleEvents: () ->
currEditor = atom.workspace.getActiveTextEditor()
if currEditor?
@disposables.add currEditor.getBuffer().onDidStopChanging =>
@changeHandler() if atom.config.get 'preview.liveUpdate'
@disposables.add currEditor.onDidChangePath =>
@emitter.emit 'did-change-title'
@disposables.add currEditor.getBuffer().onDidSave =>
@changeHandler() unless atom.config.get 'preview.liveUpdate'
@disposables.add currEditor.getBuffer().onDidReload =>
@changeHandler() unless atom.config.get 'preview.liveUpdate'
handleTabChanges: =>
updateOnTabChange =
atom.config.get 'preview.updateOnTabChange'
if updateOnTabChange
currEditor = atom.workspace.getActiveTextEditor()
if currEditor?
# Stop watching for events on current Editor
@disposables.dispose()
# Start watching editors on new editor
@handleEvents()
# Trigger update
@changeHandler()
toggleOptions: ->
@optionsView.toggle()
selectRenderer: ->
@selectRendererView.attach()
showError: (result) ->
# console.log('showError', result)
failureMessage = if result and result.message
'<div class="text-error preview-text-error">' + result.message.replace(/\n/g, '<br/>') + '</div>'
else
""
stackDump = if result and result.stack
'<div class="text-warning preview-text-warning">' + result.stack.replace(/\n/g, '<br/>') + '</div>'
else
""
@showMessage()
@messageView.message.html $$$ ->
@div
class: 'preview-spinner'
style: 'text-align: center'
=>
@span
class: 'loading loading-spinner-large inline-block'
@div
class: 'text-highlight preview-text-highlight',
'Previewing Failed\u2026'
@raw failureMessage if failureMessage?
@raw stackDump if stackDump?
showLoading: ->
@showMessage()
@messageView.message.html $$$ ->
@div
class: 'preview-spinner'
style: 'text-align: center'
=>
@span
class: 'loading loading-spinner-large inline-block'
@div
class: 'text-highlight preview-text-highlight',
'Loading Preview\u2026'
showMessage: ->
if not @messageView.hasParent()
#@editorContents.append @messageView
@self.append @messageView
hideMessage: ->
if @messageView.hasParent()
@messageView.detach()
renderViewForPreview: (view) =>
@editorContents.hide()
@htmlPreviewContainer.show()
@htmlPreviewContainer.html view
hideViewPreview: =>
@htmlPreviewContainer.hide()
@editorContents.show()
getTitle: ->
# if @getEditor()?
# "#{@getEditor().getTitle()} preview"
# else
"Atom Preview"
getEditor: ->
@textEditor.getModel()
getPath: ->
if @getEditor()?
@getEditor().getPath()
getURI: ->
"atom://atom-preview"
focus: ->
false
# Public: Destroys the indicator.
destroy: ->
@messageView.detach()
@activeItemSubscription.dispose()
@disposables.dispose()
renderPreview: =>
@renderPreviewWithRenderer "Default"
renderPreviewWithRenderer: (rendererName) =>
# Update Title
@emitter.emit 'did-change-title'
# Start preview processing
cEditor = atom.workspace.getActiveTextEditor()
editor = @getEditor()
# console.log('renderPreviewWithRenderer', rendererName)
# console.log('editor', editor, cEditor)
if cEditor? and cEditor isnt editor and \
cEditor instanceof TextEditor
# console.log "Remember last editor"
@lastEditor = cEditor
else
# console.log "Revert to last editor", @lastEditor
cEditor = @lastEditor
if not cEditor?
# cEditor not defined
@showError({message:"Please select your Text Editor view to render a preview of your code"})
else
# Source Code text
text = cEditor.getText()
# Save Preview's Scroll position
spos = editor.getScrollTop()
# console.log(text)
# console.log(cEditor is editor, cEditor, editor)
@showLoading()
# Update Title
@emitter.emit 'did-change-title'
# Create Callback
callback = (error, result) =>
# console.log('callback', error, result.length)
@hideMessage()
# Force focus on the editor
focusOnEditor = =>
return
# if @lastEditor?
# # console.log "Focus on last editor!", @lastEditor
# uri = @lastEditor.getUri()
# if pane = atom.workspace.paneForUri(uri)
# # console.log pane
# pane.activate()
if error?
focusOnEditor()
return @showError error
# Check if result is a string and therefore source code
if typeof result is "string"
outLang = renderer.lang()
grammar = atom.grammars.selectGrammar("source.#{outLang}", result)
editor.setGrammar grammar
editor.setText result
# Restore Preview's Scroll Positon
editor.setScrollTop(spos)
@hideViewPreview()
focusOnEditor()
# Check if result is a SpacePen View (jQuery)
else if result instanceof View
# Is SpacePen View
@renderViewForPreview(result)
focusOnEditor()
else
# Unknown result type
@hideViewPreview() # Show Editor by default
focusOnEditor()
console.log('unsupported result', result)
return @showError new Error("Unsupported result type.")
# Start preview processing
try
grammar = cEditor.getGrammar().name
filePath = cEditor.getPath()
# console.log grammar,filePath
extension = path.extname(filePath)
# console.log extension
# Get the renderer
renderer = null
if rendererName is "Default"
# Get the cached renderer for this file
renderer = @matchedRenderersCache[filePath]
# Check if cached renderer was found
if not renderer?
# Find renderer
renderer = renderers.findRenderer grammar, extension
else
# Get the Renderer by name
renderer = renderers.grammars[rendererName]
# console.log('renderer', renderer)
# Save matched renderer
@matchedRenderersCache[filePath] = renderer
# console.log renderer
if not text?
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Nothing to render'
properties:
grammar: grammar
extension: extension
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
}
return @showError new Error "Nothing to render."
if renderer?
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Preview'
properties:
grammar: grammar,
extension: extension,
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return renderer.render text, filePath, callback
else
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Renderer not found'
properties:
grammar: grammar,
extension: extension,
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return @showError(new Error \
"Can not find renderer for grammar #{grammar}.")
catch e
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Error'
properties:
error: e
vesion: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return @showError e
module.exports = document.registerElement 'atom-preview-editor', prototype: PreviewView.prototype
| 129771 | {Emitter, Disposable, CompositeDisposable, TextEditor} = require 'atom'
{$, $$, $$$, View, ScrollView, TextEditorView} = require 'atom-space-pen-views'
util = require 'util'
path = require 'path'
_ = require 'underscore-plus'
renderers = require './renderer'
PreviewMessageView = require './preview-message-view'
OptionsView = require './options-view'
SelectRendererView = require './select-renderer-view.coffee'
{allowUnsafeEval} = require 'loophole'
analyticsWriteKey = "<KEY>"
pkg = require "../package"
version = pkg.version
class PreviewView extends HTMLElement
textEditor: document.createElement('atom-text-editor')
messageView = null
optionsView = null
selectRendererView = null
htmlPreviewContainer = null
lastEditor: null
lastRendererName: null # TODO: implement the tracking of this
matchedRenderersCache: {}
# Setup Observers
emitter: new Emitter
disposables: new CompositeDisposable
# Public: Initializes the indicator.
initialize: ->
@classList.add('atom-preview-container')
# Update on Tab Change
@activeItemSubscription = atom.workspace.onDidChangeActivePaneItem =>
@handleTabChanges()
# Setup debounced renderer
atom.config.observe 'preview.refreshDebouncePeriod', \
(wait) =>
# console.log "update debounce to #{wait} ms"
@debouncedRenderPreview = _.debounce @renderPreview.bind(@), wait
@self = $(@)
@editorContents = $(@textEditor)
# Add Text Editor
@appendChild(@textEditor)
# Create container for Previewing Rendered HTML
@htmlPreviewContainer = $$ ->
@div =>
@div "Empty HTML Preview..."
# Add HTML Previewer
@self.append @htmlPreviewContainer
@htmlPreviewContainer.hide() # hide by default
# Attach the MessageView
@messageView = new PreviewMessageView()
@self.append(@messageView)
# Attach the OptionsView
@optionsView = new OptionsView(@)
# Create SelectRendererView
@selectRendererView = new SelectRendererView(@)
@showLoading()
# Setup Analytics
Analytics = null
allowUnsafeEval ->
Analytics = require 'analytics-node'
@analytics = new Analytics analyticsWriteKey
# set a unique identifier
if not atom.config.get 'preview._analyticsUserId'
uuid = require 'node-uuid'
atom.config.set 'preview._analyticsUserId', uuid.v4()
# identify the user
atom.config.observe 'preview._analyticsUserId', {}, (userId) =>
# console.log 'userId :', userId
@analytics.identify {
userId: userId
}
# Start rendering
@renderPreview()
return @
changeHandler: () =>
@debouncedRenderPreview()
onDidChangeTitle: (callback) ->
@emitter.on 'did-change-title', callback
handleEvents: () ->
currEditor = atom.workspace.getActiveTextEditor()
if currEditor?
@disposables.add currEditor.getBuffer().onDidStopChanging =>
@changeHandler() if atom.config.get 'preview.liveUpdate'
@disposables.add currEditor.onDidChangePath =>
@emitter.emit 'did-change-title'
@disposables.add currEditor.getBuffer().onDidSave =>
@changeHandler() unless atom.config.get 'preview.liveUpdate'
@disposables.add currEditor.getBuffer().onDidReload =>
@changeHandler() unless atom.config.get 'preview.liveUpdate'
handleTabChanges: =>
updateOnTabChange =
atom.config.get 'preview.updateOnTabChange'
if updateOnTabChange
currEditor = atom.workspace.getActiveTextEditor()
if currEditor?
# Stop watching for events on current Editor
@disposables.dispose()
# Start watching editors on new editor
@handleEvents()
# Trigger update
@changeHandler()
toggleOptions: ->
@optionsView.toggle()
selectRenderer: ->
@selectRendererView.attach()
showError: (result) ->
# console.log('showError', result)
failureMessage = if result and result.message
'<div class="text-error preview-text-error">' + result.message.replace(/\n/g, '<br/>') + '</div>'
else
""
stackDump = if result and result.stack
'<div class="text-warning preview-text-warning">' + result.stack.replace(/\n/g, '<br/>') + '</div>'
else
""
@showMessage()
@messageView.message.html $$$ ->
@div
class: 'preview-spinner'
style: 'text-align: center'
=>
@span
class: 'loading loading-spinner-large inline-block'
@div
class: 'text-highlight preview-text-highlight',
'Previewing Failed\u2026'
@raw failureMessage if failureMessage?
@raw stackDump if stackDump?
showLoading: ->
@showMessage()
@messageView.message.html $$$ ->
@div
class: 'preview-spinner'
style: 'text-align: center'
=>
@span
class: 'loading loading-spinner-large inline-block'
@div
class: 'text-highlight preview-text-highlight',
'Loading Preview\u2026'
showMessage: ->
if not @messageView.hasParent()
#@editorContents.append @messageView
@self.append @messageView
hideMessage: ->
if @messageView.hasParent()
@messageView.detach()
renderViewForPreview: (view) =>
@editorContents.hide()
@htmlPreviewContainer.show()
@htmlPreviewContainer.html view
hideViewPreview: =>
@htmlPreviewContainer.hide()
@editorContents.show()
getTitle: ->
# if @getEditor()?
# "#{@getEditor().getTitle()} preview"
# else
"Atom Preview"
getEditor: ->
@textEditor.getModel()
getPath: ->
if @getEditor()?
@getEditor().getPath()
getURI: ->
"atom://atom-preview"
focus: ->
false
# Public: Destroys the indicator.
destroy: ->
@messageView.detach()
@activeItemSubscription.dispose()
@disposables.dispose()
renderPreview: =>
@renderPreviewWithRenderer "Default"
renderPreviewWithRenderer: (rendererName) =>
# Update Title
@emitter.emit 'did-change-title'
# Start preview processing
cEditor = atom.workspace.getActiveTextEditor()
editor = @getEditor()
# console.log('renderPreviewWithRenderer', rendererName)
# console.log('editor', editor, cEditor)
if cEditor? and cEditor isnt editor and \
cEditor instanceof TextEditor
# console.log "Remember last editor"
@lastEditor = cEditor
else
# console.log "Revert to last editor", @lastEditor
cEditor = @lastEditor
if not cEditor?
# cEditor not defined
@showError({message:"Please select your Text Editor view to render a preview of your code"})
else
# Source Code text
text = cEditor.getText()
# Save Preview's Scroll position
spos = editor.getScrollTop()
# console.log(text)
# console.log(cEditor is editor, cEditor, editor)
@showLoading()
# Update Title
@emitter.emit 'did-change-title'
# Create Callback
callback = (error, result) =>
# console.log('callback', error, result.length)
@hideMessage()
# Force focus on the editor
focusOnEditor = =>
return
# if @lastEditor?
# # console.log "Focus on last editor!", @lastEditor
# uri = @lastEditor.getUri()
# if pane = atom.workspace.paneForUri(uri)
# # console.log pane
# pane.activate()
if error?
focusOnEditor()
return @showError error
# Check if result is a string and therefore source code
if typeof result is "string"
outLang = renderer.lang()
grammar = atom.grammars.selectGrammar("source.#{outLang}", result)
editor.setGrammar grammar
editor.setText result
# Restore Preview's Scroll Positon
editor.setScrollTop(spos)
@hideViewPreview()
focusOnEditor()
# Check if result is a SpacePen View (jQuery)
else if result instanceof View
# Is SpacePen View
@renderViewForPreview(result)
focusOnEditor()
else
# Unknown result type
@hideViewPreview() # Show Editor by default
focusOnEditor()
console.log('unsupported result', result)
return @showError new Error("Unsupported result type.")
# Start preview processing
try
grammar = cEditor.getGrammar().name
filePath = cEditor.getPath()
# console.log grammar,filePath
extension = path.extname(filePath)
# console.log extension
# Get the renderer
renderer = null
if rendererName is "Default"
# Get the cached renderer for this file
renderer = @matchedRenderersCache[filePath]
# Check if cached renderer was found
if not renderer?
# Find renderer
renderer = renderers.findRenderer grammar, extension
else
# Get the Renderer by name
renderer = renderers.grammars[rendererName]
# console.log('renderer', renderer)
# Save matched renderer
@matchedRenderersCache[filePath] = renderer
# console.log renderer
if not text?
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Nothing to render'
properties:
grammar: grammar
extension: extension
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
}
return @showError new Error "Nothing to render."
if renderer?
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Preview'
properties:
grammar: grammar,
extension: extension,
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return renderer.render text, filePath, callback
else
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Renderer not found'
properties:
grammar: grammar,
extension: extension,
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return @showError(new Error \
"Can not find renderer for grammar #{grammar}.")
catch e
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Error'
properties:
error: e
vesion: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return @showError e
module.exports = document.registerElement 'atom-preview-editor', prototype: PreviewView.prototype
| true | {Emitter, Disposable, CompositeDisposable, TextEditor} = require 'atom'
{$, $$, $$$, View, ScrollView, TextEditorView} = require 'atom-space-pen-views'
util = require 'util'
path = require 'path'
_ = require 'underscore-plus'
renderers = require './renderer'
PreviewMessageView = require './preview-message-view'
OptionsView = require './options-view'
SelectRendererView = require './select-renderer-view.coffee'
{allowUnsafeEval} = require 'loophole'
analyticsWriteKey = "PI:KEY:<KEY>END_PI"
pkg = require "../package"
version = pkg.version
class PreviewView extends HTMLElement
textEditor: document.createElement('atom-text-editor')
messageView = null
optionsView = null
selectRendererView = null
htmlPreviewContainer = null
lastEditor: null
lastRendererName: null # TODO: implement the tracking of this
matchedRenderersCache: {}
# Setup Observers
emitter: new Emitter
disposables: new CompositeDisposable
# Public: Initializes the indicator.
initialize: ->
@classList.add('atom-preview-container')
# Update on Tab Change
@activeItemSubscription = atom.workspace.onDidChangeActivePaneItem =>
@handleTabChanges()
# Setup debounced renderer
atom.config.observe 'preview.refreshDebouncePeriod', \
(wait) =>
# console.log "update debounce to #{wait} ms"
@debouncedRenderPreview = _.debounce @renderPreview.bind(@), wait
@self = $(@)
@editorContents = $(@textEditor)
# Add Text Editor
@appendChild(@textEditor)
# Create container for Previewing Rendered HTML
@htmlPreviewContainer = $$ ->
@div =>
@div "Empty HTML Preview..."
# Add HTML Previewer
@self.append @htmlPreviewContainer
@htmlPreviewContainer.hide() # hide by default
# Attach the MessageView
@messageView = new PreviewMessageView()
@self.append(@messageView)
# Attach the OptionsView
@optionsView = new OptionsView(@)
# Create SelectRendererView
@selectRendererView = new SelectRendererView(@)
@showLoading()
# Setup Analytics
Analytics = null
allowUnsafeEval ->
Analytics = require 'analytics-node'
@analytics = new Analytics analyticsWriteKey
# set a unique identifier
if not atom.config.get 'preview._analyticsUserId'
uuid = require 'node-uuid'
atom.config.set 'preview._analyticsUserId', uuid.v4()
# identify the user
atom.config.observe 'preview._analyticsUserId', {}, (userId) =>
# console.log 'userId :', userId
@analytics.identify {
userId: userId
}
# Start rendering
@renderPreview()
return @
changeHandler: () =>
@debouncedRenderPreview()
onDidChangeTitle: (callback) ->
@emitter.on 'did-change-title', callback
handleEvents: () ->
currEditor = atom.workspace.getActiveTextEditor()
if currEditor?
@disposables.add currEditor.getBuffer().onDidStopChanging =>
@changeHandler() if atom.config.get 'preview.liveUpdate'
@disposables.add currEditor.onDidChangePath =>
@emitter.emit 'did-change-title'
@disposables.add currEditor.getBuffer().onDidSave =>
@changeHandler() unless atom.config.get 'preview.liveUpdate'
@disposables.add currEditor.getBuffer().onDidReload =>
@changeHandler() unless atom.config.get 'preview.liveUpdate'
handleTabChanges: =>
updateOnTabChange =
atom.config.get 'preview.updateOnTabChange'
if updateOnTabChange
currEditor = atom.workspace.getActiveTextEditor()
if currEditor?
# Stop watching for events on current Editor
@disposables.dispose()
# Start watching editors on new editor
@handleEvents()
# Trigger update
@changeHandler()
toggleOptions: ->
@optionsView.toggle()
selectRenderer: ->
@selectRendererView.attach()
showError: (result) ->
# console.log('showError', result)
failureMessage = if result and result.message
'<div class="text-error preview-text-error">' + result.message.replace(/\n/g, '<br/>') + '</div>'
else
""
stackDump = if result and result.stack
'<div class="text-warning preview-text-warning">' + result.stack.replace(/\n/g, '<br/>') + '</div>'
else
""
@showMessage()
@messageView.message.html $$$ ->
@div
class: 'preview-spinner'
style: 'text-align: center'
=>
@span
class: 'loading loading-spinner-large inline-block'
@div
class: 'text-highlight preview-text-highlight',
'Previewing Failed\u2026'
@raw failureMessage if failureMessage?
@raw stackDump if stackDump?
showLoading: ->
@showMessage()
@messageView.message.html $$$ ->
@div
class: 'preview-spinner'
style: 'text-align: center'
=>
@span
class: 'loading loading-spinner-large inline-block'
@div
class: 'text-highlight preview-text-highlight',
'Loading Preview\u2026'
showMessage: ->
if not @messageView.hasParent()
#@editorContents.append @messageView
@self.append @messageView
hideMessage: ->
if @messageView.hasParent()
@messageView.detach()
renderViewForPreview: (view) =>
@editorContents.hide()
@htmlPreviewContainer.show()
@htmlPreviewContainer.html view
hideViewPreview: =>
@htmlPreviewContainer.hide()
@editorContents.show()
getTitle: ->
# if @getEditor()?
# "#{@getEditor().getTitle()} preview"
# else
"Atom Preview"
getEditor: ->
@textEditor.getModel()
getPath: ->
if @getEditor()?
@getEditor().getPath()
getURI: ->
"atom://atom-preview"
focus: ->
false
# Public: Destroys the indicator.
destroy: ->
@messageView.detach()
@activeItemSubscription.dispose()
@disposables.dispose()
renderPreview: =>
@renderPreviewWithRenderer "Default"
renderPreviewWithRenderer: (rendererName) =>
# Update Title
@emitter.emit 'did-change-title'
# Start preview processing
cEditor = atom.workspace.getActiveTextEditor()
editor = @getEditor()
# console.log('renderPreviewWithRenderer', rendererName)
# console.log('editor', editor, cEditor)
if cEditor? and cEditor isnt editor and \
cEditor instanceof TextEditor
# console.log "Remember last editor"
@lastEditor = cEditor
else
# console.log "Revert to last editor", @lastEditor
cEditor = @lastEditor
if not cEditor?
# cEditor not defined
@showError({message:"Please select your Text Editor view to render a preview of your code"})
else
# Source Code text
text = cEditor.getText()
# Save Preview's Scroll position
spos = editor.getScrollTop()
# console.log(text)
# console.log(cEditor is editor, cEditor, editor)
@showLoading()
# Update Title
@emitter.emit 'did-change-title'
# Create Callback
callback = (error, result) =>
# console.log('callback', error, result.length)
@hideMessage()
# Force focus on the editor
focusOnEditor = =>
return
# if @lastEditor?
# # console.log "Focus on last editor!", @lastEditor
# uri = @lastEditor.getUri()
# if pane = atom.workspace.paneForUri(uri)
# # console.log pane
# pane.activate()
if error?
focusOnEditor()
return @showError error
# Check if result is a string and therefore source code
if typeof result is "string"
outLang = renderer.lang()
grammar = atom.grammars.selectGrammar("source.#{outLang}", result)
editor.setGrammar grammar
editor.setText result
# Restore Preview's Scroll Positon
editor.setScrollTop(spos)
@hideViewPreview()
focusOnEditor()
# Check if result is a SpacePen View (jQuery)
else if result instanceof View
# Is SpacePen View
@renderViewForPreview(result)
focusOnEditor()
else
# Unknown result type
@hideViewPreview() # Show Editor by default
focusOnEditor()
console.log('unsupported result', result)
return @showError new Error("Unsupported result type.")
# Start preview processing
try
grammar = cEditor.getGrammar().name
filePath = cEditor.getPath()
# console.log grammar,filePath
extension = path.extname(filePath)
# console.log extension
# Get the renderer
renderer = null
if rendererName is "Default"
# Get the cached renderer for this file
renderer = @matchedRenderersCache[filePath]
# Check if cached renderer was found
if not renderer?
# Find renderer
renderer = renderers.findRenderer grammar, extension
else
# Get the Renderer by name
renderer = renderers.grammars[rendererName]
# console.log('renderer', renderer)
# Save matched renderer
@matchedRenderersCache[filePath] = renderer
# console.log renderer
if not text?
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Nothing to render'
properties:
grammar: grammar
extension: extension
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
}
return @showError new Error "Nothing to render."
if renderer?
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Preview'
properties:
grammar: grammar,
extension: extension,
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return renderer.render text, filePath, callback
else
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Renderer not found'
properties:
grammar: grammar,
extension: extension,
version: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return @showError(new Error \
"Can not find renderer for grammar #{grammar}.")
catch e
# Track
@analytics.track {
userId: atom.config.get 'preview._analyticsUserId'
event: 'Error'
properties:
error: e
vesion: version
# Google Analytics
label: "#{grammar}|#{extension}"
category: version
}
return @showError e
module.exports = document.registerElement 'atom-preview-editor', prototype: PreviewView.prototype
|
[
{
"context": "= second\n rest = others\n\ncontenders = [\n 'Michael Phelps'\n 'Liu Xiang'\n 'Yao Ming'\n 'Allyson Feli",
"end": 172,
"score": 0.9998136162757874,
"start": 158,
"tag": "NAME",
"value": "Michael Phelps"
},
{
"context": " others\n\ncontenders = [\n 'Michael Phelps'\n 'Liu Xiang'\n 'Yao Ming'\n 'Allyson Felis'\n 'Shawn Jo",
"end": 188,
"score": 0.9997130632400513,
"start": 179,
"tag": "NAME",
"value": "Liu Xiang"
},
{
"context": "ers = [\n 'Michael Phelps'\n 'Liu Xiang'\n 'Yao Ming'\n 'Allyson Felis'\n 'Shawn Johnson'\n 'Rom",
"end": 203,
"score": 0.9997329115867615,
"start": 195,
"tag": "NAME",
"value": "Yao Ming"
},
{
"context": "chael Phelps'\n 'Liu Xiang'\n 'Yao Ming'\n 'Allyson Felis'\n 'Shawn Johnson'\n 'Roman Sebrle'\n 'Guo ",
"end": 223,
"score": 0.999829113483429,
"start": 210,
"tag": "NAME",
"value": "Allyson Felis"
},
{
"context": "iu Xiang'\n 'Yao Ming'\n 'Allyson Felis'\n 'Shawn Johnson'\n 'Roman Sebrle'\n 'Guo Jingjing'\n 'Tyson",
"end": 243,
"score": 0.9998252391815186,
"start": 230,
"tag": "NAME",
"value": "Shawn Johnson"
},
{
"context": "ing'\n 'Allyson Felis'\n 'Shawn Johnson'\n 'Roman Sebrle'\n 'Guo Jingjing'\n 'Tyson Gay'\n 'Asafa Po",
"end": 262,
"score": 0.9998400807380676,
"start": 250,
"tag": "NAME",
"value": "Roman Sebrle"
},
{
"context": "elis'\n 'Shawn Johnson'\n 'Roman Sebrle'\n 'Guo Jingjing'\n 'Tyson Gay'\n 'Asafa Powell'\n 'Usain Bo",
"end": 281,
"score": 0.9998177886009216,
"start": 269,
"tag": "NAME",
"value": "Guo Jingjing"
},
{
"context": "hnson'\n 'Roman Sebrle'\n 'Guo Jingjing'\n 'Tyson Gay'\n 'Asafa Powell'\n 'Usain Bolt'\n]\n\nawardMeda",
"end": 297,
"score": 0.9998326301574707,
"start": 288,
"tag": "NAME",
"value": "Tyson Gay"
},
{
"context": "n Sebrle'\n 'Guo Jingjing'\n 'Tyson Gay'\n 'Asafa Powell'\n 'Usain Bolt'\n]\n\nawardMedals contenders...\n\na",
"end": 316,
"score": 0.9998247623443604,
"start": 304,
"tag": "NAME",
"value": "Asafa Powell"
},
{
"context": "Jingjing'\n 'Tyson Gay'\n 'Asafa Powell'\n 'Usain Bolt'\n]\n\nawardMedals contenders...\n\nalert 'Gold: ' + g",
"end": 333,
"score": 0.9998339414596558,
"start": 323,
"tag": "NAME",
"value": "Usain Bolt"
}
] | 002.basic-syntax/src/005.va_arg.coffee | goosman-lei/coffee-lear | 0 | gold = silver = rest = 'unknown'
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
'Michael Phelps'
'Liu Xiang'
'Yao Ming'
'Allyson Felis'
'Shawn Johnson'
'Roman Sebrle'
'Guo Jingjing'
'Tyson Gay'
'Asafa Powell'
'Usain Bolt'
]
awardMedals contenders...
alert 'Gold: ' + gold
alert 'Silver: ' + silver
alert 'GoldThe Field ' + rest | 39043 | gold = silver = rest = 'unknown'
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
'<NAME>'
]
awardMedals contenders...
alert 'Gold: ' + gold
alert 'Silver: ' + silver
alert 'GoldThe Field ' + rest | true | gold = silver = rest = 'unknown'
awardMedals = (first, second, others...) ->
gold = first
silver = second
rest = others
contenders = [
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
'PI:NAME:<NAME>END_PI'
]
awardMedals contenders...
alert 'Gold: ' + gold
alert 'Silver: ' + silver
alert 'GoldThe Field ' + rest |
[
{
"context": "# author: tmwhere.com\n\nutil = require('generic_modules/utility')\nHashMa",
"end": 21,
"score": 0.8445987105369568,
"start": 10,
"tag": "EMAIL",
"value": "tmwhere.com"
}
] | src/generic_modules/astar.coffee | t-mw/citygen | 177 | # author: tmwhere.com
util = require('generic_modules/utility')
HashMap = require('map')
module.exports =
PathLocation:
class PathLocation
constructor: (@o, @fraction) ->
calc: do ->
cost = (current, next, start, end) ->
currentFraction = undefined
nextFraction = undefined
if (start.o == end.o)
fraction = Math.abs(start.fraction - end.fraction)
return fraction * current.cost()
else
if (current == start.o)
currentFraction = start.fraction
if (next == end.o)
nextFraction = end.fraction
return current.costTo(next, currentFraction) + next.costTo(current, nextFraction)
{
find: (start, end) ->
frontier = new util.PriorityQueue
frontier.put(start.o, 0)
came_from = new HashMap
came_from.put(start.o, null)
cost_so_far = new HashMap
cost_so_far.put(start.o, 0)
while (frontier.length() > 0)
current = frontier.get()
if current == end.o
break
for next in current.neighbours()
new_cost = cost_so_far.get(current) + cost(current, next, start, end)
if !cost_so_far.get(next)? || new_cost < cost_so_far.get(next)
cost_so_far.put(next, new_cost)
priority = new_cost # + heuristic(goal, next)
frontier.put(next, priority)
came_from.put(next, current)
console.log("path cost: #{cost_so_far.get(end.o)}")
# reconstruct path
current = end.o
path = [current]
while current != start.o
current = came_from.get(current)
path.unshift(current)
return path
}
| 20945 | # author: <EMAIL>
util = require('generic_modules/utility')
HashMap = require('map')
module.exports =
PathLocation:
class PathLocation
constructor: (@o, @fraction) ->
calc: do ->
cost = (current, next, start, end) ->
currentFraction = undefined
nextFraction = undefined
if (start.o == end.o)
fraction = Math.abs(start.fraction - end.fraction)
return fraction * current.cost()
else
if (current == start.o)
currentFraction = start.fraction
if (next == end.o)
nextFraction = end.fraction
return current.costTo(next, currentFraction) + next.costTo(current, nextFraction)
{
find: (start, end) ->
frontier = new util.PriorityQueue
frontier.put(start.o, 0)
came_from = new HashMap
came_from.put(start.o, null)
cost_so_far = new HashMap
cost_so_far.put(start.o, 0)
while (frontier.length() > 0)
current = frontier.get()
if current == end.o
break
for next in current.neighbours()
new_cost = cost_so_far.get(current) + cost(current, next, start, end)
if !cost_so_far.get(next)? || new_cost < cost_so_far.get(next)
cost_so_far.put(next, new_cost)
priority = new_cost # + heuristic(goal, next)
frontier.put(next, priority)
came_from.put(next, current)
console.log("path cost: #{cost_so_far.get(end.o)}")
# reconstruct path
current = end.o
path = [current]
while current != start.o
current = came_from.get(current)
path.unshift(current)
return path
}
| true | # author: PI:EMAIL:<EMAIL>END_PI
util = require('generic_modules/utility')
HashMap = require('map')
module.exports =
PathLocation:
class PathLocation
constructor: (@o, @fraction) ->
calc: do ->
cost = (current, next, start, end) ->
currentFraction = undefined
nextFraction = undefined
if (start.o == end.o)
fraction = Math.abs(start.fraction - end.fraction)
return fraction * current.cost()
else
if (current == start.o)
currentFraction = start.fraction
if (next == end.o)
nextFraction = end.fraction
return current.costTo(next, currentFraction) + next.costTo(current, nextFraction)
{
find: (start, end) ->
frontier = new util.PriorityQueue
frontier.put(start.o, 0)
came_from = new HashMap
came_from.put(start.o, null)
cost_so_far = new HashMap
cost_so_far.put(start.o, 0)
while (frontier.length() > 0)
current = frontier.get()
if current == end.o
break
for next in current.neighbours()
new_cost = cost_so_far.get(current) + cost(current, next, start, end)
if !cost_so_far.get(next)? || new_cost < cost_so_far.get(next)
cost_so_far.put(next, new_cost)
priority = new_cost # + heuristic(goal, next)
frontier.put(next, priority)
came_from.put(next, current)
console.log("path cost: #{cost_so_far.get(end.o)}")
# reconstruct path
current = end.o
path = [current]
while current != start.o
current = came_from.get(current)
path.unshift(current)
return path
}
|
[
{
"context": "ist + '/' + filePath\n auth:\n user: subject\n pass: process.env.BINTRAY_API_KEY\n ",
"end": 2217,
"score": 0.9636011719703674,
"start": 2210,
"tag": "USERNAME",
"value": "subject"
},
{
"context": "h:\n user: subject\n pass: process.env.BINTRAY_API_KEY\n headers:\n 'X-",
"end": 2241,
"score": 0.6927526593208313,
"start": 2241,
"tag": "PASSWORD",
"value": ""
},
{
"context": " + fileNameShort\n auth:\n user: subject\n pass: process.env.BINTRAY_API_KEY\n ",
"end": 3671,
"score": 0.9577661752700806,
"start": 3664,
"tag": "USERNAME",
"value": "subject"
},
{
"context": " auth:\n user: subject\n pass: process.env.BINTRAY_API_KEY\n headers:\n 'X",
"end": 3701,
"score": 0.6273233294487,
"start": 3690,
"tag": "PASSWORD",
"value": "process.env"
}
] | tasks/publish.coffee | vaginessa/Messenger-for-Desktop | 1,988 | gulp = require 'gulp'
path = require 'path'
fs = require 'fs-extra-promise'
crypto = require 'crypto'
async = require 'async'
mustache = require 'gulp-mustache'
githubRelease = require 'gulp-github-release'
request = require 'request'
utils = require './utils'
{deepClone, applySpawn} = utils
manifest = deepClone require '../src/package.json'
mainManifest = require '../package.json'
changelogJson = require '../CHANGELOG.json'
args = require './args'
# Upload every file in ./dist to GitHub
gulp.task 'publish:github', ->
if not process.env.GITHUB_TOKEN
return console.warn 'GITHUB_TOKEN env var not set.'
channelAppend = ''
if manifest.versionChannel isnt 'stable'
channelAppend = '-' + manifest.versionChannel
release = changelogJson[0]
log = []
for key in Object.keys(release.changes)
logs = release.changes[key]
.map (line) -> '- ' + line
.join '\n'
log.push '\n**' + key + '**\n'
log.push logs
changelog = log.join '\n'
gulp.src './dist/*'
.pipe githubRelease
token: process.env.GITHUB_TOKEN
manifest: manifest
reuseRelease: true
reuseDraftOnly: true
draft: true
tag: 'v' + manifest.version
name: 'v' + manifest.version + channelAppend
notes: changelog.trim()
# Upload deb and RPM packages to Bintray
['deb', 'rpm'].forEach (dist) ->
gulp.task 'publish:bintray:' + dist, (done) ->
if not process.env.BINTRAY_API_KEY
return console.warn 'BINTRAY_API_KEY env var not set.'
arch64Name = if dist is 'deb' then 'amd64' else 'x86_64'
tasks = [
['./dist/' + manifest.name + '-' + manifest.version + '-linux-' + arch64Name + '.' + dist, arch64Name]
['./dist/' + manifest.name + '-' + manifest.version + '-linux-i386.' + dist, 'i386']
].map (item) ->
[srcPath, archType] = item
host = 'https://api.bintray.com'
subject = mainManifest.bintray.subject
filePath = path.basename(srcPath)
if dist is 'deb'
poolPath = 'pool/main/' + manifest.name[0] + '/'
filePath = poolPath + manifest.name + '/' + filePath
opts =
url: host + '/content/' + subject + '/' + dist + '/' + filePath
auth:
user: subject
pass: process.env.BINTRAY_API_KEY
headers:
'X-Bintray-Package': manifest.name
'X-Bintray-Version': manifest.version
'X-Bintray-Publish': 1
'X-Bintray-Override': 1
'X-Bintray-Debian-Distribution': manifest.versionChannel
'X-Bintray-Debian-Component': 'main'
'X-Bintray-Debian-Architecture': archType
(cb) ->
console.log 'Uploading', srcPath if args.verbose
fs.createReadStream srcPath
.pipe request.put opts, (err, res, body) ->
if not err
console.log body if args.verbose
cb(err)
async.series tasks, done
# Upload artifacts to Bintray
['darwin', 'win32', 'linux'].forEach (dist) ->
gulp.task 'publish:bintray:artifacts:' + dist, (done) ->
if not process.env.BINTRAY_API_KEY
return console.warn 'BINTRAY_API_KEY env var not set.'
fs.readdir './dist', (err, files) ->
if err
return done err
tasks = files.map (fileNameShort) ->
fileNameLong = path.resolve './dist/', fileNameShort
host = 'https://api.bintray.com'
subject = mainManifest.bintray.subject
artifactsRepoName = mainManifest.bintray.artifactsRepoName
opts =
url: host + '/content/' + subject + '/' + artifactsRepoName +
'/staging/' + dist + '/' + manifest.version + '/' + fileNameShort
auth:
user: subject
pass: process.env.BINTRAY_API_KEY
headers:
'X-Bintray-Package': manifest.name
'X-Bintray-Version': manifest.version
'X-Bintray-Publish': 1
'X-Bintray-Override': 1
if fileNameShort is 'RELEASES' or fileNameShort.indexOf('.nupkg') > -1
opts.headers['Content-Type'] = 'application/octet-stream'
(cb) ->
console.log 'Uploading', fileNameLong if args.verbose
fs.createReadStream fileNameLong
.pipe request.put opts, (err, res, body) ->
if not err
console.log body if args.verbose
if JSON.stringify(body).toLowerCase().indexOf('success') is -1
err = new Error('bintray upload failed')
cb(err)
async.series tasks, (err) ->
if err
console.log err
artifactsUrl = 'https://dl.bintray.com/' + mainManifest.bintray.subject + '/' +
mainManifest.bintray.artifactsRepoName + '/staging/' + dist + '/'
console.log 'Upload finished: ' + artifactsUrl if args.verbose
done()
| 1568 | gulp = require 'gulp'
path = require 'path'
fs = require 'fs-extra-promise'
crypto = require 'crypto'
async = require 'async'
mustache = require 'gulp-mustache'
githubRelease = require 'gulp-github-release'
request = require 'request'
utils = require './utils'
{deepClone, applySpawn} = utils
manifest = deepClone require '../src/package.json'
mainManifest = require '../package.json'
changelogJson = require '../CHANGELOG.json'
args = require './args'
# Upload every file in ./dist to GitHub
gulp.task 'publish:github', ->
if not process.env.GITHUB_TOKEN
return console.warn 'GITHUB_TOKEN env var not set.'
channelAppend = ''
if manifest.versionChannel isnt 'stable'
channelAppend = '-' + manifest.versionChannel
release = changelogJson[0]
log = []
for key in Object.keys(release.changes)
logs = release.changes[key]
.map (line) -> '- ' + line
.join '\n'
log.push '\n**' + key + '**\n'
log.push logs
changelog = log.join '\n'
gulp.src './dist/*'
.pipe githubRelease
token: process.env.GITHUB_TOKEN
manifest: manifest
reuseRelease: true
reuseDraftOnly: true
draft: true
tag: 'v' + manifest.version
name: 'v' + manifest.version + channelAppend
notes: changelog.trim()
# Upload deb and RPM packages to Bintray
['deb', 'rpm'].forEach (dist) ->
gulp.task 'publish:bintray:' + dist, (done) ->
if not process.env.BINTRAY_API_KEY
return console.warn 'BINTRAY_API_KEY env var not set.'
arch64Name = if dist is 'deb' then 'amd64' else 'x86_64'
tasks = [
['./dist/' + manifest.name + '-' + manifest.version + '-linux-' + arch64Name + '.' + dist, arch64Name]
['./dist/' + manifest.name + '-' + manifest.version + '-linux-i386.' + dist, 'i386']
].map (item) ->
[srcPath, archType] = item
host = 'https://api.bintray.com'
subject = mainManifest.bintray.subject
filePath = path.basename(srcPath)
if dist is 'deb'
poolPath = 'pool/main/' + manifest.name[0] + '/'
filePath = poolPath + manifest.name + '/' + filePath
opts =
url: host + '/content/' + subject + '/' + dist + '/' + filePath
auth:
user: subject
pass: process<PASSWORD>.env.BINTRAY_API_KEY
headers:
'X-Bintray-Package': manifest.name
'X-Bintray-Version': manifest.version
'X-Bintray-Publish': 1
'X-Bintray-Override': 1
'X-Bintray-Debian-Distribution': manifest.versionChannel
'X-Bintray-Debian-Component': 'main'
'X-Bintray-Debian-Architecture': archType
(cb) ->
console.log 'Uploading', srcPath if args.verbose
fs.createReadStream srcPath
.pipe request.put opts, (err, res, body) ->
if not err
console.log body if args.verbose
cb(err)
async.series tasks, done
# Upload artifacts to Bintray
['darwin', 'win32', 'linux'].forEach (dist) ->
gulp.task 'publish:bintray:artifacts:' + dist, (done) ->
if not process.env.BINTRAY_API_KEY
return console.warn 'BINTRAY_API_KEY env var not set.'
fs.readdir './dist', (err, files) ->
if err
return done err
tasks = files.map (fileNameShort) ->
fileNameLong = path.resolve './dist/', fileNameShort
host = 'https://api.bintray.com'
subject = mainManifest.bintray.subject
artifactsRepoName = mainManifest.bintray.artifactsRepoName
opts =
url: host + '/content/' + subject + '/' + artifactsRepoName +
'/staging/' + dist + '/' + manifest.version + '/' + fileNameShort
auth:
user: subject
pass: <PASSWORD>.BINTRAY_API_KEY
headers:
'X-Bintray-Package': manifest.name
'X-Bintray-Version': manifest.version
'X-Bintray-Publish': 1
'X-Bintray-Override': 1
if fileNameShort is 'RELEASES' or fileNameShort.indexOf('.nupkg') > -1
opts.headers['Content-Type'] = 'application/octet-stream'
(cb) ->
console.log 'Uploading', fileNameLong if args.verbose
fs.createReadStream fileNameLong
.pipe request.put opts, (err, res, body) ->
if not err
console.log body if args.verbose
if JSON.stringify(body).toLowerCase().indexOf('success') is -1
err = new Error('bintray upload failed')
cb(err)
async.series tasks, (err) ->
if err
console.log err
artifactsUrl = 'https://dl.bintray.com/' + mainManifest.bintray.subject + '/' +
mainManifest.bintray.artifactsRepoName + '/staging/' + dist + '/'
console.log 'Upload finished: ' + artifactsUrl if args.verbose
done()
| true | gulp = require 'gulp'
path = require 'path'
fs = require 'fs-extra-promise'
crypto = require 'crypto'
async = require 'async'
mustache = require 'gulp-mustache'
githubRelease = require 'gulp-github-release'
request = require 'request'
utils = require './utils'
{deepClone, applySpawn} = utils
manifest = deepClone require '../src/package.json'
mainManifest = require '../package.json'
changelogJson = require '../CHANGELOG.json'
args = require './args'
# Upload every file in ./dist to GitHub
gulp.task 'publish:github', ->
if not process.env.GITHUB_TOKEN
return console.warn 'GITHUB_TOKEN env var not set.'
channelAppend = ''
if manifest.versionChannel isnt 'stable'
channelAppend = '-' + manifest.versionChannel
release = changelogJson[0]
log = []
for key in Object.keys(release.changes)
logs = release.changes[key]
.map (line) -> '- ' + line
.join '\n'
log.push '\n**' + key + '**\n'
log.push logs
changelog = log.join '\n'
gulp.src './dist/*'
.pipe githubRelease
token: process.env.GITHUB_TOKEN
manifest: manifest
reuseRelease: true
reuseDraftOnly: true
draft: true
tag: 'v' + manifest.version
name: 'v' + manifest.version + channelAppend
notes: changelog.trim()
# Upload deb and RPM packages to Bintray
['deb', 'rpm'].forEach (dist) ->
gulp.task 'publish:bintray:' + dist, (done) ->
if not process.env.BINTRAY_API_KEY
return console.warn 'BINTRAY_API_KEY env var not set.'
arch64Name = if dist is 'deb' then 'amd64' else 'x86_64'
tasks = [
['./dist/' + manifest.name + '-' + manifest.version + '-linux-' + arch64Name + '.' + dist, arch64Name]
['./dist/' + manifest.name + '-' + manifest.version + '-linux-i386.' + dist, 'i386']
].map (item) ->
[srcPath, archType] = item
host = 'https://api.bintray.com'
subject = mainManifest.bintray.subject
filePath = path.basename(srcPath)
if dist is 'deb'
poolPath = 'pool/main/' + manifest.name[0] + '/'
filePath = poolPath + manifest.name + '/' + filePath
opts =
url: host + '/content/' + subject + '/' + dist + '/' + filePath
auth:
user: subject
pass: processPI:PASSWORD:<PASSWORD>END_PI.env.BINTRAY_API_KEY
headers:
'X-Bintray-Package': manifest.name
'X-Bintray-Version': manifest.version
'X-Bintray-Publish': 1
'X-Bintray-Override': 1
'X-Bintray-Debian-Distribution': manifest.versionChannel
'X-Bintray-Debian-Component': 'main'
'X-Bintray-Debian-Architecture': archType
(cb) ->
console.log 'Uploading', srcPath if args.verbose
fs.createReadStream srcPath
.pipe request.put opts, (err, res, body) ->
if not err
console.log body if args.verbose
cb(err)
async.series tasks, done
# Upload artifacts to Bintray
['darwin', 'win32', 'linux'].forEach (dist) ->
gulp.task 'publish:bintray:artifacts:' + dist, (done) ->
if not process.env.BINTRAY_API_KEY
return console.warn 'BINTRAY_API_KEY env var not set.'
fs.readdir './dist', (err, files) ->
if err
return done err
tasks = files.map (fileNameShort) ->
fileNameLong = path.resolve './dist/', fileNameShort
host = 'https://api.bintray.com'
subject = mainManifest.bintray.subject
artifactsRepoName = mainManifest.bintray.artifactsRepoName
opts =
url: host + '/content/' + subject + '/' + artifactsRepoName +
'/staging/' + dist + '/' + manifest.version + '/' + fileNameShort
auth:
user: subject
pass: PI:PASSWORD:<PASSWORD>END_PI.BINTRAY_API_KEY
headers:
'X-Bintray-Package': manifest.name
'X-Bintray-Version': manifest.version
'X-Bintray-Publish': 1
'X-Bintray-Override': 1
if fileNameShort is 'RELEASES' or fileNameShort.indexOf('.nupkg') > -1
opts.headers['Content-Type'] = 'application/octet-stream'
(cb) ->
console.log 'Uploading', fileNameLong if args.verbose
fs.createReadStream fileNameLong
.pipe request.put opts, (err, res, body) ->
if not err
console.log body if args.verbose
if JSON.stringify(body).toLowerCase().indexOf('success') is -1
err = new Error('bintray upload failed')
cb(err)
async.series tasks, (err) ->
if err
console.log err
artifactsUrl = 'https://dl.bintray.com/' + mainManifest.bintray.subject + '/' +
mainManifest.bintray.artifactsRepoName + '/staging/' + dist + '/'
console.log 'Upload finished: ' + artifactsUrl if args.verbose
done()
|
[
{
"context": "##\n# GusNIRC\n#\n# Gustavo6046's Node IRC (client).\n##\n\nnet = require(\"net\")\nfs ",
"end": 28,
"score": 0.9996089339256287,
"start": 17,
"tag": "USERNAME",
"value": "Gustavo6046"
},
{
"context": " return null\n\nclass Command\n constructor: (@name, @matcher, @perform, @bot) ->\n if typeof @",
"end": 2680,
"score": 0.9905530214309692,
"start": 2676,
"tag": "USERNAME",
"value": "name"
},
{
"context": "turn null\n\nclass IRCConnection\n constructor: (@id, @bot, @server, @port, @account, @password, @queu",
"end": 3191,
"score": 0.7404085397720337,
"start": 3189,
"tag": "USERNAME",
"value": "id"
},
{
"context": " #{@account} #{@password}\")\n @send(\"PRIVMSG Q@CServe.quakenet.org :IDENTIFY #{@account} #{@password}\")\n\n for",
"end": 4805,
"score": 0.9999162554740906,
"start": 4784,
"tag": "EMAIL",
"value": "Q@CServe.quakenet.org"
},
{
"context": "OIN #{channel}\")\n\nclass IRCBot\n constructor: (@nick, @ident, @realname, @queueTime, @commands) ->\n ",
"end": 5755,
"score": 0.9713737964630127,
"start": 5751,
"tag": "USERNAME",
"value": "nick"
},
{
"context": "ommands) ->\n if not @ident? then @ident = \"GusNIRC\"\n if not @nick? then @nick = \"GusNIRC\"\n ",
"end": 5847,
"score": 0.9750778675079346,
"start": 5840,
"tag": "USERNAME",
"value": "GusNIRC"
},
{
"context": "t = \"GusNIRC\"\n if not @nick? then @nick = \"GusNIRC\"\n if not @commands? then @commands = []\n ",
"end": 5892,
"score": 0.9837060570716858,
"start": 5885,
"tag": "USERNAME",
"value": "GusNIRC"
},
{
"context": " =>\n if not account?\n password = null\n\n @connections[id] = new IRCConnection(id,",
"end": 7958,
"score": 0.9628178477287292,
"start": 7954,
"tag": "PASSWORD",
"value": "null"
}
] | irc.coffee | Gustavo6046/GusNIRC | 0 | ##
# GusNIRC
#
# Gustavo6046's Node IRC (client).
##
net = require("net")
fs = require("fs")
objpath = require("object-path")
messageMatchers = [
["privmsg", "(([^\!]+)\!([^@]+)@([^ ]+)) PRIVMSG ([^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "message"]]
["join", "(([^\!]+)\!([^@]+)@([^ ]+)) JOIN (#[^ ]+).+", ["host", "nickname", "ident", "hostname", "channel"]]
["part", "(([^\!]+)\!([^@]+)@([^ ]+)) PART (#[^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "reason"]]
["notice", "(([^\!]+)\!([^@]+)@([^ ]+)) NOTICE (#[^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "message"]]
["quit", "(([^\!]+)\!([^@]+)@([^ ]+)) QUIT :(.+)", ["host", "nickname", "ident", "hostname", "reason"]]
["ping", "PING :(.+)", ["server"]]
]
class IRCMessage
constructor: (@conn, @raw) ->
@data = {}
@kinds = []
for kind in messageMatchers
r = RegExp(kind[1], "i")
if @raw.match(r)?
@kinds.push(kind[0])
groups = r.exec(@raw)
i = 0
for g in groups.slice(1)
objpath.set(@data, [kind[0], kind[2][i]], g)
i++
reply: (message) =>
if not (@data.privmsg? and @data.privmsg.channel?)
return false
for l in (message + '').split("\n")
if @data.privmsg.channel is @conn.bot.nick
@conn.send("PRIVMSG #{@data.privmsg.nickname} :#{l}")
else
@conn.send("PRIVMSG #{@data.privmsg.channel} :#{l}")
return true
class CommandMatcher
constructor: (@regexStr, @regexFlags) ->
@exp = RegExp(@regexStr, (if @regexFlags? then @regexFlags else "i"))
match: (raw, command, connection) =>
if raw.match(@exp)?
return @exp.exec(raw)
else
return null
class MessageMatcher extends CommandMatcher
constructor: (@regexStr, @regexFlags) ->
@exp = RegExp("[^\\!]+![^@]+@[^ ]+ PRIVMSG #[^ ]+ :#{@regexStr}", (if @regexFlags? then @regexFlags else "i"))
class PrefixedMatcher extends MessageMatcher
constructor: (@regexStr, @regexFlags) ->
@prefix = ""
setPrefix: (@prefix) =>
match: (raw, command, connection) =>
matchstr = "[^\\!]+![^@]+@[^ ]+ PRIVMSG [^ ]+ :#{(@prefix+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}#{@regexStr}"
@exp = RegExp(matchstr, (if @regexFlags? then @regexFlags else "i"))
m = raw.match(@exp)
if m?
groups = @exp.exec(raw)
return groups
else
return null
class Command
constructor: (@name, @matcher, @perform, @bot) ->
if typeof @matcher == "string"
@matcher = new CommandMatcher(@matcher, "i")
receive: (raw, message, connection) =>
@lastParsed = raw
m = @matcher.match(raw, @, connection)
if m?
try
return @perform(message, m.slice(1), connection)
catch err
console.log(err)
message.reply(err)
else
return null
class IRCConnection
constructor: (@id, @bot, @server, @port, @account, @password, @queueTime, @autojoin) ->
@status = "disconnected"
@users = {}
@logfiles = ["global.log", "logs/#{@id}.log"]
@_buffer = ""
@queue = []
log: (logstring, relevant) =>
if relevant
for f in @logfiles
fs.writeFileSync(f, "[#{@id} #{new Date().toISOString()}] #{logstring}\n", { flag: "a" })
console.log("[#{@id} #{new Date().toISOString()}] #{logstring}")
connect: =>
@status = "connecting"
@socket = new net.Socket()
@socket.setEncoding("utf-8")
@socket.on("end", @disconnected)
@socket.on("data", @received)
@socket.connect(@port, @server, @connected)
disconnected: =>
@status = "disconnected"
@log("Disconnected.")
connected: =>
@log("Connected to socket.")
@status = "initializing"
@_mainLoop()
@send("PASS #{@account}:#{@password}")
@send("NICK #{@bot.nick}")
@send("USER #{@account} +b * :#{@bot.realname}")
@status = "motd"
_mainLoop: =>
if @queue.length > 0
data = @queue.splice(0, 1)
if data? and data isnt ""
@socket.write(data + "\r\n")
@log(">>> #{data}")
setTimeout(@_mainLoop, @queueTime)
send: (data) =>
if data is "" or not data.match(/[^\s]/)
return
@queue.push(data)
ready: =>
@send("PRIVMSG NickServ :IDENTIFY #{@account} #{@password}")
@send("PRIVMSG Q@CServe.quakenet.org :IDENTIFY #{@account} #{@password}")
for c in @autojoin
@send("JOIN #{c}")
parse: (line) =>
if "ping" in line.kinds
@send("PONG :#{line.data["ping"].server}")
if @status == "ready"
for c in @bot.commands
c.receive(line.raw, line, @)
if @status == "motd"
if line.raw.match(/[^ ]+ 376/i)?
@status = "ready"
@ready()
received: (data) =>
lines = data.split("\r\n")
@_buffer += lines[lines.length - 1]
for l in lines.slice(0, lines.length - 1)
@log("<<< #{l}")
@parse(new IRCMessage(@, if l.startsWith(":") then l.slice(1) else l))
joinChannel: (channel, keyword) =>
@channels.push(channel)
if keyword?
@send("JOIN #{channel} :#{keyword}")
else
@send("JOIN #{channel}")
class IRCBot
constructor: (@nick, @ident, @realname, @queueTime, @commands) ->
if not @ident? then @ident = "GusNIRC"
if not @nick? then @nick = "GusNIRC"
if not @commands? then @commands = []
if not @realname? then @realname = "A GusNIRC Bot."
@connections = {}
@cmdNames = []
@_commandModules = []
@prefix = ""
for cmd in @commands
@cmdNames.push(cmd.name)
reloadCommands: () =>
@commands = []
for mod in @_commandModules
delete require.cache[require.resolve(mod)]
for mc in require(mod)
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(@prefix)
@commands.push(com)
reloadCommandsFolder: (folder) =>
folder = (if folder? then folder else "commands")
@commands = []
for mod in fs.readdirSync(folder).filter((fn) -> fn.endsWith(".js")).map((fn) -> "./#{folder}/#{fn}")
delete require.cache[require.resolve(mod)]
for mc in require(mod)
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(@prefix)
@commands.push(com)
@parseConfig: (config, commandModules) ->
cmds = []
for c in commandModules
mod = require(c)
for mc in mod
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(config.global.prefix)
cmds.push(com)
bot = new IRCBot(config.global.nick, config.global.ident, config.global.realname, config.global.queueTime * 1000, cmds)
bot._commandModules = commandModules
bot.prefix = config.global.prefix
for c in config.networks
bot.addConnection(c.id, c.server, c.port, c.account, c.password, c.channels)
return bot
addConnection: (id, server, port, account, password, channels) =>
if not account?
password = null
@connections[id] = new IRCConnection(id, @, server, port, account, password, @queueTime, channels)
start: =>
for _, c of @connections
c.connect()
module.exports = {
IRCBot: IRCBot
IRCConnection: IRCConnection,
Command: Command,
CommandMatcher: CommandMatcher,
MessageMatcher: MessageMatcher,
PrefixedMatcher: PrefixedMatcher,
IRCMessage: IRCMessage
} | 180522 | ##
# GusNIRC
#
# Gustavo6046's Node IRC (client).
##
net = require("net")
fs = require("fs")
objpath = require("object-path")
messageMatchers = [
["privmsg", "(([^\!]+)\!([^@]+)@([^ ]+)) PRIVMSG ([^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "message"]]
["join", "(([^\!]+)\!([^@]+)@([^ ]+)) JOIN (#[^ ]+).+", ["host", "nickname", "ident", "hostname", "channel"]]
["part", "(([^\!]+)\!([^@]+)@([^ ]+)) PART (#[^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "reason"]]
["notice", "(([^\!]+)\!([^@]+)@([^ ]+)) NOTICE (#[^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "message"]]
["quit", "(([^\!]+)\!([^@]+)@([^ ]+)) QUIT :(.+)", ["host", "nickname", "ident", "hostname", "reason"]]
["ping", "PING :(.+)", ["server"]]
]
class IRCMessage
constructor: (@conn, @raw) ->
@data = {}
@kinds = []
for kind in messageMatchers
r = RegExp(kind[1], "i")
if @raw.match(r)?
@kinds.push(kind[0])
groups = r.exec(@raw)
i = 0
for g in groups.slice(1)
objpath.set(@data, [kind[0], kind[2][i]], g)
i++
reply: (message) =>
if not (@data.privmsg? and @data.privmsg.channel?)
return false
for l in (message + '').split("\n")
if @data.privmsg.channel is @conn.bot.nick
@conn.send("PRIVMSG #{@data.privmsg.nickname} :#{l}")
else
@conn.send("PRIVMSG #{@data.privmsg.channel} :#{l}")
return true
class CommandMatcher
constructor: (@regexStr, @regexFlags) ->
@exp = RegExp(@regexStr, (if @regexFlags? then @regexFlags else "i"))
match: (raw, command, connection) =>
if raw.match(@exp)?
return @exp.exec(raw)
else
return null
class MessageMatcher extends CommandMatcher
constructor: (@regexStr, @regexFlags) ->
@exp = RegExp("[^\\!]+![^@]+@[^ ]+ PRIVMSG #[^ ]+ :#{@regexStr}", (if @regexFlags? then @regexFlags else "i"))
class PrefixedMatcher extends MessageMatcher
constructor: (@regexStr, @regexFlags) ->
@prefix = ""
setPrefix: (@prefix) =>
match: (raw, command, connection) =>
matchstr = "[^\\!]+![^@]+@[^ ]+ PRIVMSG [^ ]+ :#{(@prefix+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}#{@regexStr}"
@exp = RegExp(matchstr, (if @regexFlags? then @regexFlags else "i"))
m = raw.match(@exp)
if m?
groups = @exp.exec(raw)
return groups
else
return null
class Command
constructor: (@name, @matcher, @perform, @bot) ->
if typeof @matcher == "string"
@matcher = new CommandMatcher(@matcher, "i")
receive: (raw, message, connection) =>
@lastParsed = raw
m = @matcher.match(raw, @, connection)
if m?
try
return @perform(message, m.slice(1), connection)
catch err
console.log(err)
message.reply(err)
else
return null
class IRCConnection
constructor: (@id, @bot, @server, @port, @account, @password, @queueTime, @autojoin) ->
@status = "disconnected"
@users = {}
@logfiles = ["global.log", "logs/#{@id}.log"]
@_buffer = ""
@queue = []
log: (logstring, relevant) =>
if relevant
for f in @logfiles
fs.writeFileSync(f, "[#{@id} #{new Date().toISOString()}] #{logstring}\n", { flag: "a" })
console.log("[#{@id} #{new Date().toISOString()}] #{logstring}")
connect: =>
@status = "connecting"
@socket = new net.Socket()
@socket.setEncoding("utf-8")
@socket.on("end", @disconnected)
@socket.on("data", @received)
@socket.connect(@port, @server, @connected)
disconnected: =>
@status = "disconnected"
@log("Disconnected.")
connected: =>
@log("Connected to socket.")
@status = "initializing"
@_mainLoop()
@send("PASS #{@account}:#{@password}")
@send("NICK #{@bot.nick}")
@send("USER #{@account} +b * :#{@bot.realname}")
@status = "motd"
_mainLoop: =>
if @queue.length > 0
data = @queue.splice(0, 1)
if data? and data isnt ""
@socket.write(data + "\r\n")
@log(">>> #{data}")
setTimeout(@_mainLoop, @queueTime)
send: (data) =>
if data is "" or not data.match(/[^\s]/)
return
@queue.push(data)
ready: =>
@send("PRIVMSG NickServ :IDENTIFY #{@account} #{@password}")
@send("PRIVMSG <EMAIL> :IDENTIFY #{@account} #{@password}")
for c in @autojoin
@send("JOIN #{c}")
parse: (line) =>
if "ping" in line.kinds
@send("PONG :#{line.data["ping"].server}")
if @status == "ready"
for c in @bot.commands
c.receive(line.raw, line, @)
if @status == "motd"
if line.raw.match(/[^ ]+ 376/i)?
@status = "ready"
@ready()
received: (data) =>
lines = data.split("\r\n")
@_buffer += lines[lines.length - 1]
for l in lines.slice(0, lines.length - 1)
@log("<<< #{l}")
@parse(new IRCMessage(@, if l.startsWith(":") then l.slice(1) else l))
joinChannel: (channel, keyword) =>
@channels.push(channel)
if keyword?
@send("JOIN #{channel} :#{keyword}")
else
@send("JOIN #{channel}")
class IRCBot
constructor: (@nick, @ident, @realname, @queueTime, @commands) ->
if not @ident? then @ident = "GusNIRC"
if not @nick? then @nick = "GusNIRC"
if not @commands? then @commands = []
if not @realname? then @realname = "A GusNIRC Bot."
@connections = {}
@cmdNames = []
@_commandModules = []
@prefix = ""
for cmd in @commands
@cmdNames.push(cmd.name)
reloadCommands: () =>
@commands = []
for mod in @_commandModules
delete require.cache[require.resolve(mod)]
for mc in require(mod)
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(@prefix)
@commands.push(com)
reloadCommandsFolder: (folder) =>
folder = (if folder? then folder else "commands")
@commands = []
for mod in fs.readdirSync(folder).filter((fn) -> fn.endsWith(".js")).map((fn) -> "./#{folder}/#{fn}")
delete require.cache[require.resolve(mod)]
for mc in require(mod)
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(@prefix)
@commands.push(com)
@parseConfig: (config, commandModules) ->
cmds = []
for c in commandModules
mod = require(c)
for mc in mod
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(config.global.prefix)
cmds.push(com)
bot = new IRCBot(config.global.nick, config.global.ident, config.global.realname, config.global.queueTime * 1000, cmds)
bot._commandModules = commandModules
bot.prefix = config.global.prefix
for c in config.networks
bot.addConnection(c.id, c.server, c.port, c.account, c.password, c.channels)
return bot
addConnection: (id, server, port, account, password, channels) =>
if not account?
password = <PASSWORD>
@connections[id] = new IRCConnection(id, @, server, port, account, password, @queueTime, channels)
start: =>
for _, c of @connections
c.connect()
module.exports = {
IRCBot: IRCBot
IRCConnection: IRCConnection,
Command: Command,
CommandMatcher: CommandMatcher,
MessageMatcher: MessageMatcher,
PrefixedMatcher: PrefixedMatcher,
IRCMessage: IRCMessage
} | true | ##
# GusNIRC
#
# Gustavo6046's Node IRC (client).
##
net = require("net")
fs = require("fs")
objpath = require("object-path")
messageMatchers = [
["privmsg", "(([^\!]+)\!([^@]+)@([^ ]+)) PRIVMSG ([^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "message"]]
["join", "(([^\!]+)\!([^@]+)@([^ ]+)) JOIN (#[^ ]+).+", ["host", "nickname", "ident", "hostname", "channel"]]
["part", "(([^\!]+)\!([^@]+)@([^ ]+)) PART (#[^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "reason"]]
["notice", "(([^\!]+)\!([^@]+)@([^ ]+)) NOTICE (#[^ ]+) :(.+)", ["host", "nickname", "ident", "hostname", "channel", "message"]]
["quit", "(([^\!]+)\!([^@]+)@([^ ]+)) QUIT :(.+)", ["host", "nickname", "ident", "hostname", "reason"]]
["ping", "PING :(.+)", ["server"]]
]
class IRCMessage
constructor: (@conn, @raw) ->
@data = {}
@kinds = []
for kind in messageMatchers
r = RegExp(kind[1], "i")
if @raw.match(r)?
@kinds.push(kind[0])
groups = r.exec(@raw)
i = 0
for g in groups.slice(1)
objpath.set(@data, [kind[0], kind[2][i]], g)
i++
reply: (message) =>
if not (@data.privmsg? and @data.privmsg.channel?)
return false
for l in (message + '').split("\n")
if @data.privmsg.channel is @conn.bot.nick
@conn.send("PRIVMSG #{@data.privmsg.nickname} :#{l}")
else
@conn.send("PRIVMSG #{@data.privmsg.channel} :#{l}")
return true
class CommandMatcher
constructor: (@regexStr, @regexFlags) ->
@exp = RegExp(@regexStr, (if @regexFlags? then @regexFlags else "i"))
match: (raw, command, connection) =>
if raw.match(@exp)?
return @exp.exec(raw)
else
return null
class MessageMatcher extends CommandMatcher
constructor: (@regexStr, @regexFlags) ->
@exp = RegExp("[^\\!]+![^@]+@[^ ]+ PRIVMSG #[^ ]+ :#{@regexStr}", (if @regexFlags? then @regexFlags else "i"))
class PrefixedMatcher extends MessageMatcher
constructor: (@regexStr, @regexFlags) ->
@prefix = ""
setPrefix: (@prefix) =>
match: (raw, command, connection) =>
matchstr = "[^\\!]+![^@]+@[^ ]+ PRIVMSG [^ ]+ :#{(@prefix+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}#{@regexStr}"
@exp = RegExp(matchstr, (if @regexFlags? then @regexFlags else "i"))
m = raw.match(@exp)
if m?
groups = @exp.exec(raw)
return groups
else
return null
class Command
constructor: (@name, @matcher, @perform, @bot) ->
if typeof @matcher == "string"
@matcher = new CommandMatcher(@matcher, "i")
receive: (raw, message, connection) =>
@lastParsed = raw
m = @matcher.match(raw, @, connection)
if m?
try
return @perform(message, m.slice(1), connection)
catch err
console.log(err)
message.reply(err)
else
return null
class IRCConnection
constructor: (@id, @bot, @server, @port, @account, @password, @queueTime, @autojoin) ->
@status = "disconnected"
@users = {}
@logfiles = ["global.log", "logs/#{@id}.log"]
@_buffer = ""
@queue = []
log: (logstring, relevant) =>
if relevant
for f in @logfiles
fs.writeFileSync(f, "[#{@id} #{new Date().toISOString()}] #{logstring}\n", { flag: "a" })
console.log("[#{@id} #{new Date().toISOString()}] #{logstring}")
connect: =>
@status = "connecting"
@socket = new net.Socket()
@socket.setEncoding("utf-8")
@socket.on("end", @disconnected)
@socket.on("data", @received)
@socket.connect(@port, @server, @connected)
disconnected: =>
@status = "disconnected"
@log("Disconnected.")
connected: =>
@log("Connected to socket.")
@status = "initializing"
@_mainLoop()
@send("PASS #{@account}:#{@password}")
@send("NICK #{@bot.nick}")
@send("USER #{@account} +b * :#{@bot.realname}")
@status = "motd"
_mainLoop: =>
if @queue.length > 0
data = @queue.splice(0, 1)
if data? and data isnt ""
@socket.write(data + "\r\n")
@log(">>> #{data}")
setTimeout(@_mainLoop, @queueTime)
send: (data) =>
if data is "" or not data.match(/[^\s]/)
return
@queue.push(data)
ready: =>
@send("PRIVMSG NickServ :IDENTIFY #{@account} #{@password}")
@send("PRIVMSG PI:EMAIL:<EMAIL>END_PI :IDENTIFY #{@account} #{@password}")
for c in @autojoin
@send("JOIN #{c}")
parse: (line) =>
if "ping" in line.kinds
@send("PONG :#{line.data["ping"].server}")
if @status == "ready"
for c in @bot.commands
c.receive(line.raw, line, @)
if @status == "motd"
if line.raw.match(/[^ ]+ 376/i)?
@status = "ready"
@ready()
received: (data) =>
lines = data.split("\r\n")
@_buffer += lines[lines.length - 1]
for l in lines.slice(0, lines.length - 1)
@log("<<< #{l}")
@parse(new IRCMessage(@, if l.startsWith(":") then l.slice(1) else l))
joinChannel: (channel, keyword) =>
@channels.push(channel)
if keyword?
@send("JOIN #{channel} :#{keyword}")
else
@send("JOIN #{channel}")
class IRCBot
constructor: (@nick, @ident, @realname, @queueTime, @commands) ->
if not @ident? then @ident = "GusNIRC"
if not @nick? then @nick = "GusNIRC"
if not @commands? then @commands = []
if not @realname? then @realname = "A GusNIRC Bot."
@connections = {}
@cmdNames = []
@_commandModules = []
@prefix = ""
for cmd in @commands
@cmdNames.push(cmd.name)
reloadCommands: () =>
@commands = []
for mod in @_commandModules
delete require.cache[require.resolve(mod)]
for mc in require(mod)
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(@prefix)
@commands.push(com)
reloadCommandsFolder: (folder) =>
folder = (if folder? then folder else "commands")
@commands = []
for mod in fs.readdirSync(folder).filter((fn) -> fn.endsWith(".js")).map((fn) -> "./#{folder}/#{fn}")
delete require.cache[require.resolve(mod)]
for mc in require(mod)
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(@prefix)
@commands.push(com)
@parseConfig: (config, commandModules) ->
cmds = []
for c in commandModules
mod = require(c)
for mc in mod
com = new Command(mc.name, mc.matcher, mc.perform)
if com.matcher instanceof PrefixedMatcher
com.matcher.setPrefix(config.global.prefix)
cmds.push(com)
bot = new IRCBot(config.global.nick, config.global.ident, config.global.realname, config.global.queueTime * 1000, cmds)
bot._commandModules = commandModules
bot.prefix = config.global.prefix
for c in config.networks
bot.addConnection(c.id, c.server, c.port, c.account, c.password, c.channels)
return bot
addConnection: (id, server, port, account, password, channels) =>
if not account?
password = PI:PASSWORD:<PASSWORD>END_PI
@connections[id] = new IRCConnection(id, @, server, port, account, password, @queueTime, channels)
start: =>
for _, c of @connections
c.connect()
module.exports = {
IRCBot: IRCBot
IRCConnection: IRCConnection,
Command: Command,
CommandMatcher: CommandMatcher,
MessageMatcher: MessageMatcher,
PrefixedMatcher: PrefixedMatcher,
IRCMessage: IRCMessage
} |
[
{
"context": "sort}>#{output}</span>\")\n\n fields.push\n key: \"createdBy.name\"\n label: \"Submitted by\"\n\n fields.push\n key",
"end": 3466,
"score": 0.949345052242279,
"start": 3452,
"tag": "KEY",
"value": "createdBy.name"
},
{
"context": " label: \"Submitted by\"\n\n fields.push\n key: \"controls\"\n label: \"\"\n hideToggle: true\n fn: (val,",
"end": 3527,
"score": 0.7641397714614868,
"start": 3519,
"tag": "KEY",
"value": "controls"
}
] | client/controllers/table.coffee | ecohealthalliance/rana | 0 | getCollections = => @collections
created = ->
@query = new ReactiveVar()
Template.table.created = created
Template.pendingTable.created = created
query = ->
Template.instance().query
Template.table.query = query
Template.pendingTable.query = query
filters = =>
filters = []
query = Template.instance().query?.get() or {}
# reactive-table filters don't support arbitrary queries yet
if ! _.isEmpty query
queries = if '$and' of query then query['$and'] else [query]
filterCount = 0
for q in queries
key = Object.keys(q)[0]
value = q[key] or ""
filterId = 'reports-' + key + filterCount
filter = new ReactiveTable.Filter(filterId, [key])
if value isnt filter.get()
filter.set(value)
filters.push filterId
filterCount++
filters
Template.table.filters = filters
Template.pendingTable.filters = filters
Template.table.settings = () =>
settings 'full'
Template.table.obfuscatedSettings = () =>
settings 'obfuscated'
Template.pendingTable.settings = () =>
settings 'pending'
settings = (tableType) =>
isAdmin = Roles.userIsInRole Meteor.user(), "admin", Groups.findOne({path: 'rana'})?._id
schema = @collections.Reports.simpleSchema().schema()
fields = []
studyVars = {}
getStudyNameVar = (studyId) ->
if studyVars[studyId]
return studyVars[studyId]
else
studyNameVar = new ReactiveVar("")
studyVars[studyId] = studyNameVar
onReady = () ->
studyName = getCollections().Studies.findOne(studyId)?.name
studyNameVar.set studyName
Meteor.subscribe "studies", studyId, onReady
return studyNameVar
fields.push
key: "studyId"
label: "Study"
fn: (val, obj) ->
getStudyNameVar(val).get()
if tableType in ['full', 'pending']
fields.push
key: "eventLocation"
label: "Event Location"
fn: (val, obj) ->
if val
String(val.geo.coordinates[0]) + ', ' + String(val.geo.coordinates[1])
else
''
else
fields.push
key: "eventLocation.country"
label: "Event Location Country"
if tableType in ['full', 'pending']
columns = [
"speciesGenus"
"speciesName"
"screeningReason"
"populationType"
]
for key in columns
do (key) ->
label = schema[key].label or key
if label.length > 30
label = key
fields.push
key: key
label: label
fn: (val, object) ->
if schema[key]?.autoform?.afFieldInput?.options
option = _.findWhere(
schema[key].autoform.afFieldInput.options,
value: val
)
display = option?.label or ''
new Spacebars.SafeString("<span sort=#{sort}>#{display}</span>")
else
output = val or ''
# capitalize first letter
if output.length > 1
output = output.charAt(0).toUpperCase() + output.slice(1)
# truncate long fields
if output.length > 100
output = output.slice(0, 100) + '...'
# put empty values at the end
if output is '' then sort = 2 else sort = 1
if not output
output = ''
# use option labels instead of values
new Spacebars.SafeString("<span sort=#{sort}>#{output}</span>")
fields.push
key: "createdBy.name"
label: "Submitted by"
fields.push
key: "controls"
label: ""
hideToggle: true
fn: (val, obj) ->
if obj.createdBy.userId == Meteor.userId()
tablePath = Router.path 'table'
editPath = Router.path 'editReport', {reportId: obj._id}, {query: "redirectOnSubmit=#{tablePath}"}
new Spacebars.SafeString("""
<a class="control edit" href="#{editPath}" title="Edit"></a>
<a class="control remove remove-form" data-id="#{obj._id}" title="Remove"></a>
""")
else if isAdmin
viewPath = Router.path 'editReport', {reportId: obj._id}
new Spacebars.SafeString("""
<a class="control view" href="#{viewPath}" title="View"></a>
<a class="control remove remove-form" data-id="#{obj._id}" title="Remove"></a>
""")
else
viewPath = Router.path 'editReport', {reportId: obj._id}
new Spacebars.SafeString("""
<a class="control view" href="#{viewPath}" title="View"></a>
""")
if tableType is 'pending'
fields.push
key: "controls"
label: ""
hideToggle: true
fn: (val, obj) ->
new Spacebars.SafeString("""
<a class="control approve-report" data-id="#{obj._id}" title="Approve report"></a>
<a class="control reject-report" data-id="#{obj._id}" title="Reject Report"></a>
<a class="control approve-user" data-id="#{obj.createdBy.userId}" title="Approve User"></a>
<a class="control reject-user" data-id="#{obj.createdBy.userId}" title="Reject User`"></a>
""")
if tableType is 'pending'
noDataTmpl = Template.noPendingReports
else
noDataTmpl = Template.noReports
showColumnToggles: true
showFilter: false
fields: fields
noDataTmpl: noDataTmpl
rowClass: (val) ->
if !isAdmin
switch val.approval
when 'approved' then 'approved'
when 'rejected' then 'rejected'
when 'pending' then 'pending'
events =
'click .remove-form': (evt)->
reportId = $(evt.target).data("id")
reply = prompt('Type "delete" to confirm that this report should be removed.')
if reply == "delete"
getCollections().Reports.remove(reportId)
'click .toggle-filter': () ->
$('.filter-controls').toggleClass('hidden')
$('.toggle-filter').toggleClass('showingOpts')
"click .next-page, click .previous-page" : () ->
if (window.scrollY > 0)
$('body').animate({scrollTop:0,400})
'click .export:not(.disabled)': (event, template) ->
$(event.target).addClass('disabled')
query = template.query.get()
Meteor.call 'export', query, (err, result) ->
if (err)
console.log err
alert "There was an error exporting the data."
else
window.open "data:text/csv;charset=utf-8," + encodeURIComponent(result)
$(event.target).removeClass('disabled')
'click .edit': () ->
toastr.remove()
Template.table.events events
Template.pendingTable.events events
Template.pendingTable.events
'click .approve-report': (e) =>
@setApproval 'setReportApproval', $(e.target).data('id'), 'approved', "Report approved"
'click .reject-report': (e) =>
@setApproval 'setReportApproval', $(e.target).data('id'), 'rejected', "Report rejected"
'click .approve-user': (e) =>
@setApproval 'setUserApproval', $(e.target).data('id'), 'approved', "User approved"
'click .reject-user': (e) =>
@setApproval 'setUserApproval', $(e.target).data('id'), 'rejected', "User rejected"
| 219731 | getCollections = => @collections
created = ->
@query = new ReactiveVar()
Template.table.created = created
Template.pendingTable.created = created
query = ->
Template.instance().query
Template.table.query = query
Template.pendingTable.query = query
filters = =>
filters = []
query = Template.instance().query?.get() or {}
# reactive-table filters don't support arbitrary queries yet
if ! _.isEmpty query
queries = if '$and' of query then query['$and'] else [query]
filterCount = 0
for q in queries
key = Object.keys(q)[0]
value = q[key] or ""
filterId = 'reports-' + key + filterCount
filter = new ReactiveTable.Filter(filterId, [key])
if value isnt filter.get()
filter.set(value)
filters.push filterId
filterCount++
filters
Template.table.filters = filters
Template.pendingTable.filters = filters
Template.table.settings = () =>
settings 'full'
Template.table.obfuscatedSettings = () =>
settings 'obfuscated'
Template.pendingTable.settings = () =>
settings 'pending'
settings = (tableType) =>
isAdmin = Roles.userIsInRole Meteor.user(), "admin", Groups.findOne({path: 'rana'})?._id
schema = @collections.Reports.simpleSchema().schema()
fields = []
studyVars = {}
getStudyNameVar = (studyId) ->
if studyVars[studyId]
return studyVars[studyId]
else
studyNameVar = new ReactiveVar("")
studyVars[studyId] = studyNameVar
onReady = () ->
studyName = getCollections().Studies.findOne(studyId)?.name
studyNameVar.set studyName
Meteor.subscribe "studies", studyId, onReady
return studyNameVar
fields.push
key: "studyId"
label: "Study"
fn: (val, obj) ->
getStudyNameVar(val).get()
if tableType in ['full', 'pending']
fields.push
key: "eventLocation"
label: "Event Location"
fn: (val, obj) ->
if val
String(val.geo.coordinates[0]) + ', ' + String(val.geo.coordinates[1])
else
''
else
fields.push
key: "eventLocation.country"
label: "Event Location Country"
if tableType in ['full', 'pending']
columns = [
"speciesGenus"
"speciesName"
"screeningReason"
"populationType"
]
for key in columns
do (key) ->
label = schema[key].label or key
if label.length > 30
label = key
fields.push
key: key
label: label
fn: (val, object) ->
if schema[key]?.autoform?.afFieldInput?.options
option = _.findWhere(
schema[key].autoform.afFieldInput.options,
value: val
)
display = option?.label or ''
new Spacebars.SafeString("<span sort=#{sort}>#{display}</span>")
else
output = val or ''
# capitalize first letter
if output.length > 1
output = output.charAt(0).toUpperCase() + output.slice(1)
# truncate long fields
if output.length > 100
output = output.slice(0, 100) + '...'
# put empty values at the end
if output is '' then sort = 2 else sort = 1
if not output
output = ''
# use option labels instead of values
new Spacebars.SafeString("<span sort=#{sort}>#{output}</span>")
fields.push
key: "<KEY>"
label: "Submitted by"
fields.push
key: "<KEY>"
label: ""
hideToggle: true
fn: (val, obj) ->
if obj.createdBy.userId == Meteor.userId()
tablePath = Router.path 'table'
editPath = Router.path 'editReport', {reportId: obj._id}, {query: "redirectOnSubmit=#{tablePath}"}
new Spacebars.SafeString("""
<a class="control edit" href="#{editPath}" title="Edit"></a>
<a class="control remove remove-form" data-id="#{obj._id}" title="Remove"></a>
""")
else if isAdmin
viewPath = Router.path 'editReport', {reportId: obj._id}
new Spacebars.SafeString("""
<a class="control view" href="#{viewPath}" title="View"></a>
<a class="control remove remove-form" data-id="#{obj._id}" title="Remove"></a>
""")
else
viewPath = Router.path 'editReport', {reportId: obj._id}
new Spacebars.SafeString("""
<a class="control view" href="#{viewPath}" title="View"></a>
""")
if tableType is 'pending'
fields.push
key: "controls"
label: ""
hideToggle: true
fn: (val, obj) ->
new Spacebars.SafeString("""
<a class="control approve-report" data-id="#{obj._id}" title="Approve report"></a>
<a class="control reject-report" data-id="#{obj._id}" title="Reject Report"></a>
<a class="control approve-user" data-id="#{obj.createdBy.userId}" title="Approve User"></a>
<a class="control reject-user" data-id="#{obj.createdBy.userId}" title="Reject User`"></a>
""")
if tableType is 'pending'
noDataTmpl = Template.noPendingReports
else
noDataTmpl = Template.noReports
showColumnToggles: true
showFilter: false
fields: fields
noDataTmpl: noDataTmpl
rowClass: (val) ->
if !isAdmin
switch val.approval
when 'approved' then 'approved'
when 'rejected' then 'rejected'
when 'pending' then 'pending'
events =
'click .remove-form': (evt)->
reportId = $(evt.target).data("id")
reply = prompt('Type "delete" to confirm that this report should be removed.')
if reply == "delete"
getCollections().Reports.remove(reportId)
'click .toggle-filter': () ->
$('.filter-controls').toggleClass('hidden')
$('.toggle-filter').toggleClass('showingOpts')
"click .next-page, click .previous-page" : () ->
if (window.scrollY > 0)
$('body').animate({scrollTop:0,400})
'click .export:not(.disabled)': (event, template) ->
$(event.target).addClass('disabled')
query = template.query.get()
Meteor.call 'export', query, (err, result) ->
if (err)
console.log err
alert "There was an error exporting the data."
else
window.open "data:text/csv;charset=utf-8," + encodeURIComponent(result)
$(event.target).removeClass('disabled')
'click .edit': () ->
toastr.remove()
Template.table.events events
Template.pendingTable.events events
Template.pendingTable.events
'click .approve-report': (e) =>
@setApproval 'setReportApproval', $(e.target).data('id'), 'approved', "Report approved"
'click .reject-report': (e) =>
@setApproval 'setReportApproval', $(e.target).data('id'), 'rejected', "Report rejected"
'click .approve-user': (e) =>
@setApproval 'setUserApproval', $(e.target).data('id'), 'approved', "User approved"
'click .reject-user': (e) =>
@setApproval 'setUserApproval', $(e.target).data('id'), 'rejected', "User rejected"
| true | getCollections = => @collections
created = ->
@query = new ReactiveVar()
Template.table.created = created
Template.pendingTable.created = created
query = ->
Template.instance().query
Template.table.query = query
Template.pendingTable.query = query
filters = =>
filters = []
query = Template.instance().query?.get() or {}
# reactive-table filters don't support arbitrary queries yet
if ! _.isEmpty query
queries = if '$and' of query then query['$and'] else [query]
filterCount = 0
for q in queries
key = Object.keys(q)[0]
value = q[key] or ""
filterId = 'reports-' + key + filterCount
filter = new ReactiveTable.Filter(filterId, [key])
if value isnt filter.get()
filter.set(value)
filters.push filterId
filterCount++
filters
Template.table.filters = filters
Template.pendingTable.filters = filters
Template.table.settings = () =>
settings 'full'
Template.table.obfuscatedSettings = () =>
settings 'obfuscated'
Template.pendingTable.settings = () =>
settings 'pending'
settings = (tableType) =>
isAdmin = Roles.userIsInRole Meteor.user(), "admin", Groups.findOne({path: 'rana'})?._id
schema = @collections.Reports.simpleSchema().schema()
fields = []
studyVars = {}
getStudyNameVar = (studyId) ->
if studyVars[studyId]
return studyVars[studyId]
else
studyNameVar = new ReactiveVar("")
studyVars[studyId] = studyNameVar
onReady = () ->
studyName = getCollections().Studies.findOne(studyId)?.name
studyNameVar.set studyName
Meteor.subscribe "studies", studyId, onReady
return studyNameVar
fields.push
key: "studyId"
label: "Study"
fn: (val, obj) ->
getStudyNameVar(val).get()
if tableType in ['full', 'pending']
fields.push
key: "eventLocation"
label: "Event Location"
fn: (val, obj) ->
if val
String(val.geo.coordinates[0]) + ', ' + String(val.geo.coordinates[1])
else
''
else
fields.push
key: "eventLocation.country"
label: "Event Location Country"
if tableType in ['full', 'pending']
columns = [
"speciesGenus"
"speciesName"
"screeningReason"
"populationType"
]
for key in columns
do (key) ->
label = schema[key].label or key
if label.length > 30
label = key
fields.push
key: key
label: label
fn: (val, object) ->
if schema[key]?.autoform?.afFieldInput?.options
option = _.findWhere(
schema[key].autoform.afFieldInput.options,
value: val
)
display = option?.label or ''
new Spacebars.SafeString("<span sort=#{sort}>#{display}</span>")
else
output = val or ''
# capitalize first letter
if output.length > 1
output = output.charAt(0).toUpperCase() + output.slice(1)
# truncate long fields
if output.length > 100
output = output.slice(0, 100) + '...'
# put empty values at the end
if output is '' then sort = 2 else sort = 1
if not output
output = ''
# use option labels instead of values
new Spacebars.SafeString("<span sort=#{sort}>#{output}</span>")
fields.push
key: "PI:KEY:<KEY>END_PI"
label: "Submitted by"
fields.push
key: "PI:KEY:<KEY>END_PI"
label: ""
hideToggle: true
fn: (val, obj) ->
if obj.createdBy.userId == Meteor.userId()
tablePath = Router.path 'table'
editPath = Router.path 'editReport', {reportId: obj._id}, {query: "redirectOnSubmit=#{tablePath}"}
new Spacebars.SafeString("""
<a class="control edit" href="#{editPath}" title="Edit"></a>
<a class="control remove remove-form" data-id="#{obj._id}" title="Remove"></a>
""")
else if isAdmin
viewPath = Router.path 'editReport', {reportId: obj._id}
new Spacebars.SafeString("""
<a class="control view" href="#{viewPath}" title="View"></a>
<a class="control remove remove-form" data-id="#{obj._id}" title="Remove"></a>
""")
else
viewPath = Router.path 'editReport', {reportId: obj._id}
new Spacebars.SafeString("""
<a class="control view" href="#{viewPath}" title="View"></a>
""")
if tableType is 'pending'
fields.push
key: "controls"
label: ""
hideToggle: true
fn: (val, obj) ->
new Spacebars.SafeString("""
<a class="control approve-report" data-id="#{obj._id}" title="Approve report"></a>
<a class="control reject-report" data-id="#{obj._id}" title="Reject Report"></a>
<a class="control approve-user" data-id="#{obj.createdBy.userId}" title="Approve User"></a>
<a class="control reject-user" data-id="#{obj.createdBy.userId}" title="Reject User`"></a>
""")
if tableType is 'pending'
noDataTmpl = Template.noPendingReports
else
noDataTmpl = Template.noReports
showColumnToggles: true
showFilter: false
fields: fields
noDataTmpl: noDataTmpl
rowClass: (val) ->
if !isAdmin
switch val.approval
when 'approved' then 'approved'
when 'rejected' then 'rejected'
when 'pending' then 'pending'
events =
'click .remove-form': (evt)->
reportId = $(evt.target).data("id")
reply = prompt('Type "delete" to confirm that this report should be removed.')
if reply == "delete"
getCollections().Reports.remove(reportId)
'click .toggle-filter': () ->
$('.filter-controls').toggleClass('hidden')
$('.toggle-filter').toggleClass('showingOpts')
"click .next-page, click .previous-page" : () ->
if (window.scrollY > 0)
$('body').animate({scrollTop:0,400})
'click .export:not(.disabled)': (event, template) ->
$(event.target).addClass('disabled')
query = template.query.get()
Meteor.call 'export', query, (err, result) ->
if (err)
console.log err
alert "There was an error exporting the data."
else
window.open "data:text/csv;charset=utf-8," + encodeURIComponent(result)
$(event.target).removeClass('disabled')
'click .edit': () ->
toastr.remove()
Template.table.events events
Template.pendingTable.events events
Template.pendingTable.events
'click .approve-report': (e) =>
@setApproval 'setReportApproval', $(e.target).data('id'), 'approved', "Report approved"
'click .reject-report': (e) =>
@setApproval 'setReportApproval', $(e.target).data('id'), 'rejected', "Report rejected"
'click .approve-user': (e) =>
@setApproval 'setUserApproval', $(e.target).data('id'), 'approved', "User approved"
'click .reject-user': (e) =>
@setApproval 'setUserApproval', $(e.target).data('id'), 'rejected', "User rejected"
|
[
{
"context": "nts = [\n {\n id: \"asd123f2d3123922\"\n name: \"Fernando Paredes\"\n phone: \"12345678\"\n },\n {\n id: \"1a902339",
"end": 1503,
"score": 0.9998571872711182,
"start": 1487,
"tag": "NAME",
"value": "Fernando Paredes"
},
{
"context": "Paredes\"\n phone: \"12345678\"\n },\n {\n id: \"1a902339bc3d3eff87f\"\n name: \"Jimena Perez\"\n phone: \"11",
"end": 1555,
"score": 0.5657440423965454,
"start": 1546,
"tag": "KEY",
"value": "a902339bc"
},
{
"context": " phone: \"12345678\"\n },\n {\n id: \"1a902339bc3d3eff87f\"\n name: \"Jimena Perez\"\n phone: \"11223344\"\n ",
"end": 1564,
"score": 0.5741524696350098,
"start": 1557,
"tag": "KEY",
"value": "3eff87f"
},
{
"context": " },\n {\n id: \"1a902339bc3d3eff87f\"\n name: \"Jimena Perez\"\n phone: \"11223344\"\n },\n {\n id: \"abcdef12",
"end": 1589,
"score": 0.9998515844345093,
"start": 1577,
"tag": "NAME",
"value": "Jimena Perez"
},
{
"context": "na Perez\"\n phone: \"11223344\"\n },\n {\n id: \"abcdef1234567890\"\n name: \"Susana Horia\"\n phone: \"22334455\"\n ",
"end": 1647,
"score": 0.7072231769561768,
"start": 1631,
"tag": "KEY",
"value": "abcdef1234567890"
},
{
"context": "4\"\n },\n {\n id: \"abcdef1234567890\"\n name: \"Susana Horia\"\n phone: \"22334455\"\n },\n]\n# #################",
"end": 1672,
"score": 0.9998513460159302,
"start": 1660,
"tag": "NAME",
"value": "Susana Horia"
}
] | assets/js/patients/patients.coffee | romeroyonatan/node-turnos | 0 |
angular.module('myApp.patients', ['ngRoute'])
.config ['$routeProvider', ($routeProvider) ->
$routeProvider.when '/patients',
templateUrl: '/partials/patient/all'
controller: 'PatientListCtrl'
$routeProvider.when '/patients/create',
templateUrl: '/partials/patient/create'
controller: 'PatientCreateCtrl'
$routeProvider.when '/patients/delete/:id',
templateUrl: 'partials/patient/delete'
controller: 'PatientDeleteCtrl'
$routeProvider.when '/patients/:id',
templateUrl: 'partials/patient/detail'
controller: 'PatientDetailCtrl'
]
.controller 'PatientListCtrl', ["$scope", ($scope) ->
$scope.patients = patients
]
.controller 'PatientDetailCtrl', ["$scope", "$routeParams", "$location",
($scope, $routeParams, $location) ->
$scope.patient = p for p in patients when p.id is $routeParams.id
]
.controller 'PatientCreateCtrl', ["$scope", "$location", ($scope, $location) ->
$scope.create = (patient) ->
patient.id = "#{patients.length + 1}"
patients.push patient
$location.path "/"
$scope.cancel = () ->
$location.path "/"
]
.controller 'PatientDeleteCtrl', ["$scope", "$location",
($scope, $location) ->
$scope.delete = (patient) ->
patients = p for p in patients when p.id isnt patient.id
$location.path "/"
]
# ############################################################################
# Esto sera reemplazado por una API RESTful
patients = [
{
id: "asd123f2d3123922"
name: "Fernando Paredes"
phone: "12345678"
},
{
id: "1a902339bc3d3eff87f"
name: "Jimena Perez"
phone: "11223344"
},
{
id: "abcdef1234567890"
name: "Susana Horia"
phone: "22334455"
},
]
# ############################################################################
| 93180 |
angular.module('myApp.patients', ['ngRoute'])
.config ['$routeProvider', ($routeProvider) ->
$routeProvider.when '/patients',
templateUrl: '/partials/patient/all'
controller: 'PatientListCtrl'
$routeProvider.when '/patients/create',
templateUrl: '/partials/patient/create'
controller: 'PatientCreateCtrl'
$routeProvider.when '/patients/delete/:id',
templateUrl: 'partials/patient/delete'
controller: 'PatientDeleteCtrl'
$routeProvider.when '/patients/:id',
templateUrl: 'partials/patient/detail'
controller: 'PatientDetailCtrl'
]
.controller 'PatientListCtrl', ["$scope", ($scope) ->
$scope.patients = patients
]
.controller 'PatientDetailCtrl', ["$scope", "$routeParams", "$location",
($scope, $routeParams, $location) ->
$scope.patient = p for p in patients when p.id is $routeParams.id
]
.controller 'PatientCreateCtrl', ["$scope", "$location", ($scope, $location) ->
$scope.create = (patient) ->
patient.id = "#{patients.length + 1}"
patients.push patient
$location.path "/"
$scope.cancel = () ->
$location.path "/"
]
.controller 'PatientDeleteCtrl', ["$scope", "$location",
($scope, $location) ->
$scope.delete = (patient) ->
patients = p for p in patients when p.id isnt patient.id
$location.path "/"
]
# ############################################################################
# Esto sera reemplazado por una API RESTful
patients = [
{
id: "asd123f2d3123922"
name: "<NAME>"
phone: "12345678"
},
{
id: "1<KEY>3d<KEY>"
name: "<NAME>"
phone: "11223344"
},
{
id: "<KEY>"
name: "<NAME>"
phone: "22334455"
},
]
# ############################################################################
| true |
angular.module('myApp.patients', ['ngRoute'])
.config ['$routeProvider', ($routeProvider) ->
$routeProvider.when '/patients',
templateUrl: '/partials/patient/all'
controller: 'PatientListCtrl'
$routeProvider.when '/patients/create',
templateUrl: '/partials/patient/create'
controller: 'PatientCreateCtrl'
$routeProvider.when '/patients/delete/:id',
templateUrl: 'partials/patient/delete'
controller: 'PatientDeleteCtrl'
$routeProvider.when '/patients/:id',
templateUrl: 'partials/patient/detail'
controller: 'PatientDetailCtrl'
]
.controller 'PatientListCtrl', ["$scope", ($scope) ->
$scope.patients = patients
]
.controller 'PatientDetailCtrl', ["$scope", "$routeParams", "$location",
($scope, $routeParams, $location) ->
$scope.patient = p for p in patients when p.id is $routeParams.id
]
.controller 'PatientCreateCtrl', ["$scope", "$location", ($scope, $location) ->
$scope.create = (patient) ->
patient.id = "#{patients.length + 1}"
patients.push patient
$location.path "/"
$scope.cancel = () ->
$location.path "/"
]
.controller 'PatientDeleteCtrl', ["$scope", "$location",
($scope, $location) ->
$scope.delete = (patient) ->
patients = p for p in patients when p.id isnt patient.id
$location.path "/"
]
# ############################################################################
# Esto sera reemplazado por una API RESTful
patients = [
{
id: "asd123f2d3123922"
name: "PI:NAME:<NAME>END_PI"
phone: "12345678"
},
{
id: "1PI:KEY:<KEY>END_PI3dPI:KEY:<KEY>END_PI"
name: "PI:NAME:<NAME>END_PI"
phone: "11223344"
},
{
id: "PI:KEY:<KEY>END_PI"
name: "PI:NAME:<NAME>END_PI"
phone: "22334455"
},
]
# ############################################################################
|
[
{
"context": "db \"#{__dirname}/../db/tmp\"\n client.users.set 'dorianb',\n lastname: 'Bagur'\n firstname: 'Doria",
"end": 336,
"score": 0.5326357483863831,
"start": 329,
"tag": "USERNAME",
"value": "dorianb"
},
{
"context": "rianb',\n lastname: 'Bagur'\n firstname: 'Dorian'\n password: '1234'\n email: 'alfred@ethy",
"end": 387,
"score": 0.9625741243362427,
"start": 381,
"tag": "NAME",
"value": "Dorian"
},
{
"context": "Bagur'\n firstname: 'Dorian'\n password: '1234'\n email: 'alfred@ethylocle.com'\n , (err) ",
"end": 410,
"score": 0.9994040131568909,
"start": 406,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "me: 'Dorian'\n password: '1234'\n email: 'alfred@ethylocle.com'\n , (err) ->\n return next err if err\n ",
"end": 446,
"score": 0.9999325275421143,
"start": 426,
"tag": "EMAIL",
"value": "alfred@ethylocle.com"
},
{
"context": "rn next err if err\n client.users.setByEmail 'alfred@ethylocle.com',\n username: 'dorianb'\n , (err) ->\n ",
"end": 543,
"score": 0.9999321699142456,
"start": 523,
"tag": "EMAIL",
"value": "alfred@ethylocle.com"
},
{
"context": "yEmail 'alfred@ethylocle.com',\n username: 'dorianb'\n , (err) ->\n return next err if err\n",
"end": 572,
"score": 0.9995947480201721,
"start": 565,
"tag": "USERNAME",
"value": "dorianb"
},
{
"context": " return next err if err\n client.users.set 'maoqiaoz',\n lastname: 'Zhou'\n firstname:",
"end": 656,
"score": 0.9573220014572144,
"start": 648,
"tag": "USERNAME",
"value": "maoqiaoz"
},
{
"context": " firstname: 'Maoqiao'\n password: '4321'\n email: 'gilbert@ethylocle.com'\n ",
"end": 742,
"score": 0.9993793368339539,
"start": 738,
"tag": "PASSWORD",
"value": "4321"
},
{
"context": "iao'\n password: '4321'\n email: 'gilbert@ethylocle.com'\n , (err) ->\n return next err if ",
"end": 783,
"score": 0.999933123588562,
"start": 762,
"tag": "EMAIL",
"value": "gilbert@ethylocle.com"
},
{
"context": "ext err if err\n client.users.setByEmail 'gilbert@ethylocle.com',\n username: 'maoqiaoz'\n , (e",
"end": 893,
"score": 0.9999317526817322,
"start": 872,
"tag": "EMAIL",
"value": "gilbert@ethylocle.com"
},
{
"context": "l 'gilbert@ethylocle.com',\n username: 'maoqiaoz'\n , (err) ->\n return next err",
"end": 927,
"score": 0.999620795249939,
"start": 919,
"tag": "USERNAME",
"value": "maoqiaoz"
},
{
"context": "son\"\n .on 'end', () ->\n client.users.get 'dorianb', (err, user) ->\n return next err if err\n ",
"end": 1394,
"score": 0.7852198481559753,
"start": 1387,
"tag": "USERNAME",
"value": "dorianb"
},
{
"context": "next err if err\n user.username.should.eql 'dorianb'\n user.lastname.should.eql 'Bagur'\n ",
"end": 1484,
"score": 0.9995880126953125,
"start": 1477,
"tag": "USERNAME",
"value": "dorianb"
},
{
"context": "ld.eql 'Bagur'\n user.firstname.should.eql 'Dorian'\n user.email.should.eql 'dorian@ethylocle.",
"end": 1568,
"score": 0.9037654399871826,
"start": 1562,
"tag": "NAME",
"value": "Dorian"
},
{
"context": "hould.eql 'Dorian'\n user.email.should.eql 'dorian@ethylocle.com'\n user.password.should.eql '1234'\n ",
"end": 1621,
"score": 0.9999302625656128,
"start": 1601,
"tag": "EMAIL",
"value": "dorian@ethylocle.com"
},
{
"context": "@ethylocle.com'\n user.password.should.eql '1234'\n client.users.get 'maoqiaoz', (err, user)",
"end": 1661,
"score": 0.9994158744812012,
"start": 1657,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "sword.should.eql '1234'\n client.users.get 'maoqiaoz', (err, user) ->\n return next err if err",
"end": 1697,
"score": 0.782084584236145,
"start": 1689,
"tag": "USERNAME",
"value": "maoqiaoz"
},
{
"context": "xt err if err\n user.username.should.eql 'maoqiaoz'\n user.lastname.should.eql 'Zhou'\n ",
"end": 1792,
"score": 0.9993560910224915,
"start": 1784,
"tag": "USERNAME",
"value": "maoqiaoz"
},
{
"context": "ql 'maoqiaoz'\n user.lastname.should.eql 'Zhou'\n user.firstname.should.eql 'Maoqiao'\n ",
"end": 1834,
"score": 0.8244167566299438,
"start": 1830,
"tag": "NAME",
"value": "Zhou"
},
{
"context": "d.eql 'Zhou'\n user.firstname.should.eql 'Maoqiao'\n user.email.should.eql 'maoqiao@eth",
"end": 1876,
"score": 0.7730416059494019,
"start": 1873,
"tag": "NAME",
"value": "Mao"
},
{
"context": "ld.eql 'Maoqiao'\n user.email.should.eql 'maoqiao@ethylocle.com'\n user.password.should.eql '1234'\n ",
"end": 1936,
"score": 0.9999345541000366,
"start": 1915,
"tag": "EMAIL",
"value": "maoqiao@ethylocle.com"
},
{
"context": "thylocle.com'\n user.password.should.eql '1234'\n client.close()\n next()\n .p",
"end": 1978,
"score": 0.9992374777793884,
"start": 1974,
"tag": "PASSWORD",
"value": "1234"
}
] | tests/export.coffee | dorianb/expressApp | 0 | rimraf = require 'rimraf'
should = require 'should'
fs = require 'fs'
exportStream = require '../lib/export'
db = require '../lib/db'
describe 'export', ->
beforeEach (next) ->
rimraf "#{__dirname}/../db/tmp", next
it 'Export to sample.csv', (next) ->
###client = db "#{__dirname}/../db/tmp"
client.users.set 'dorianb',
lastname: 'Bagur'
firstname: 'Dorian'
password: '1234'
email: 'alfred@ethylocle.com'
, (err) ->
return next err if err
client.users.setByEmail 'alfred@ethylocle.com',
username: 'dorianb'
, (err) ->
return next err if err
client.users.set 'maoqiaoz',
lastname: 'Zhou'
firstname: 'Maoqiao'
password: '4321'
email: 'gilbert@ethylocle.com'
, (err) ->
return next err if err
client.users.setByEmail 'gilbert@ethylocle.com',
username: 'maoqiaoz'
, (err) ->
return next err if err
exportStream client, format: 'csv'
.on 'end', () ->
client.close()
next()
.pipe fs.createWriteStream "#{__dirname}/../exportation.csv"###
next()
it 'Export to sample.json', (next) ->
###client = db "#{__dirname}/../db/tmp"
fs
.createReadStream "#{__dirname}/../sample.json"
.on 'end', () ->
client.users.get 'dorianb', (err, user) ->
return next err if err
user.username.should.eql 'dorianb'
user.lastname.should.eql 'Bagur'
user.firstname.should.eql 'Dorian'
user.email.should.eql 'dorian@ethylocle.com'
user.password.should.eql '1234'
client.users.get 'maoqiaoz', (err, user) ->
return next err if err
user.username.should.eql 'maoqiaoz'
user.lastname.should.eql 'Zhou'
user.firstname.should.eql 'Maoqiao'
user.email.should.eql 'maoqiao@ethylocle.com'
user.password.should.eql '1234'
client.close()
next()
.pipe importStream client, format: 'json'###
next()
| 40547 | rimraf = require 'rimraf'
should = require 'should'
fs = require 'fs'
exportStream = require '../lib/export'
db = require '../lib/db'
describe 'export', ->
beforeEach (next) ->
rimraf "#{__dirname}/../db/tmp", next
it 'Export to sample.csv', (next) ->
###client = db "#{__dirname}/../db/tmp"
client.users.set 'dorianb',
lastname: 'Bagur'
firstname: '<NAME>'
password: '<PASSWORD>'
email: '<EMAIL>'
, (err) ->
return next err if err
client.users.setByEmail '<EMAIL>',
username: 'dorianb'
, (err) ->
return next err if err
client.users.set 'maoqiaoz',
lastname: 'Zhou'
firstname: 'Maoqiao'
password: '<PASSWORD>'
email: '<EMAIL>'
, (err) ->
return next err if err
client.users.setByEmail '<EMAIL>',
username: 'maoqiaoz'
, (err) ->
return next err if err
exportStream client, format: 'csv'
.on 'end', () ->
client.close()
next()
.pipe fs.createWriteStream "#{__dirname}/../exportation.csv"###
next()
it 'Export to sample.json', (next) ->
###client = db "#{__dirname}/../db/tmp"
fs
.createReadStream "#{__dirname}/../sample.json"
.on 'end', () ->
client.users.get 'dorianb', (err, user) ->
return next err if err
user.username.should.eql 'dorianb'
user.lastname.should.eql 'Bagur'
user.firstname.should.eql '<NAME>'
user.email.should.eql '<EMAIL>'
user.password.should.eql '<PASSWORD>'
client.users.get 'maoqiaoz', (err, user) ->
return next err if err
user.username.should.eql 'maoqiaoz'
user.lastname.should.eql '<NAME>'
user.firstname.should.eql '<NAME>qiao'
user.email.should.eql '<EMAIL>'
user.password.should.eql '<PASSWORD>'
client.close()
next()
.pipe importStream client, format: 'json'###
next()
| true | rimraf = require 'rimraf'
should = require 'should'
fs = require 'fs'
exportStream = require '../lib/export'
db = require '../lib/db'
describe 'export', ->
beforeEach (next) ->
rimraf "#{__dirname}/../db/tmp", next
it 'Export to sample.csv', (next) ->
###client = db "#{__dirname}/../db/tmp"
client.users.set 'dorianb',
lastname: 'Bagur'
firstname: 'PI:NAME:<NAME>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
, (err) ->
return next err if err
client.users.setByEmail 'PI:EMAIL:<EMAIL>END_PI',
username: 'dorianb'
, (err) ->
return next err if err
client.users.set 'maoqiaoz',
lastname: 'Zhou'
firstname: 'Maoqiao'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
, (err) ->
return next err if err
client.users.setByEmail 'PI:EMAIL:<EMAIL>END_PI',
username: 'maoqiaoz'
, (err) ->
return next err if err
exportStream client, format: 'csv'
.on 'end', () ->
client.close()
next()
.pipe fs.createWriteStream "#{__dirname}/../exportation.csv"###
next()
it 'Export to sample.json', (next) ->
###client = db "#{__dirname}/../db/tmp"
fs
.createReadStream "#{__dirname}/../sample.json"
.on 'end', () ->
client.users.get 'dorianb', (err, user) ->
return next err if err
user.username.should.eql 'dorianb'
user.lastname.should.eql 'Bagur'
user.firstname.should.eql 'PI:NAME:<NAME>END_PI'
user.email.should.eql 'PI:EMAIL:<EMAIL>END_PI'
user.password.should.eql 'PI:PASSWORD:<PASSWORD>END_PI'
client.users.get 'maoqiaoz', (err, user) ->
return next err if err
user.username.should.eql 'maoqiaoz'
user.lastname.should.eql 'PI:NAME:<NAME>END_PI'
user.firstname.should.eql 'PI:NAME:<NAME>END_PIqiao'
user.email.should.eql 'PI:EMAIL:<EMAIL>END_PI'
user.password.should.eql 'PI:PASSWORD:<PASSWORD>END_PI'
client.close()
next()
.pipe importStream client, format: 'json'###
next()
|
[
{
"context": ".log (id_in)\n\nconfig = {\n\tuser: 'sa',\n\tpassword: 'scott_tiger',\n\tserver: 'host_mssql',\n\tdatabase: 'city',\n}\n\nco",
"end": 488,
"score": 0.9988526105880737,
"start": 477,
"tag": "PASSWORD",
"value": "scott_tiger"
}
] | mssql/coffee/delete/mssql_delete.coffee | ekzemplaro/data_base_language | 3 | #! /usr/bin/coffee
# ---------------------------------------------------------------
# mssql_delete.coffee
#
# Jul/03/2014
#
# ---------------------------------------------------------------
mssql = require('mssql')
sql_manipulate= require ('/var/www/data_base/common/node_common/sql_manipulate')
# ---------------------------------------------------------------
console.log "*** 開始 ***"
id_in = process.argv[2]
console.log (id_in)
config = {
user: 'sa',
password: 'scott_tiger',
server: 'host_mssql',
database: 'city',
}
connection = new mssql.Connection(config, (err) ->
request = new mssql.Request(connection)
command = sql_manipulate.delete_command_gen (id_in)
request.query(command, (err, rows) ->
if (err)
throw err
console.log "*** 終了 ***"
)
connection.close()
)
# ---------------------------------------------------------------
| 177179 | #! /usr/bin/coffee
# ---------------------------------------------------------------
# mssql_delete.coffee
#
# Jul/03/2014
#
# ---------------------------------------------------------------
mssql = require('mssql')
sql_manipulate= require ('/var/www/data_base/common/node_common/sql_manipulate')
# ---------------------------------------------------------------
console.log "*** 開始 ***"
id_in = process.argv[2]
console.log (id_in)
config = {
user: 'sa',
password: '<PASSWORD>',
server: 'host_mssql',
database: 'city',
}
connection = new mssql.Connection(config, (err) ->
request = new mssql.Request(connection)
command = sql_manipulate.delete_command_gen (id_in)
request.query(command, (err, rows) ->
if (err)
throw err
console.log "*** 終了 ***"
)
connection.close()
)
# ---------------------------------------------------------------
| true | #! /usr/bin/coffee
# ---------------------------------------------------------------
# mssql_delete.coffee
#
# Jul/03/2014
#
# ---------------------------------------------------------------
mssql = require('mssql')
sql_manipulate= require ('/var/www/data_base/common/node_common/sql_manipulate')
# ---------------------------------------------------------------
console.log "*** 開始 ***"
id_in = process.argv[2]
console.log (id_in)
config = {
user: 'sa',
password: 'PI:PASSWORD:<PASSWORD>END_PI',
server: 'host_mssql',
database: 'city',
}
connection = new mssql.Connection(config, (err) ->
request = new mssql.Request(connection)
command = sql_manipulate.delete_command_gen (id_in)
request.query(command, (err, rows) ->
if (err)
throw err
console.log "*** 終了 ***"
)
connection.close()
)
# ---------------------------------------------------------------
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9991492629051208,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | lib/_stream_passthrough.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# a passthrough stream.
# basically just the most minimal sort of Transform stream.
# Every written chunk gets output as-is.
PassThrough = (options) ->
return new PassThrough(options) unless this instanceof PassThrough
Transform.call this, options
return
"use strict"
module.exports = PassThrough
Transform = require("_stream_transform")
util = require("util")
util.inherits PassThrough, Transform
PassThrough::_transform = (chunk, encoding, cb) ->
cb null, chunk
return
| 111729 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# a passthrough stream.
# basically just the most minimal sort of Transform stream.
# Every written chunk gets output as-is.
PassThrough = (options) ->
return new PassThrough(options) unless this instanceof PassThrough
Transform.call this, options
return
"use strict"
module.exports = PassThrough
Transform = require("_stream_transform")
util = require("util")
util.inherits PassThrough, Transform
PassThrough::_transform = (chunk, encoding, cb) ->
cb null, chunk
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
# a passthrough stream.
# basically just the most minimal sort of Transform stream.
# Every written chunk gets output as-is.
PassThrough = (options) ->
return new PassThrough(options) unless this instanceof PassThrough
Transform.call this, options
return
"use strict"
module.exports = PassThrough
Transform = require("_stream_transform")
util = require("util")
util.inherits PassThrough, Transform
PassThrough::_transform = (chunk, encoding, cb) ->
cb null, chunk
return
|
[
{
"context": "/app/js/infrastructure/LockManager.js'\nlockKey = \"lock:web:{#{5678}}\"\nlockValue = \"123456\"\nSandboxedModule = require('s",
"end": 193,
"score": 0.9927215576171875,
"start": 174,
"tag": "KEY",
"value": "lock:web:{#{5678}}\""
}
] | test/unit/coffee/infrastructure/LockManager/ReleasingTheLock.coffee | davidmehren/web-sharelatex | 1 | sinon = require('sinon')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
lockKey = "lock:web:{#{5678}}"
lockValue = "123456"
SandboxedModule = require('sandboxed-module')
describe 'LockManager - releasing the lock', ()->
deleteStub = sinon.stub().callsArgWith(4)
mocks =
"logger-sharelatex": log:->
"./RedisWrapper":
client: ()->
auth:->
eval:deleteStub
LockManager = SandboxedModule.require(modulePath, requires: mocks)
LockManager.unlockScript = "this is the unlock script"
it 'should put a all data into memory', (done)->
LockManager._releaseLock lockKey, lockValue, ->
deleteStub.calledWith(LockManager.unlockScript, 1, lockKey, lockValue).should.equal true
done()
| 191725 | sinon = require('sinon')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
lockKey = "<KEY>
lockValue = "123456"
SandboxedModule = require('sandboxed-module')
describe 'LockManager - releasing the lock', ()->
deleteStub = sinon.stub().callsArgWith(4)
mocks =
"logger-sharelatex": log:->
"./RedisWrapper":
client: ()->
auth:->
eval:deleteStub
LockManager = SandboxedModule.require(modulePath, requires: mocks)
LockManager.unlockScript = "this is the unlock script"
it 'should put a all data into memory', (done)->
LockManager._releaseLock lockKey, lockValue, ->
deleteStub.calledWith(LockManager.unlockScript, 1, lockKey, lockValue).should.equal true
done()
| true | sinon = require('sinon')
assert = require('assert')
path = require('path')
modulePath = path.join __dirname, '../../../../../app/js/infrastructure/LockManager.js'
lockKey = "PI:KEY:<KEY>END_PI
lockValue = "123456"
SandboxedModule = require('sandboxed-module')
describe 'LockManager - releasing the lock', ()->
deleteStub = sinon.stub().callsArgWith(4)
mocks =
"logger-sharelatex": log:->
"./RedisWrapper":
client: ()->
auth:->
eval:deleteStub
LockManager = SandboxedModule.require(modulePath, requires: mocks)
LockManager.unlockScript = "this is the unlock script"
it 'should put a all data into memory', (done)->
LockManager._releaseLock lockKey, lockValue, ->
deleteStub.calledWith(LockManager.unlockScript, 1, lockKey, lockValue).should.equal true
done()
|
[
{
"context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# L",
"end": 35,
"score": 0.9998745322227478,
"start": 21,
"tag": "NAME",
"value": "JeongHoon Byun"
},
{
"context": "# Copyright (c) 2013 JeongHoon Byun aka \"Outsider\", <http://blog.outsider.ne.kr/>\n# Licensed under ",
"end": 49,
"score": 0.9858162999153137,
"start": 41,
"tag": "USERNAME",
"value": "Outsider"
}
] | test/parser/java-parser.test.coffee | uppalapatisujitha/CodingConventionofCommitHistory | 421 | # Copyright (c) 2013 JeongHoon Byun aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/java-parser'
describe 'java-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'public String getName{}', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' public String getName{}', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' public String getName{}', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\tpublic String getName{}', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\tpublic String getName{}', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t public String getName{} ', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \tpublic String getName{}', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'public String getName{}', {}
convention.indent.tab.should.equal 0
describe 'blockstatement >', ->
it 'check block statement with one space #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT) { return; }', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #2', ->
convention = parser.blockstatement '} else if (height < MIN_HIGHT) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #3', ->
convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #4', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #5', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT){ return; }', {}
convention.blockstatement.onespace.should.equal 0
it 'check block statement with one space #6', ->
convention = parser.blockstatement 'if (isTrue()) { return; }', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with no space #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT){ return (); }', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement with no space #2', ->
convention = parser.blockstatement '}else if (height < MIN_HIGHT){', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement with no space #3', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)', {}
convention.blockstatement.nospace.should.equal 0
it 'check block statement with no space #4', ->
convention = parser.blockstatement '} else if(height < MIN_HIGHT) {', {}
convention.blockstatement.nospace.should.equal 0
it 'check block statement with no space #5', ->
convention = parser.blockstatement '} else if(isTrue()){', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement at new line #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #2', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT) // comment', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #3', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)/* */', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #4', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT)', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #5', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #6', ->
convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {}
convention.blockstatement.newline.should.equal 0
it 'check block statement at new line #7', ->
convention = parser.blockstatement 'if ( isTrue() ) //{}', {}
convention.blockstatement.newline.should.equal 1
describe 'constant >', ->
it 'check constant with all caps #1', ->
convention = parser.constant ' static public final String FOOBAR= "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #2', ->
convention = parser.constant ' public static final String FOOBAR2= "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #3', ->
convention = parser.constant 'private final static String FOO_BAR = "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #4', ->
convention = parser.constant 'final public static String FOO_BAR = "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #5', ->
convention = parser.constant ' public final String foobar = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with all caps #6', ->
convention = parser.constant 'public final String FOOBAR = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with all caps #7', ->
convention = parser.constant 'private final static String FOOBARa = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with not all caps #1', ->
convention = parser.constant ' static public final String foobar= "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #2', ->
convention = parser.constant ' public static final String foobar2= "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #3', ->
convention = parser.constant 'public final static String FOOBARa = "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #4', ->
convention = parser.constant 'final public static String FOo_BAR = "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #5', ->
convention = parser.constant ' public static final String FOO_BAR= "";', {}
convention.constant.notallcaps.should.equal 0
it 'check constant with not all caps #6', ->
convention = parser.constant ' public final String Foo= "";', {}
convention.constant.notallcaps.should.equal 0
describe 'conditionstatement >', ->
it 'check condition statement with one space #1', ->
convention = parser.conditionstatement 'if ( a.equal("")) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #2', ->
convention = parser.conditionstatement 'while ( isTrue() ) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #3', ->
convention = parser.conditionstatement 'switch (name) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #4', ->
convention = parser.conditionstatement 'if( isTrue()) {', {}
convention.conditionstatement.onespace.should.equal 0
it 'check condition statement with no space #1', ->
convention = parser.conditionstatement 'if( isTrue()) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #2', ->
convention = parser.conditionstatement 'while( isTrue() ) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #3', ->
convention = parser.conditionstatement 'switch(name) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #4', ->
convention = parser.conditionstatement 'if ( a.equal("")) {', {}
convention.conditionstatement.nospace.should.equal 0
describe 'argumentdef >', ->
it 'check argument definition with one space #1', ->
convention = parser.argumentdef 'public void setName11( String name ) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #2', ->
convention = parser.argumentdef ' public void setName( String name ) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #3', ->
convention = parser.argumentdef '\t\tpublic void setName( String name, Sting age) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #4', ->
convention = parser.argumentdef 'if ( isTrue() ) {}', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #5', ->
convention = parser.argumentdef 'while ( isTrue() ) {}', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #6', ->
convention = parser.argumentdef 'public void setName11(String name ) {', {}
convention.argumentdef.onespace.should.equal 0
it 'check argument definition with no space #1', ->
convention = parser.argumentdef 'public void setName(String name) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #2', ->
convention = parser.argumentdef '\t\tpublic void setName(String name) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #3', ->
convention = parser.argumentdef 'public void setName(String name, Sting age) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #4', ->
convention = parser.argumentdef 'if (isTrue()) {}', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #5', ->
convention = parser.argumentdef 'while (isTrue()) {}', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #6', ->
convention = parser.argumentdef '/t/tpublic void setName( String name) {', {}
convention.argumentdef.nospace.should.equal 0
describe 'linelength >', ->
it 'line length is 80 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #3', ->
convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 0
it 'line length is 120 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #3', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char120.should.equal 0
it 'line length is 150 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {}
convention.linelength.char150.should.equal 1
describe 'staticvar >', ->
it 'static variable with special prefix #1', ->
convention = parser.staticvar ' static String _name;', {}
convention.staticvar.prefix.should.equal 1
it 'static variable with special prefix #2', ->
convention = parser.staticvar ' static String $name;', {}
convention.staticvar.prefix.should.equal 1
it 'static variable with special prefix #3', ->
convention = parser.staticvar ' static String name;', {}
convention.staticvar.prefix.should.equal 0
it 'static variable with no special prefix #1', ->
convention = parser.staticvar ' static String _name;', {}
convention.staticvar.noprefix.should.equal 0
it 'static variable with no special prefix #2', ->
convention = parser.staticvar ' static String $name;', {}
convention.staticvar.noprefix.should.equal 0
it 'static variable with no special prefix #3', ->
convention = parser.staticvar ' static String name;', {}
convention.staticvar.noprefix.should.equal 1
describe 'finalstaticorder >', ->
it 'public - static - final #1', ->
convention = parser.finalstaticorder 'public static final String t1 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #2', ->
convention = parser.finalstaticorder 'public static transient final String t2 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #3', ->
convention = parser.finalstaticorder 'transient public static final String t3 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #4', ->
convention = parser.finalstaticorder 'public final static String t4 = "";', {}
convention.finalstaticorder.accstfin.should.equal 0
it 'public - final - static #1', ->
convention = parser.finalstaticorder 'public final static String t1 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #2', ->
convention = parser.finalstaticorder 'public final static transient String t2 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #3', ->
convention = parser.finalstaticorder 'transient public final static String t3 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #4', ->
convention = parser.finalstaticorder 'final public static String t4 = "";', {}
convention.finalstaticorder.accfinst.should.equal 0
it 'final - public - static #1', ->
convention = parser.finalstaticorder 'final public static String t1 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #2', ->
convention = parser.finalstaticorder 'final public static transient String t2 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #3', ->
convention = parser.finalstaticorder 'final transient public static String t3 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #4', ->
convention = parser.finalstaticorder 'static public final String t4 = "";', {}
convention.finalstaticorder.finaccst.should.equal 0
it 'final - public - static #1', ->
convention = parser.finalstaticorder 'static public final String t1 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #2', ->
convention = parser.finalstaticorder 'static public transient final String t2 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #3', ->
convention = parser.finalstaticorder 'static transient public final String t3 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #4', ->
convention = parser.finalstaticorder 'public static final String t4 = "";', {}
convention.finalstaticorder.staccfin.should.equal 0
| 69049 | # Copyright (c) 2013 <NAME> aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/java-parser'
describe 'java-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'public String getName{}', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' public String getName{}', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' public String getName{}', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\tpublic String getName{}', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\tpublic String getName{}', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t public String getName{} ', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \tpublic String getName{}', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'public String getName{}', {}
convention.indent.tab.should.equal 0
describe 'blockstatement >', ->
it 'check block statement with one space #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT) { return; }', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #2', ->
convention = parser.blockstatement '} else if (height < MIN_HIGHT) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #3', ->
convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #4', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #5', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT){ return; }', {}
convention.blockstatement.onespace.should.equal 0
it 'check block statement with one space #6', ->
convention = parser.blockstatement 'if (isTrue()) { return; }', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with no space #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT){ return (); }', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement with no space #2', ->
convention = parser.blockstatement '}else if (height < MIN_HIGHT){', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement with no space #3', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)', {}
convention.blockstatement.nospace.should.equal 0
it 'check block statement with no space #4', ->
convention = parser.blockstatement '} else if(height < MIN_HIGHT) {', {}
convention.blockstatement.nospace.should.equal 0
it 'check block statement with no space #5', ->
convention = parser.blockstatement '} else if(isTrue()){', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement at new line #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #2', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT) // comment', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #3', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)/* */', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #4', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT)', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #5', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #6', ->
convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {}
convention.blockstatement.newline.should.equal 0
it 'check block statement at new line #7', ->
convention = parser.blockstatement 'if ( isTrue() ) //{}', {}
convention.blockstatement.newline.should.equal 1
describe 'constant >', ->
it 'check constant with all caps #1', ->
convention = parser.constant ' static public final String FOOBAR= "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #2', ->
convention = parser.constant ' public static final String FOOBAR2= "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #3', ->
convention = parser.constant 'private final static String FOO_BAR = "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #4', ->
convention = parser.constant 'final public static String FOO_BAR = "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #5', ->
convention = parser.constant ' public final String foobar = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with all caps #6', ->
convention = parser.constant 'public final String FOOBAR = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with all caps #7', ->
convention = parser.constant 'private final static String FOOBARa = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with not all caps #1', ->
convention = parser.constant ' static public final String foobar= "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #2', ->
convention = parser.constant ' public static final String foobar2= "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #3', ->
convention = parser.constant 'public final static String FOOBARa = "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #4', ->
convention = parser.constant 'final public static String FOo_BAR = "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #5', ->
convention = parser.constant ' public static final String FOO_BAR= "";', {}
convention.constant.notallcaps.should.equal 0
it 'check constant with not all caps #6', ->
convention = parser.constant ' public final String Foo= "";', {}
convention.constant.notallcaps.should.equal 0
describe 'conditionstatement >', ->
it 'check condition statement with one space #1', ->
convention = parser.conditionstatement 'if ( a.equal("")) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #2', ->
convention = parser.conditionstatement 'while ( isTrue() ) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #3', ->
convention = parser.conditionstatement 'switch (name) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #4', ->
convention = parser.conditionstatement 'if( isTrue()) {', {}
convention.conditionstatement.onespace.should.equal 0
it 'check condition statement with no space #1', ->
convention = parser.conditionstatement 'if( isTrue()) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #2', ->
convention = parser.conditionstatement 'while( isTrue() ) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #3', ->
convention = parser.conditionstatement 'switch(name) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #4', ->
convention = parser.conditionstatement 'if ( a.equal("")) {', {}
convention.conditionstatement.nospace.should.equal 0
describe 'argumentdef >', ->
it 'check argument definition with one space #1', ->
convention = parser.argumentdef 'public void setName11( String name ) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #2', ->
convention = parser.argumentdef ' public void setName( String name ) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #3', ->
convention = parser.argumentdef '\t\tpublic void setName( String name, Sting age) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #4', ->
convention = parser.argumentdef 'if ( isTrue() ) {}', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #5', ->
convention = parser.argumentdef 'while ( isTrue() ) {}', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #6', ->
convention = parser.argumentdef 'public void setName11(String name ) {', {}
convention.argumentdef.onespace.should.equal 0
it 'check argument definition with no space #1', ->
convention = parser.argumentdef 'public void setName(String name) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #2', ->
convention = parser.argumentdef '\t\tpublic void setName(String name) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #3', ->
convention = parser.argumentdef 'public void setName(String name, Sting age) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #4', ->
convention = parser.argumentdef 'if (isTrue()) {}', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #5', ->
convention = parser.argumentdef 'while (isTrue()) {}', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #6', ->
convention = parser.argumentdef '/t/tpublic void setName( String name) {', {}
convention.argumentdef.nospace.should.equal 0
describe 'linelength >', ->
it 'line length is 80 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #3', ->
convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 0
it 'line length is 120 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #3', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char120.should.equal 0
it 'line length is 150 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {}
convention.linelength.char150.should.equal 1
describe 'staticvar >', ->
it 'static variable with special prefix #1', ->
convention = parser.staticvar ' static String _name;', {}
convention.staticvar.prefix.should.equal 1
it 'static variable with special prefix #2', ->
convention = parser.staticvar ' static String $name;', {}
convention.staticvar.prefix.should.equal 1
it 'static variable with special prefix #3', ->
convention = parser.staticvar ' static String name;', {}
convention.staticvar.prefix.should.equal 0
it 'static variable with no special prefix #1', ->
convention = parser.staticvar ' static String _name;', {}
convention.staticvar.noprefix.should.equal 0
it 'static variable with no special prefix #2', ->
convention = parser.staticvar ' static String $name;', {}
convention.staticvar.noprefix.should.equal 0
it 'static variable with no special prefix #3', ->
convention = parser.staticvar ' static String name;', {}
convention.staticvar.noprefix.should.equal 1
describe 'finalstaticorder >', ->
it 'public - static - final #1', ->
convention = parser.finalstaticorder 'public static final String t1 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #2', ->
convention = parser.finalstaticorder 'public static transient final String t2 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #3', ->
convention = parser.finalstaticorder 'transient public static final String t3 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #4', ->
convention = parser.finalstaticorder 'public final static String t4 = "";', {}
convention.finalstaticorder.accstfin.should.equal 0
it 'public - final - static #1', ->
convention = parser.finalstaticorder 'public final static String t1 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #2', ->
convention = parser.finalstaticorder 'public final static transient String t2 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #3', ->
convention = parser.finalstaticorder 'transient public final static String t3 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #4', ->
convention = parser.finalstaticorder 'final public static String t4 = "";', {}
convention.finalstaticorder.accfinst.should.equal 0
it 'final - public - static #1', ->
convention = parser.finalstaticorder 'final public static String t1 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #2', ->
convention = parser.finalstaticorder 'final public static transient String t2 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #3', ->
convention = parser.finalstaticorder 'final transient public static String t3 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #4', ->
convention = parser.finalstaticorder 'static public final String t4 = "";', {}
convention.finalstaticorder.finaccst.should.equal 0
it 'final - public - static #1', ->
convention = parser.finalstaticorder 'static public final String t1 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #2', ->
convention = parser.finalstaticorder 'static public transient final String t2 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #3', ->
convention = parser.finalstaticorder 'static transient public final String t3 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #4', ->
convention = parser.finalstaticorder 'public static final String t4 = "";', {}
convention.finalstaticorder.staccfin.should.equal 0
| true | # Copyright (c) 2013 PI:NAME:<NAME>END_PI aka "Outsider", <http://blog.outsider.ne.kr/>
# Licensed under the MIT license.
# <http://outsider.mit-license.org/>
should = require 'should'
parser = require '../../src/parser/java-parser'
describe 'java-parser >', ->
describe 'indent >', ->
it 'check space indent #1', ->
convention = parser.indent 'public String getName{}', {}
convention.indent.space.should.equal 0
it 'check space indent #2', ->
convention = parser.indent ' public String getName{}', {}
convention.indent.space.should.equal 1
it 'check space indent #3', ->
convention = parser.indent ' public String getName{}', {}
convention.indent.space.should.equal 1
it 'check tab indent #1', ->
convention = parser.indent '\tpublic String getName{}', {}
convention.indent.tab.should.equal 1
it 'check tab indent #2', ->
convention = parser.indent '\t\tpublic String getName{}', {}
convention.indent.tab.should.equal 1
it 'check tab indent #3', ->
convention = parser.indent '\t\t public String getName{} ', {}
convention.indent.tab.should.equal 1
it 'check tab indent #4', ->
convention = parser.indent ' \tpublic String getName{}', {}
convention.indent.tab.should.equal 0
it 'check tab indent #5', ->
convention = parser.indent 'public String getName{}', {}
convention.indent.tab.should.equal 0
describe 'blockstatement >', ->
it 'check block statement with one space #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT) { return; }', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #2', ->
convention = parser.blockstatement '} else if (height < MIN_HIGHT) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #3', ->
convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #4', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with one space #5', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT){ return; }', {}
convention.blockstatement.onespace.should.equal 0
it 'check block statement with one space #6', ->
convention = parser.blockstatement 'if (isTrue()) { return; }', {}
convention.blockstatement.onespace.should.equal 1
it 'check block statement with no space #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT){ return (); }', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement with no space #2', ->
convention = parser.blockstatement '}else if (height < MIN_HIGHT){', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement with no space #3', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)', {}
convention.blockstatement.nospace.should.equal 0
it 'check block statement with no space #4', ->
convention = parser.blockstatement '} else if(height < MIN_HIGHT) {', {}
convention.blockstatement.nospace.should.equal 0
it 'check block statement with no space #5', ->
convention = parser.blockstatement '} else if(isTrue()){', {}
convention.blockstatement.nospace.should.equal 1
it 'check block statement at new line #1', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #2', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT) // comment', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #3', ->
convention = parser.blockstatement 'if (height < MIN_HIGHT)/* */', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #4', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT)', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #5', ->
convention = parser.blockstatement 'else if (height < MIN_HIGHT) {', {}
convention.blockstatement.newline.should.equal 1
it 'check block statement at new line #6', ->
convention = parser.blockstatement '} else if ( height < MIN_HIGHT ) {', {}
convention.blockstatement.newline.should.equal 0
it 'check block statement at new line #7', ->
convention = parser.blockstatement 'if ( isTrue() ) //{}', {}
convention.blockstatement.newline.should.equal 1
describe 'constant >', ->
it 'check constant with all caps #1', ->
convention = parser.constant ' static public final String FOOBAR= "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #2', ->
convention = parser.constant ' public static final String FOOBAR2= "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #3', ->
convention = parser.constant 'private final static String FOO_BAR = "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #4', ->
convention = parser.constant 'final public static String FOO_BAR = "";', {}
convention.constant.allcaps.should.equal 1
it 'check constant with all caps #5', ->
convention = parser.constant ' public final String foobar = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with all caps #6', ->
convention = parser.constant 'public final String FOOBAR = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with all caps #7', ->
convention = parser.constant 'private final static String FOOBARa = "";', {}
convention.constant.allcaps.should.equal 0
it 'check constant with not all caps #1', ->
convention = parser.constant ' static public final String foobar= "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #2', ->
convention = parser.constant ' public static final String foobar2= "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #3', ->
convention = parser.constant 'public final static String FOOBARa = "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #4', ->
convention = parser.constant 'final public static String FOo_BAR = "";', {}
convention.constant.notallcaps.should.equal 1
it 'check constant with not all caps #5', ->
convention = parser.constant ' public static final String FOO_BAR= "";', {}
convention.constant.notallcaps.should.equal 0
it 'check constant with not all caps #6', ->
convention = parser.constant ' public final String Foo= "";', {}
convention.constant.notallcaps.should.equal 0
describe 'conditionstatement >', ->
it 'check condition statement with one space #1', ->
convention = parser.conditionstatement 'if ( a.equal("")) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #2', ->
convention = parser.conditionstatement 'while ( isTrue() ) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #3', ->
convention = parser.conditionstatement 'switch (name) {', {}
convention.conditionstatement.onespace.should.equal 1
it 'check condition statement with one space #4', ->
convention = parser.conditionstatement 'if( isTrue()) {', {}
convention.conditionstatement.onespace.should.equal 0
it 'check condition statement with no space #1', ->
convention = parser.conditionstatement 'if( isTrue()) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #2', ->
convention = parser.conditionstatement 'while( isTrue() ) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #3', ->
convention = parser.conditionstatement 'switch(name) {', {}
convention.conditionstatement.nospace.should.equal 1
it 'check condition statement with no space #4', ->
convention = parser.conditionstatement 'if ( a.equal("")) {', {}
convention.conditionstatement.nospace.should.equal 0
describe 'argumentdef >', ->
it 'check argument definition with one space #1', ->
convention = parser.argumentdef 'public void setName11( String name ) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #2', ->
convention = parser.argumentdef ' public void setName( String name ) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #3', ->
convention = parser.argumentdef '\t\tpublic void setName( String name, Sting age) {', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #4', ->
convention = parser.argumentdef 'if ( isTrue() ) {}', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #5', ->
convention = parser.argumentdef 'while ( isTrue() ) {}', {}
convention.argumentdef.onespace.should.equal 1
it 'check argument definition with one space #6', ->
convention = parser.argumentdef 'public void setName11(String name ) {', {}
convention.argumentdef.onespace.should.equal 0
it 'check argument definition with no space #1', ->
convention = parser.argumentdef 'public void setName(String name) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #2', ->
convention = parser.argumentdef '\t\tpublic void setName(String name) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #3', ->
convention = parser.argumentdef 'public void setName(String name, Sting age) {', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #4', ->
convention = parser.argumentdef 'if (isTrue()) {}', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #5', ->
convention = parser.argumentdef 'while (isTrue()) {}', {}
convention.argumentdef.nospace.should.equal 1
it 'check argument definition with no space #6', ->
convention = parser.argumentdef '/t/tpublic void setName( String name) {', {}
convention.argumentdef.nospace.should.equal 0
describe 'linelength >', ->
it 'line length is 80 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 1
it 'line length is 80 characters #3', ->
convention = parser.linelength '\t\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char80.should.equal 0
it 'line length is 120 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #2', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age, String job) { return \"a\"; }', {}
convention.linelength.char120.should.equal 1
it 'line length is 120 characters #3', ->
convention = parser.linelength '\t\tpublic String findFirstName( String name, String age) { return \"a\"; }', {}
convention.linelength.char120.should.equal 0
it 'line length is 150 characters #1', ->
convention = parser.linelength ' public String findFirstName( String name, String age, String job) { return \"a\"; } //afijfjeovjfiejffjeifjidjvosjfiejfioejovfjeifjiejfosjfioejfoiejfoi', {}
convention.linelength.char150.should.equal 1
describe 'staticvar >', ->
it 'static variable with special prefix #1', ->
convention = parser.staticvar ' static String _name;', {}
convention.staticvar.prefix.should.equal 1
it 'static variable with special prefix #2', ->
convention = parser.staticvar ' static String $name;', {}
convention.staticvar.prefix.should.equal 1
it 'static variable with special prefix #3', ->
convention = parser.staticvar ' static String name;', {}
convention.staticvar.prefix.should.equal 0
it 'static variable with no special prefix #1', ->
convention = parser.staticvar ' static String _name;', {}
convention.staticvar.noprefix.should.equal 0
it 'static variable with no special prefix #2', ->
convention = parser.staticvar ' static String $name;', {}
convention.staticvar.noprefix.should.equal 0
it 'static variable with no special prefix #3', ->
convention = parser.staticvar ' static String name;', {}
convention.staticvar.noprefix.should.equal 1
describe 'finalstaticorder >', ->
it 'public - static - final #1', ->
convention = parser.finalstaticorder 'public static final String t1 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #2', ->
convention = parser.finalstaticorder 'public static transient final String t2 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #3', ->
convention = parser.finalstaticorder 'transient public static final String t3 = "";', {}
convention.finalstaticorder.accstfin.should.equal 1
it 'public - static - final #4', ->
convention = parser.finalstaticorder 'public final static String t4 = "";', {}
convention.finalstaticorder.accstfin.should.equal 0
it 'public - final - static #1', ->
convention = parser.finalstaticorder 'public final static String t1 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #2', ->
convention = parser.finalstaticorder 'public final static transient String t2 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #3', ->
convention = parser.finalstaticorder 'transient public final static String t3 = "";', {}
convention.finalstaticorder.accfinst.should.equal 1
it 'public - final - static #4', ->
convention = parser.finalstaticorder 'final public static String t4 = "";', {}
convention.finalstaticorder.accfinst.should.equal 0
it 'final - public - static #1', ->
convention = parser.finalstaticorder 'final public static String t1 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #2', ->
convention = parser.finalstaticorder 'final public static transient String t2 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #3', ->
convention = parser.finalstaticorder 'final transient public static String t3 = "";', {}
convention.finalstaticorder.finaccst.should.equal 1
it 'final - public - static #4', ->
convention = parser.finalstaticorder 'static public final String t4 = "";', {}
convention.finalstaticorder.finaccst.should.equal 0
it 'final - public - static #1', ->
convention = parser.finalstaticorder 'static public final String t1 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #2', ->
convention = parser.finalstaticorder 'static public transient final String t2 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #3', ->
convention = parser.finalstaticorder 'static transient public final String t3 = "";', {}
convention.finalstaticorder.staccfin.should.equal 1
it 'final - public - static #4', ->
convention = parser.finalstaticorder 'public static final String t4 = "";', {}
convention.finalstaticorder.staccfin.should.equal 0
|
[
{
"context": "###\ntyto - http://jh3y.github.io/tyto\nLicensed under the MIT license\n\nJh",
"end": 22,
"score": 0.766325056552887,
"start": 18,
"tag": "USERNAME",
"value": "jh3y"
},
{
"context": "3y.github.io/tyto\nLicensed under the MIT license\n\nJhey Tompkins (c) 2014.\n\nPermission is hereby granted, free of ",
"end": 83,
"score": 0.9998352527618408,
"start": 70,
"tag": "NAME",
"value": "Jhey Tompkins"
},
{
"context": "cipient\n then tyto.config.emailRecipient\n else 'someone@somewhere.com'\n d = new Date()\n subject = if tyto.config.emai",
"end": 17270,
"score": 0.999779999256134,
"start": 17249,
"tag": "EMAIL",
"value": "someone@somewhere.com"
}
] | src/coffeescript/tyto.coffee | logorrhea/tyto | 0 | ###
tyto - http://jh3y.github.io/tyto
Licensed under the MIT license
Jhey Tompkins (c) 2014.
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.
###
window.tyto = tyto = (opts) ->
return new tyto(opts) unless this instanceof tyto
newTyto = this
if window.localStorage.tyto isnt `undefined`
newTyto.config = JSON.parse window.localStorage.tyto
else if opts isnt `undefined`
newTyto.config = opts
else
newTyto.config = tytoConfig
newTyto.modals = {}
newTyto._autoSave = newTyto.config.autoSave
$.when(
newTyto._loadTemplates()
).done ->
newTyto._init()
newTyto
tyto::_init = () ->
tyto = this
tyto._buildBarn()
tyto._bindActions()
tyto
tyto::_loadTemplates = ->
tyto = this
$.when(
$.get("templates/column.html"),
$.get("templates/item.html"),
$.get("templates/email.html")
).done (t1, t2, t3, t4) ->
tyto.columnHtml = t1[0]
tyto.itemHtml = t2[0]
tyto.emailHtml = t3[0]
tyto::_buildBarn = () ->
tyto = this
tyto.undo = {}
config = tyto.config
# dont build unless
if config.DOMElementSelector isnt `undefined` or config.DOMId isnt `undefined`
if config.DOMId isnt `undefined`
tyto.element = $ '#' + config.DOMId
tyto.id = config.DOMId
else
tyto.element = $ config.DOMElementSelector
tyto.id = "barn"
tyto.element.attr 'data-tyto', 'true'
tyto.element.find('[data-action="addcolumn"]').on 'click', (e) ->
tyto.addColumn()
if window.localStorage and window.localStorage.tyto
tyto._setUpLocalStorageAutoSave()
else if window.localStorage
$('#cookie-banner')
.removeClass('hide')
.find('[data-action="cookie-close"]')
.on 'click', (e)->
tyto._setUpLocalStorageAutoSave()
$('.cookie-banner').remove()
if tyto._autoSave is false or tyto._autoSave is undefined
$('.actions [data-action="toggleautosave"] i')
.toggleClass 'fa-check-square-o fa-square-o'
if config.columns isnt `undefined` and config.columns.length > 0
tyto.element.find('.column').remove()
i = 0
while i < config.columns.length
tyto._createColumn config.columns[i]
i++
tyto._resizeColumns()
if tyto.element.find('.tyto-item').length > 0
$.each tyto.element.find('.tyto-item'), (index, item) ->
tyto._binditemEvents $ item
# added in as actions are fired on load
$('[data-action="undolast"]')
.removeClass('btn-info')
.addClass('btn-disabled')
.attr 'disabled', true
# initiate jquery sortable on columns
tyto.element.sortable
connectWith: '.column',
handle: '.column-mover'
placeholder: 'column-placeholder'
axis: "x"
containment: "#" + tyto.id
opacity: 0.8
start: (event, ui) ->
tyto._movedItem = $ ui.item
tyto._movedItemOrigin = $ event.currentTarget
columnList = Array.prototype.slice.call tyto.element.children '.column'
tyto._movedItemIndex = columnList.indexOf $(ui.item)[0]
stop: (event, ui) ->
columnList = Array.prototype.slice.call tyto.element.children '.column'
newPosition = columnList.indexOf $(ui.item)[0]
if newPosition < tyto._movedItemIndex
tyto._movedItemIndex += 1
tyto.element.trigger
type: 'tyto:action',
name: 'move-column',
DOMcolumn: tyto._movedItem,
itemIndex: tyto._movedItemIndex
tyto.notify 'column moved', 2000
tyto = this
tyto
tyto::_createColumn = (columnData) ->
tyto = this
template = Handlebars.compile tyto.columnHtml
Handlebars.registerPartial "item", tyto.itemHtml
$newColumn = $ template columnData
this.element.append $newColumn
this._bindColumnEvents $newColumn
tyto.element.trigger
type: 'tyto:action',
name: 'add-column',
DOMcolumn: $newColumn,
DOMitem: undefined
tyto::_setUpLocalStorageAutoSave = ->
tyto = this
inThrottle = undefined
throttle = (func, delay) ->
if inThrottle
clearTimeout inThrottle
inThrottle = setTimeout(->
func.apply()
tyto
, delay)
$('body').on 'tyto:action', (event)->
if tyto._autoSave
throttle(->
tyto.saveBarn JSON.stringify tyto._createBarnJSON()
, 5000)
tyto
tyto::_bindColumnEvents = ($column) ->
tyto = this
$column.find('.column-title').on 'keydown', (e) ->
columnTitle = this
if (e.keyCode is 13 or e.charCode is 13 or
e.keyCode is 27 or e.charCode is 27)
columnTitle.blur()
$column.find('.column-title').on 'click', (e) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$column.find('.column-title').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-column-title',
DOMcolumn: $column,
content: tyto._preEditItemContent
$column.find('.items').sortable
connectWith: ".items"
handle: ".item-mover"
placeholder: "item-placeholder"
containment: "#" + tyto.id
opacity: 0.8
revert: true
start: (event, ui) ->
tyto._movedItem = $ ui.item
tyto._movedItemOrigin = $ event.currentTarget
itemList = Array.prototype.slice.call(
$column.find('.items')
.children '.tyto-item'
)
tyto._movedItemIndex = itemList.indexOf $(ui.item)[0]
stop: (event, ui) ->
tyto.element.trigger
type: 'tyto:action',
name: 'move-item',
DOMcolumn: tyto._movedItemOrigin,
DOMitem: tyto._movedItem,
itemIndex: tyto._movedItemIndex
tyto.notify 'item moved', 2000
$column.find('[data-action="removecolumn"]')
.on 'click', (e) ->
tyto.removeColumn $column
$column.find('[data-action="additem"]')
.on 'click', (e) ->
tyto.addItem $column
tyto
tyto::undoLast = ->
tyto = this
if tyto.undo
switch tyto.undo.action
when 'add-column'
tyto.undo.column.remove()
tyto._resizeColumns()
when 'add-item'
tyto.undo.item.remove()
when 'remove-column'
if tyto.undo.columnIndex > tyto.element.find('.column').length - 1
tyto.element.append tyto.undo.column
else
$(tyto.element.find('.column')[tyto.undo.columnIndex])
.before tyto.undo.column
tyto._bindColumnEvents tyto.undo.column
$.each tyto.undo.column.find('[data-tyto-item]'), () ->
tyto._binditemEvents $ this
tyto._resizeColumns()
when 'remove-item'
if (tyto.undo.itemIndex >
tyto.undo.column.find('[data-tyto-item]').length - 1)
tyto.undo.column.find('.items').append tyto.undo.item
else
$(tyto.element
.find(tyto.undo.column)
.find('[data-tyto-item]')[tyto.undo.itemIndex]
).before tyto.undo.item
tyto._binditemEvents tyto.undo.item
when 'move-item'
if (tyto.undo.itemIndex is 0 and
tyto.undo.column.children('.tyto-item').length is 0)
tyto.undo.column.append tyto.undo.item
else
$(tyto.undo.column.
children('.tyto-item')[tyto.undo.itemIndex]
).before tyto.undo.item
when 'move-column'
$(tyto.element
.children('.column')[tyto.undo.itemIndex]
).before tyto.undo.column
when 'edit-item-title'
tyto.undo.item
.find('.tyto-item-title')[0].innerHTML = tyto.undo.editContent
when 'edit-item-content'
tyto.undo.item
.find('.tyto-item-content')[0].innerHTML = tyto.undo.editContent
when 'edit-column-title'
tyto.undo.column
.find('.column-title')[0].innerHTML = tyto.undo.editContent
when 'wipe-board'
tyto.element.append tyto.undo.item
$.each tyto.element.find('.tyto-item'), (key, $item) ->
tyto._binditemEvents $ $item
$.each tyto.element.find('.column'), (key, $column) ->
tyto._bindColumnEvents $ $column
else
console.log "tyto: no luck, you don't seem to be able to undo that"
$('[data-action="undolast"]')
.removeClass('btn-info btn-default')
.addClass('btn-disabled')
.attr 'disabled', true
tyto.notify 'undone', 2000
tyto::addColumn = ->
tyto = this
if tyto.element.find('.column').length < tyto.config.maxColumns
tyto._createColumn()
tyto._resizeColumns()
tyto.notify 'column added', 2000
else
alert """whoah, it's getting busy and you've reached the maximum amount of
columns. You can however increase the amount of maximum columns via the
config."""
tyto::removeColumn = ($column = this.element.find('.column').last()) ->
tyto = this
calculateIndex = ->
colIndex = undefined
$.each $(".column"), (key, value) ->
if $column[0] is value
colIndex = key
return false
colIndex
removeColumn = ->
columnList = Array.prototype.slice.call(
$column.parent('[data-tyto]')
.children '.column'
)
tyto.element.trigger
type: 'tyto:action',
name: 'remove-column',
DOMitem: undefined,
DOMcolumn: $column,
columnIndex: columnList.indexOf $column[0]
$column.remove()
tyto._resizeColumns()
if $column.find('.tyto-item').length > 0
if confirm """are you sure you want to remove this column?
doing so will lose all items within it."""
removeColumn()
tyto.notify 'column removed', 2000
else
removeColumn()
tyto.notify 'column removed', 2000
tyto
tyto::addItem = ($column = this.element.find('.column').first(), content) ->
this._createItem $column, content
this.notify 'item added', 2000
tyto::_createItem = ($column, content) ->
tyto = this
template = Handlebars.compile tyto.itemHtml
$newitem = $ template {}
tyto._binditemEvents $newitem
$column.find('.tyto-item-holder .items').append $newitem
tyto.element.trigger
type: 'tyto:action',
name: 'add-item',
DOMitem: $newitem,
DOMcolumn: $column
tyto::_binditemEvents = ($item) ->
tyto = this
$item.find('.close').on 'click', (event) ->
if confirm 'are you sure you want to remove this item?'
itemList = Array.prototype.slice.call $item.parent('.items').children()
tyto.element.trigger
type: 'tyto:action',
name: 'remove-item',
DOMitem: $item,
DOMcolumn: $item.parents('.column'),
columnIndex: undefined,
itemIndex: itemList.indexOf $item[0]
$item.remove()
tyto.notify 'item removed', 2000
$item.find('i.collapser').on 'click', (e) ->
icon = $ this
icon.toggleClass 'fa-minus fa-plus'
icon.closest('.tyto-item').find('.tyto-item-content').toggle()
$item.find('.tyto-item-title, .tyto-item-content').on 'keydown', (event) ->
item = this
if event.keyCode is 27 or event.charCode is 27
item.blur()
$item.find('.tyto-item-title').on 'click', (event) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$item.find('.tyto-item-title').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-item-title',
DOMitem: $item,
content: tyto._preEditItemContent
tyto.notify 'item title edited', 2000
$item.find('.tyto-item-content').on 'click', (event) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$item.find('.tyto-item-content').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-item-content',
DOMitem: $item,
content: tyto._preEditItemContent
tyto.notify 'item content edited', 2000
tyto::saveBarn = (jsonString = JSON.stringify(this._createBarnJSON())) ->
window.localStorage.setItem 'tyto', jsonString
this.notify 'board saved', 2000
tyto::deleteSave = ->
window.localStorage.removeItem 'tyto'
this.notify 'save deleted', 2000
tyto::wipeBoard = ->
if confirm 'are you really sure you wish to wipe your entire board?'
boardContent = tyto.element[0].innerHTML
tyto.element[0].innerHTML = '';
tyto.element.trigger
type: 'tyto:action',
name: 'wipe-board',
DOMitem: $ boardContent
tyto.notify 'board wiped', 2000
tyto::toggleAutoSave = ->
$('[data-action="toggleautosave"] i')
.toggleClass 'fa-check-square-o fa-square-o'
tyto._autoSave = !tyto._autoSave
if tyto._autoSave
tyto.notify 'auto-save: ON', 2000
else
tyto.notify 'auto-save: OFF', 2000
tyto.saveBarn JSON.stringify tyto._createBarnJSON()
tyto::_resizeColumns = ->
tyto = this
if tyto.element.find('.column').length > 0
correctWidth = 100 / tyto.element.find('.column').length
tyto.element.find('.column')
.css({'width': correctWidth + '%'})
tyto::_createBarnJSON = ->
tyto = this
itemboardJSON =
autoSave: tyto._autoSave
helpModalId: tyto.config.helpModalId
infoModalId: tyto.config.infoModalId
emailSubject: tyto.config.emailSubject
emailRecipient: tyto.config.emailRecipient
DOMId: tyto.config.DOMId
DOMElementSelector: tyto.config.DOMElementSelector
saveFilename: tyto.config.saveFilename
maxColumns: tyto.config.maxColumns
columns: []
columns = tyto.element.find '.column'
$.each columns, (index, column) ->
regex = new RegExp "<br>", 'g'
columnTitle = $(column).find('.column-title')[0]
.innerHTML.toString()
.replace regex, ''
items = []
columnitems = $(column).find('.tyto-item')
$.each columnitems, (index, item) ->
isCollapsed = if item.querySelector('.action-icons .collapser')
.className.indexOf('plus') isnt -1 then true else false
items.push
content: (item.querySelector('.tyto-item-content')
.innerHTML.toString().trim())
title: (item.querySelector('.tyto-item-title')
.innerHTML.toString().trim())
collapsed: isCollapsed
itemboardJSON.columns.push
title: columnTitle,
items: items
itemboardJSON
tyto::_loadBarnJSON = (json) ->
tyto = this
tyto._buildBarn json
tyto::_escapes =
'#': "@tyto-hash"
tyto::_encodeJSON = (jsonString) ->
tyto = this
if jsonString isnt `undefined`
for escape of tyto._escapes
regex = new RegExp escape, 'g'
jsonString = jsonString.replace regex, tyto._escapes[escape]
jsonString
tyto::_decodeJSON = (jsonString) ->
tyto = this
if jsonString isnt `undefined`
for escape of tyto._escapes
regex = new RegExp tyto._escapes[escape], 'g'
jsonString = jsonString.replace regex, escape
jsonString
tyto::exportBarn = ->
tyto = this
saveAnchor = $ '#savetyto'
filename = (if tyto.config.saveFilename isnt `undefined`
then tyto.config.saveFilename + '.json' else 'itemboard.json')
content = ('data:text/plain,' +
tyto._encodeJSON JSON.stringify(tyto._createBarnJSON()))
saveAnchor[0].setAttribute 'download', filename
saveAnchor[0].setAttribute 'href', content
saveAnchor[0].click()
tyto::loadBarn = ->
tyto = this
$files = $ '#tytofiles'
if window.File and window.FileReader and window.FileList and window.Blob
$files[0].click()
else
alert 'tyto: the file APIs are not fully supported in your browser'
$files.on 'change', (event) ->
f = event.target.files[0]
if (f.type.match 'application/json') or (f.name.indexOf '.json' isnt -1)
reader = new FileReader()
reader.onloadend = (event) ->
result = JSON.parse tyto._decodeJSON(this.result)
if result.columns isnt `undefined` and
(result.DOMId isnt `undefined` or
result.DOMElementSelector isnt `undefined`)
tyto._loadBarnJSON result
else
alert 'tyto: incorrect json'
reader.readAsText f
else
alert 'tyto: only load a valid itemboard json file'
tyto::_getEmailContent = ->
tyto = this;
contentString = ''
itemboardJSON = tyto._createBarnJSON()
template = Handlebars.compile tyto.emailHtml
$email = $ template itemboardJSON
regex = new RegExp '<br>', 'gi'
if $email.html().trim() is "Here are your current items."
then return "You have no items on your plate so go grab a drink! :)"
else return $email.html().replace(regex, '').trim()
tyto::emailBarn = ->
tyto = this
mailto = 'mailto:'
recipient = if tyto.config.emailRecipient
then tyto.config.emailRecipient
else 'someone@somewhere.com'
d = new Date()
subject = if tyto.config.emailSubject
then tyto.config.emailSubject
else 'items as of ' + d.toString()
content = tyto._getEmailContent()
content = encodeURIComponent content
mailtoString = mailto + recipient + '?subject=' +
encodeURIComponent(subject.trim()) + '&body=' + content
$('#tytoemail').attr 'href', mailtoString
$('#tytoemail')[0].click()
tyto::notify = (message, duration) ->
$message = $ '<div class= "tyto-notification notify" data-tyto-notify=" ' +
(duration / 1000) + ' ">' + message + '</div>'
$('body').prepend $message
setTimeout(->
$message.remove()
, duration)
tyto::showHelp = ->
tyto = this
if tyto.config.helpModalId
tyto.modals.helpModal = $ '#' + tyto.config.helpModalId
tyto.modals.helpModal.modal()
tyto::showInfo = ->
tyto = this
if tyto.config.infoModalId
tyto.modals.infoModal = $ '#' + tyto.config.infoModalId
tyto.modals.infoModal.modal()
tyto::_bindActions = ->
tyto = this
actionMap =
additem: 'addItem'
addcolumn: 'addColumn'
exportbarn: 'exportBarn'
loadbarn: 'loadBarn'
emailbarn: 'emailBarn'
helpbarn: 'showHelp'
infobarn: 'showInfo'
undolast: 'undoLast'
savebarn: 'saveBarn'
deletesave: 'deleteSave'
wipeboard: 'wipeBoard'
toggleautosave: 'toggleAutoSave'
action = ""
$('.actions').on 'click', '[data-action]', (e) ->
action = e.target.dataset.action
tyto[actionMap[action]]()
# set up action event listener for tracking actions to undo
$('body').on 'tyto:action', (event) ->
tyto.undo.action = event.name
tyto.undo.column = event.DOMcolumn
tyto.undo.item = event.DOMitem
tyto.undo.columnIndex = event.columnIndex
tyto.undo.itemIndex = event.itemIndex
tyto.undo.editContent = event.content
$('[data-action="undolast"]')
.removeAttr('disabled')
.removeClass('btn-disabled')
.addClass 'btn-default'
tyto
| 40240 | ###
tyto - http://jh3y.github.io/tyto
Licensed under the MIT license
<NAME> (c) 2014.
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.
###
window.tyto = tyto = (opts) ->
return new tyto(opts) unless this instanceof tyto
newTyto = this
if window.localStorage.tyto isnt `undefined`
newTyto.config = JSON.parse window.localStorage.tyto
else if opts isnt `undefined`
newTyto.config = opts
else
newTyto.config = tytoConfig
newTyto.modals = {}
newTyto._autoSave = newTyto.config.autoSave
$.when(
newTyto._loadTemplates()
).done ->
newTyto._init()
newTyto
tyto::_init = () ->
tyto = this
tyto._buildBarn()
tyto._bindActions()
tyto
tyto::_loadTemplates = ->
tyto = this
$.when(
$.get("templates/column.html"),
$.get("templates/item.html"),
$.get("templates/email.html")
).done (t1, t2, t3, t4) ->
tyto.columnHtml = t1[0]
tyto.itemHtml = t2[0]
tyto.emailHtml = t3[0]
tyto::_buildBarn = () ->
tyto = this
tyto.undo = {}
config = tyto.config
# dont build unless
if config.DOMElementSelector isnt `undefined` or config.DOMId isnt `undefined`
if config.DOMId isnt `undefined`
tyto.element = $ '#' + config.DOMId
tyto.id = config.DOMId
else
tyto.element = $ config.DOMElementSelector
tyto.id = "barn"
tyto.element.attr 'data-tyto', 'true'
tyto.element.find('[data-action="addcolumn"]').on 'click', (e) ->
tyto.addColumn()
if window.localStorage and window.localStorage.tyto
tyto._setUpLocalStorageAutoSave()
else if window.localStorage
$('#cookie-banner')
.removeClass('hide')
.find('[data-action="cookie-close"]')
.on 'click', (e)->
tyto._setUpLocalStorageAutoSave()
$('.cookie-banner').remove()
if tyto._autoSave is false or tyto._autoSave is undefined
$('.actions [data-action="toggleautosave"] i')
.toggleClass 'fa-check-square-o fa-square-o'
if config.columns isnt `undefined` and config.columns.length > 0
tyto.element.find('.column').remove()
i = 0
while i < config.columns.length
tyto._createColumn config.columns[i]
i++
tyto._resizeColumns()
if tyto.element.find('.tyto-item').length > 0
$.each tyto.element.find('.tyto-item'), (index, item) ->
tyto._binditemEvents $ item
# added in as actions are fired on load
$('[data-action="undolast"]')
.removeClass('btn-info')
.addClass('btn-disabled')
.attr 'disabled', true
# initiate jquery sortable on columns
tyto.element.sortable
connectWith: '.column',
handle: '.column-mover'
placeholder: 'column-placeholder'
axis: "x"
containment: "#" + tyto.id
opacity: 0.8
start: (event, ui) ->
tyto._movedItem = $ ui.item
tyto._movedItemOrigin = $ event.currentTarget
columnList = Array.prototype.slice.call tyto.element.children '.column'
tyto._movedItemIndex = columnList.indexOf $(ui.item)[0]
stop: (event, ui) ->
columnList = Array.prototype.slice.call tyto.element.children '.column'
newPosition = columnList.indexOf $(ui.item)[0]
if newPosition < tyto._movedItemIndex
tyto._movedItemIndex += 1
tyto.element.trigger
type: 'tyto:action',
name: 'move-column',
DOMcolumn: tyto._movedItem,
itemIndex: tyto._movedItemIndex
tyto.notify 'column moved', 2000
tyto = this
tyto
tyto::_createColumn = (columnData) ->
tyto = this
template = Handlebars.compile tyto.columnHtml
Handlebars.registerPartial "item", tyto.itemHtml
$newColumn = $ template columnData
this.element.append $newColumn
this._bindColumnEvents $newColumn
tyto.element.trigger
type: 'tyto:action',
name: 'add-column',
DOMcolumn: $newColumn,
DOMitem: undefined
tyto::_setUpLocalStorageAutoSave = ->
tyto = this
inThrottle = undefined
throttle = (func, delay) ->
if inThrottle
clearTimeout inThrottle
inThrottle = setTimeout(->
func.apply()
tyto
, delay)
$('body').on 'tyto:action', (event)->
if tyto._autoSave
throttle(->
tyto.saveBarn JSON.stringify tyto._createBarnJSON()
, 5000)
tyto
tyto::_bindColumnEvents = ($column) ->
tyto = this
$column.find('.column-title').on 'keydown', (e) ->
columnTitle = this
if (e.keyCode is 13 or e.charCode is 13 or
e.keyCode is 27 or e.charCode is 27)
columnTitle.blur()
$column.find('.column-title').on 'click', (e) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$column.find('.column-title').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-column-title',
DOMcolumn: $column,
content: tyto._preEditItemContent
$column.find('.items').sortable
connectWith: ".items"
handle: ".item-mover"
placeholder: "item-placeholder"
containment: "#" + tyto.id
opacity: 0.8
revert: true
start: (event, ui) ->
tyto._movedItem = $ ui.item
tyto._movedItemOrigin = $ event.currentTarget
itemList = Array.prototype.slice.call(
$column.find('.items')
.children '.tyto-item'
)
tyto._movedItemIndex = itemList.indexOf $(ui.item)[0]
stop: (event, ui) ->
tyto.element.trigger
type: 'tyto:action',
name: 'move-item',
DOMcolumn: tyto._movedItemOrigin,
DOMitem: tyto._movedItem,
itemIndex: tyto._movedItemIndex
tyto.notify 'item moved', 2000
$column.find('[data-action="removecolumn"]')
.on 'click', (e) ->
tyto.removeColumn $column
$column.find('[data-action="additem"]')
.on 'click', (e) ->
tyto.addItem $column
tyto
tyto::undoLast = ->
tyto = this
if tyto.undo
switch tyto.undo.action
when 'add-column'
tyto.undo.column.remove()
tyto._resizeColumns()
when 'add-item'
tyto.undo.item.remove()
when 'remove-column'
if tyto.undo.columnIndex > tyto.element.find('.column').length - 1
tyto.element.append tyto.undo.column
else
$(tyto.element.find('.column')[tyto.undo.columnIndex])
.before tyto.undo.column
tyto._bindColumnEvents tyto.undo.column
$.each tyto.undo.column.find('[data-tyto-item]'), () ->
tyto._binditemEvents $ this
tyto._resizeColumns()
when 'remove-item'
if (tyto.undo.itemIndex >
tyto.undo.column.find('[data-tyto-item]').length - 1)
tyto.undo.column.find('.items').append tyto.undo.item
else
$(tyto.element
.find(tyto.undo.column)
.find('[data-tyto-item]')[tyto.undo.itemIndex]
).before tyto.undo.item
tyto._binditemEvents tyto.undo.item
when 'move-item'
if (tyto.undo.itemIndex is 0 and
tyto.undo.column.children('.tyto-item').length is 0)
tyto.undo.column.append tyto.undo.item
else
$(tyto.undo.column.
children('.tyto-item')[tyto.undo.itemIndex]
).before tyto.undo.item
when 'move-column'
$(tyto.element
.children('.column')[tyto.undo.itemIndex]
).before tyto.undo.column
when 'edit-item-title'
tyto.undo.item
.find('.tyto-item-title')[0].innerHTML = tyto.undo.editContent
when 'edit-item-content'
tyto.undo.item
.find('.tyto-item-content')[0].innerHTML = tyto.undo.editContent
when 'edit-column-title'
tyto.undo.column
.find('.column-title')[0].innerHTML = tyto.undo.editContent
when 'wipe-board'
tyto.element.append tyto.undo.item
$.each tyto.element.find('.tyto-item'), (key, $item) ->
tyto._binditemEvents $ $item
$.each tyto.element.find('.column'), (key, $column) ->
tyto._bindColumnEvents $ $column
else
console.log "tyto: no luck, you don't seem to be able to undo that"
$('[data-action="undolast"]')
.removeClass('btn-info btn-default')
.addClass('btn-disabled')
.attr 'disabled', true
tyto.notify 'undone', 2000
tyto::addColumn = ->
tyto = this
if tyto.element.find('.column').length < tyto.config.maxColumns
tyto._createColumn()
tyto._resizeColumns()
tyto.notify 'column added', 2000
else
alert """whoah, it's getting busy and you've reached the maximum amount of
columns. You can however increase the amount of maximum columns via the
config."""
tyto::removeColumn = ($column = this.element.find('.column').last()) ->
tyto = this
calculateIndex = ->
colIndex = undefined
$.each $(".column"), (key, value) ->
if $column[0] is value
colIndex = key
return false
colIndex
removeColumn = ->
columnList = Array.prototype.slice.call(
$column.parent('[data-tyto]')
.children '.column'
)
tyto.element.trigger
type: 'tyto:action',
name: 'remove-column',
DOMitem: undefined,
DOMcolumn: $column,
columnIndex: columnList.indexOf $column[0]
$column.remove()
tyto._resizeColumns()
if $column.find('.tyto-item').length > 0
if confirm """are you sure you want to remove this column?
doing so will lose all items within it."""
removeColumn()
tyto.notify 'column removed', 2000
else
removeColumn()
tyto.notify 'column removed', 2000
tyto
tyto::addItem = ($column = this.element.find('.column').first(), content) ->
this._createItem $column, content
this.notify 'item added', 2000
tyto::_createItem = ($column, content) ->
tyto = this
template = Handlebars.compile tyto.itemHtml
$newitem = $ template {}
tyto._binditemEvents $newitem
$column.find('.tyto-item-holder .items').append $newitem
tyto.element.trigger
type: 'tyto:action',
name: 'add-item',
DOMitem: $newitem,
DOMcolumn: $column
tyto::_binditemEvents = ($item) ->
tyto = this
$item.find('.close').on 'click', (event) ->
if confirm 'are you sure you want to remove this item?'
itemList = Array.prototype.slice.call $item.parent('.items').children()
tyto.element.trigger
type: 'tyto:action',
name: 'remove-item',
DOMitem: $item,
DOMcolumn: $item.parents('.column'),
columnIndex: undefined,
itemIndex: itemList.indexOf $item[0]
$item.remove()
tyto.notify 'item removed', 2000
$item.find('i.collapser').on 'click', (e) ->
icon = $ this
icon.toggleClass 'fa-minus fa-plus'
icon.closest('.tyto-item').find('.tyto-item-content').toggle()
$item.find('.tyto-item-title, .tyto-item-content').on 'keydown', (event) ->
item = this
if event.keyCode is 27 or event.charCode is 27
item.blur()
$item.find('.tyto-item-title').on 'click', (event) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$item.find('.tyto-item-title').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-item-title',
DOMitem: $item,
content: tyto._preEditItemContent
tyto.notify 'item title edited', 2000
$item.find('.tyto-item-content').on 'click', (event) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$item.find('.tyto-item-content').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-item-content',
DOMitem: $item,
content: tyto._preEditItemContent
tyto.notify 'item content edited', 2000
tyto::saveBarn = (jsonString = JSON.stringify(this._createBarnJSON())) ->
window.localStorage.setItem 'tyto', jsonString
this.notify 'board saved', 2000
tyto::deleteSave = ->
window.localStorage.removeItem 'tyto'
this.notify 'save deleted', 2000
tyto::wipeBoard = ->
if confirm 'are you really sure you wish to wipe your entire board?'
boardContent = tyto.element[0].innerHTML
tyto.element[0].innerHTML = '';
tyto.element.trigger
type: 'tyto:action',
name: 'wipe-board',
DOMitem: $ boardContent
tyto.notify 'board wiped', 2000
tyto::toggleAutoSave = ->
$('[data-action="toggleautosave"] i')
.toggleClass 'fa-check-square-o fa-square-o'
tyto._autoSave = !tyto._autoSave
if tyto._autoSave
tyto.notify 'auto-save: ON', 2000
else
tyto.notify 'auto-save: OFF', 2000
tyto.saveBarn JSON.stringify tyto._createBarnJSON()
tyto::_resizeColumns = ->
tyto = this
if tyto.element.find('.column').length > 0
correctWidth = 100 / tyto.element.find('.column').length
tyto.element.find('.column')
.css({'width': correctWidth + '%'})
tyto::_createBarnJSON = ->
tyto = this
itemboardJSON =
autoSave: tyto._autoSave
helpModalId: tyto.config.helpModalId
infoModalId: tyto.config.infoModalId
emailSubject: tyto.config.emailSubject
emailRecipient: tyto.config.emailRecipient
DOMId: tyto.config.DOMId
DOMElementSelector: tyto.config.DOMElementSelector
saveFilename: tyto.config.saveFilename
maxColumns: tyto.config.maxColumns
columns: []
columns = tyto.element.find '.column'
$.each columns, (index, column) ->
regex = new RegExp "<br>", 'g'
columnTitle = $(column).find('.column-title')[0]
.innerHTML.toString()
.replace regex, ''
items = []
columnitems = $(column).find('.tyto-item')
$.each columnitems, (index, item) ->
isCollapsed = if item.querySelector('.action-icons .collapser')
.className.indexOf('plus') isnt -1 then true else false
items.push
content: (item.querySelector('.tyto-item-content')
.innerHTML.toString().trim())
title: (item.querySelector('.tyto-item-title')
.innerHTML.toString().trim())
collapsed: isCollapsed
itemboardJSON.columns.push
title: columnTitle,
items: items
itemboardJSON
tyto::_loadBarnJSON = (json) ->
tyto = this
tyto._buildBarn json
tyto::_escapes =
'#': "@tyto-hash"
tyto::_encodeJSON = (jsonString) ->
tyto = this
if jsonString isnt `undefined`
for escape of tyto._escapes
regex = new RegExp escape, 'g'
jsonString = jsonString.replace regex, tyto._escapes[escape]
jsonString
tyto::_decodeJSON = (jsonString) ->
tyto = this
if jsonString isnt `undefined`
for escape of tyto._escapes
regex = new RegExp tyto._escapes[escape], 'g'
jsonString = jsonString.replace regex, escape
jsonString
tyto::exportBarn = ->
tyto = this
saveAnchor = $ '#savetyto'
filename = (if tyto.config.saveFilename isnt `undefined`
then tyto.config.saveFilename + '.json' else 'itemboard.json')
content = ('data:text/plain,' +
tyto._encodeJSON JSON.stringify(tyto._createBarnJSON()))
saveAnchor[0].setAttribute 'download', filename
saveAnchor[0].setAttribute 'href', content
saveAnchor[0].click()
tyto::loadBarn = ->
tyto = this
$files = $ '#tytofiles'
if window.File and window.FileReader and window.FileList and window.Blob
$files[0].click()
else
alert 'tyto: the file APIs are not fully supported in your browser'
$files.on 'change', (event) ->
f = event.target.files[0]
if (f.type.match 'application/json') or (f.name.indexOf '.json' isnt -1)
reader = new FileReader()
reader.onloadend = (event) ->
result = JSON.parse tyto._decodeJSON(this.result)
if result.columns isnt `undefined` and
(result.DOMId isnt `undefined` or
result.DOMElementSelector isnt `undefined`)
tyto._loadBarnJSON result
else
alert 'tyto: incorrect json'
reader.readAsText f
else
alert 'tyto: only load a valid itemboard json file'
tyto::_getEmailContent = ->
tyto = this;
contentString = ''
itemboardJSON = tyto._createBarnJSON()
template = Handlebars.compile tyto.emailHtml
$email = $ template itemboardJSON
regex = new RegExp '<br>', 'gi'
if $email.html().trim() is "Here are your current items."
then return "You have no items on your plate so go grab a drink! :)"
else return $email.html().replace(regex, '').trim()
tyto::emailBarn = ->
tyto = this
mailto = 'mailto:'
recipient = if tyto.config.emailRecipient
then tyto.config.emailRecipient
else '<EMAIL>'
d = new Date()
subject = if tyto.config.emailSubject
then tyto.config.emailSubject
else 'items as of ' + d.toString()
content = tyto._getEmailContent()
content = encodeURIComponent content
mailtoString = mailto + recipient + '?subject=' +
encodeURIComponent(subject.trim()) + '&body=' + content
$('#tytoemail').attr 'href', mailtoString
$('#tytoemail')[0].click()
tyto::notify = (message, duration) ->
$message = $ '<div class= "tyto-notification notify" data-tyto-notify=" ' +
(duration / 1000) + ' ">' + message + '</div>'
$('body').prepend $message
setTimeout(->
$message.remove()
, duration)
tyto::showHelp = ->
tyto = this
if tyto.config.helpModalId
tyto.modals.helpModal = $ '#' + tyto.config.helpModalId
tyto.modals.helpModal.modal()
tyto::showInfo = ->
tyto = this
if tyto.config.infoModalId
tyto.modals.infoModal = $ '#' + tyto.config.infoModalId
tyto.modals.infoModal.modal()
tyto::_bindActions = ->
tyto = this
actionMap =
additem: 'addItem'
addcolumn: 'addColumn'
exportbarn: 'exportBarn'
loadbarn: 'loadBarn'
emailbarn: 'emailBarn'
helpbarn: 'showHelp'
infobarn: 'showInfo'
undolast: 'undoLast'
savebarn: 'saveBarn'
deletesave: 'deleteSave'
wipeboard: 'wipeBoard'
toggleautosave: 'toggleAutoSave'
action = ""
$('.actions').on 'click', '[data-action]', (e) ->
action = e.target.dataset.action
tyto[actionMap[action]]()
# set up action event listener for tracking actions to undo
$('body').on 'tyto:action', (event) ->
tyto.undo.action = event.name
tyto.undo.column = event.DOMcolumn
tyto.undo.item = event.DOMitem
tyto.undo.columnIndex = event.columnIndex
tyto.undo.itemIndex = event.itemIndex
tyto.undo.editContent = event.content
$('[data-action="undolast"]')
.removeAttr('disabled')
.removeClass('btn-disabled')
.addClass 'btn-default'
tyto
| true | ###
tyto - http://jh3y.github.io/tyto
Licensed under the MIT license
PI:NAME:<NAME>END_PI (c) 2014.
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.
###
window.tyto = tyto = (opts) ->
return new tyto(opts) unless this instanceof tyto
newTyto = this
if window.localStorage.tyto isnt `undefined`
newTyto.config = JSON.parse window.localStorage.tyto
else if opts isnt `undefined`
newTyto.config = opts
else
newTyto.config = tytoConfig
newTyto.modals = {}
newTyto._autoSave = newTyto.config.autoSave
$.when(
newTyto._loadTemplates()
).done ->
newTyto._init()
newTyto
tyto::_init = () ->
tyto = this
tyto._buildBarn()
tyto._bindActions()
tyto
tyto::_loadTemplates = ->
tyto = this
$.when(
$.get("templates/column.html"),
$.get("templates/item.html"),
$.get("templates/email.html")
).done (t1, t2, t3, t4) ->
tyto.columnHtml = t1[0]
tyto.itemHtml = t2[0]
tyto.emailHtml = t3[0]
tyto::_buildBarn = () ->
tyto = this
tyto.undo = {}
config = tyto.config
# dont build unless
if config.DOMElementSelector isnt `undefined` or config.DOMId isnt `undefined`
if config.DOMId isnt `undefined`
tyto.element = $ '#' + config.DOMId
tyto.id = config.DOMId
else
tyto.element = $ config.DOMElementSelector
tyto.id = "barn"
tyto.element.attr 'data-tyto', 'true'
tyto.element.find('[data-action="addcolumn"]').on 'click', (e) ->
tyto.addColumn()
if window.localStorage and window.localStorage.tyto
tyto._setUpLocalStorageAutoSave()
else if window.localStorage
$('#cookie-banner')
.removeClass('hide')
.find('[data-action="cookie-close"]')
.on 'click', (e)->
tyto._setUpLocalStorageAutoSave()
$('.cookie-banner').remove()
if tyto._autoSave is false or tyto._autoSave is undefined
$('.actions [data-action="toggleautosave"] i')
.toggleClass 'fa-check-square-o fa-square-o'
if config.columns isnt `undefined` and config.columns.length > 0
tyto.element.find('.column').remove()
i = 0
while i < config.columns.length
tyto._createColumn config.columns[i]
i++
tyto._resizeColumns()
if tyto.element.find('.tyto-item').length > 0
$.each tyto.element.find('.tyto-item'), (index, item) ->
tyto._binditemEvents $ item
# added in as actions are fired on load
$('[data-action="undolast"]')
.removeClass('btn-info')
.addClass('btn-disabled')
.attr 'disabled', true
# initiate jquery sortable on columns
tyto.element.sortable
connectWith: '.column',
handle: '.column-mover'
placeholder: 'column-placeholder'
axis: "x"
containment: "#" + tyto.id
opacity: 0.8
start: (event, ui) ->
tyto._movedItem = $ ui.item
tyto._movedItemOrigin = $ event.currentTarget
columnList = Array.prototype.slice.call tyto.element.children '.column'
tyto._movedItemIndex = columnList.indexOf $(ui.item)[0]
stop: (event, ui) ->
columnList = Array.prototype.slice.call tyto.element.children '.column'
newPosition = columnList.indexOf $(ui.item)[0]
if newPosition < tyto._movedItemIndex
tyto._movedItemIndex += 1
tyto.element.trigger
type: 'tyto:action',
name: 'move-column',
DOMcolumn: tyto._movedItem,
itemIndex: tyto._movedItemIndex
tyto.notify 'column moved', 2000
tyto = this
tyto
tyto::_createColumn = (columnData) ->
tyto = this
template = Handlebars.compile tyto.columnHtml
Handlebars.registerPartial "item", tyto.itemHtml
$newColumn = $ template columnData
this.element.append $newColumn
this._bindColumnEvents $newColumn
tyto.element.trigger
type: 'tyto:action',
name: 'add-column',
DOMcolumn: $newColumn,
DOMitem: undefined
tyto::_setUpLocalStorageAutoSave = ->
tyto = this
inThrottle = undefined
throttle = (func, delay) ->
if inThrottle
clearTimeout inThrottle
inThrottle = setTimeout(->
func.apply()
tyto
, delay)
$('body').on 'tyto:action', (event)->
if tyto._autoSave
throttle(->
tyto.saveBarn JSON.stringify tyto._createBarnJSON()
, 5000)
tyto
tyto::_bindColumnEvents = ($column) ->
tyto = this
$column.find('.column-title').on 'keydown', (e) ->
columnTitle = this
if (e.keyCode is 13 or e.charCode is 13 or
e.keyCode is 27 or e.charCode is 27)
columnTitle.blur()
$column.find('.column-title').on 'click', (e) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$column.find('.column-title').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-column-title',
DOMcolumn: $column,
content: tyto._preEditItemContent
$column.find('.items').sortable
connectWith: ".items"
handle: ".item-mover"
placeholder: "item-placeholder"
containment: "#" + tyto.id
opacity: 0.8
revert: true
start: (event, ui) ->
tyto._movedItem = $ ui.item
tyto._movedItemOrigin = $ event.currentTarget
itemList = Array.prototype.slice.call(
$column.find('.items')
.children '.tyto-item'
)
tyto._movedItemIndex = itemList.indexOf $(ui.item)[0]
stop: (event, ui) ->
tyto.element.trigger
type: 'tyto:action',
name: 'move-item',
DOMcolumn: tyto._movedItemOrigin,
DOMitem: tyto._movedItem,
itemIndex: tyto._movedItemIndex
tyto.notify 'item moved', 2000
$column.find('[data-action="removecolumn"]')
.on 'click', (e) ->
tyto.removeColumn $column
$column.find('[data-action="additem"]')
.on 'click', (e) ->
tyto.addItem $column
tyto
tyto::undoLast = ->
tyto = this
if tyto.undo
switch tyto.undo.action
when 'add-column'
tyto.undo.column.remove()
tyto._resizeColumns()
when 'add-item'
tyto.undo.item.remove()
when 'remove-column'
if tyto.undo.columnIndex > tyto.element.find('.column').length - 1
tyto.element.append tyto.undo.column
else
$(tyto.element.find('.column')[tyto.undo.columnIndex])
.before tyto.undo.column
tyto._bindColumnEvents tyto.undo.column
$.each tyto.undo.column.find('[data-tyto-item]'), () ->
tyto._binditemEvents $ this
tyto._resizeColumns()
when 'remove-item'
if (tyto.undo.itemIndex >
tyto.undo.column.find('[data-tyto-item]').length - 1)
tyto.undo.column.find('.items').append tyto.undo.item
else
$(tyto.element
.find(tyto.undo.column)
.find('[data-tyto-item]')[tyto.undo.itemIndex]
).before tyto.undo.item
tyto._binditemEvents tyto.undo.item
when 'move-item'
if (tyto.undo.itemIndex is 0 and
tyto.undo.column.children('.tyto-item').length is 0)
tyto.undo.column.append tyto.undo.item
else
$(tyto.undo.column.
children('.tyto-item')[tyto.undo.itemIndex]
).before tyto.undo.item
when 'move-column'
$(tyto.element
.children('.column')[tyto.undo.itemIndex]
).before tyto.undo.column
when 'edit-item-title'
tyto.undo.item
.find('.tyto-item-title')[0].innerHTML = tyto.undo.editContent
when 'edit-item-content'
tyto.undo.item
.find('.tyto-item-content')[0].innerHTML = tyto.undo.editContent
when 'edit-column-title'
tyto.undo.column
.find('.column-title')[0].innerHTML = tyto.undo.editContent
when 'wipe-board'
tyto.element.append tyto.undo.item
$.each tyto.element.find('.tyto-item'), (key, $item) ->
tyto._binditemEvents $ $item
$.each tyto.element.find('.column'), (key, $column) ->
tyto._bindColumnEvents $ $column
else
console.log "tyto: no luck, you don't seem to be able to undo that"
$('[data-action="undolast"]')
.removeClass('btn-info btn-default')
.addClass('btn-disabled')
.attr 'disabled', true
tyto.notify 'undone', 2000
tyto::addColumn = ->
tyto = this
if tyto.element.find('.column').length < tyto.config.maxColumns
tyto._createColumn()
tyto._resizeColumns()
tyto.notify 'column added', 2000
else
alert """whoah, it's getting busy and you've reached the maximum amount of
columns. You can however increase the amount of maximum columns via the
config."""
tyto::removeColumn = ($column = this.element.find('.column').last()) ->
tyto = this
calculateIndex = ->
colIndex = undefined
$.each $(".column"), (key, value) ->
if $column[0] is value
colIndex = key
return false
colIndex
removeColumn = ->
columnList = Array.prototype.slice.call(
$column.parent('[data-tyto]')
.children '.column'
)
tyto.element.trigger
type: 'tyto:action',
name: 'remove-column',
DOMitem: undefined,
DOMcolumn: $column,
columnIndex: columnList.indexOf $column[0]
$column.remove()
tyto._resizeColumns()
if $column.find('.tyto-item').length > 0
if confirm """are you sure you want to remove this column?
doing so will lose all items within it."""
removeColumn()
tyto.notify 'column removed', 2000
else
removeColumn()
tyto.notify 'column removed', 2000
tyto
tyto::addItem = ($column = this.element.find('.column').first(), content) ->
this._createItem $column, content
this.notify 'item added', 2000
tyto::_createItem = ($column, content) ->
tyto = this
template = Handlebars.compile tyto.itemHtml
$newitem = $ template {}
tyto._binditemEvents $newitem
$column.find('.tyto-item-holder .items').append $newitem
tyto.element.trigger
type: 'tyto:action',
name: 'add-item',
DOMitem: $newitem,
DOMcolumn: $column
tyto::_binditemEvents = ($item) ->
tyto = this
$item.find('.close').on 'click', (event) ->
if confirm 'are you sure you want to remove this item?'
itemList = Array.prototype.slice.call $item.parent('.items').children()
tyto.element.trigger
type: 'tyto:action',
name: 'remove-item',
DOMitem: $item,
DOMcolumn: $item.parents('.column'),
columnIndex: undefined,
itemIndex: itemList.indexOf $item[0]
$item.remove()
tyto.notify 'item removed', 2000
$item.find('i.collapser').on 'click', (e) ->
icon = $ this
icon.toggleClass 'fa-minus fa-plus'
icon.closest('.tyto-item').find('.tyto-item-content').toggle()
$item.find('.tyto-item-title, .tyto-item-content').on 'keydown', (event) ->
item = this
if event.keyCode is 27 or event.charCode is 27
item.blur()
$item.find('.tyto-item-title').on 'click', (event) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$item.find('.tyto-item-title').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-item-title',
DOMitem: $item,
content: tyto._preEditItemContent
tyto.notify 'item title edited', 2000
$item.find('.tyto-item-content').on 'click', (event) ->
tyto._preEditItemContent = this.innerHTML.toString().trim();
$item.find('.tyto-item-content').on 'blur', (e) ->
tyto.element.trigger
type: 'tyto:action',
name: 'edit-item-content',
DOMitem: $item,
content: tyto._preEditItemContent
tyto.notify 'item content edited', 2000
tyto::saveBarn = (jsonString = JSON.stringify(this._createBarnJSON())) ->
window.localStorage.setItem 'tyto', jsonString
this.notify 'board saved', 2000
tyto::deleteSave = ->
window.localStorage.removeItem 'tyto'
this.notify 'save deleted', 2000
tyto::wipeBoard = ->
if confirm 'are you really sure you wish to wipe your entire board?'
boardContent = tyto.element[0].innerHTML
tyto.element[0].innerHTML = '';
tyto.element.trigger
type: 'tyto:action',
name: 'wipe-board',
DOMitem: $ boardContent
tyto.notify 'board wiped', 2000
tyto::toggleAutoSave = ->
$('[data-action="toggleautosave"] i')
.toggleClass 'fa-check-square-o fa-square-o'
tyto._autoSave = !tyto._autoSave
if tyto._autoSave
tyto.notify 'auto-save: ON', 2000
else
tyto.notify 'auto-save: OFF', 2000
tyto.saveBarn JSON.stringify tyto._createBarnJSON()
tyto::_resizeColumns = ->
tyto = this
if tyto.element.find('.column').length > 0
correctWidth = 100 / tyto.element.find('.column').length
tyto.element.find('.column')
.css({'width': correctWidth + '%'})
tyto::_createBarnJSON = ->
tyto = this
itemboardJSON =
autoSave: tyto._autoSave
helpModalId: tyto.config.helpModalId
infoModalId: tyto.config.infoModalId
emailSubject: tyto.config.emailSubject
emailRecipient: tyto.config.emailRecipient
DOMId: tyto.config.DOMId
DOMElementSelector: tyto.config.DOMElementSelector
saveFilename: tyto.config.saveFilename
maxColumns: tyto.config.maxColumns
columns: []
columns = tyto.element.find '.column'
$.each columns, (index, column) ->
regex = new RegExp "<br>", 'g'
columnTitle = $(column).find('.column-title')[0]
.innerHTML.toString()
.replace regex, ''
items = []
columnitems = $(column).find('.tyto-item')
$.each columnitems, (index, item) ->
isCollapsed = if item.querySelector('.action-icons .collapser')
.className.indexOf('plus') isnt -1 then true else false
items.push
content: (item.querySelector('.tyto-item-content')
.innerHTML.toString().trim())
title: (item.querySelector('.tyto-item-title')
.innerHTML.toString().trim())
collapsed: isCollapsed
itemboardJSON.columns.push
title: columnTitle,
items: items
itemboardJSON
tyto::_loadBarnJSON = (json) ->
tyto = this
tyto._buildBarn json
tyto::_escapes =
'#': "@tyto-hash"
tyto::_encodeJSON = (jsonString) ->
tyto = this
if jsonString isnt `undefined`
for escape of tyto._escapes
regex = new RegExp escape, 'g'
jsonString = jsonString.replace regex, tyto._escapes[escape]
jsonString
tyto::_decodeJSON = (jsonString) ->
tyto = this
if jsonString isnt `undefined`
for escape of tyto._escapes
regex = new RegExp tyto._escapes[escape], 'g'
jsonString = jsonString.replace regex, escape
jsonString
tyto::exportBarn = ->
tyto = this
saveAnchor = $ '#savetyto'
filename = (if tyto.config.saveFilename isnt `undefined`
then tyto.config.saveFilename + '.json' else 'itemboard.json')
content = ('data:text/plain,' +
tyto._encodeJSON JSON.stringify(tyto._createBarnJSON()))
saveAnchor[0].setAttribute 'download', filename
saveAnchor[0].setAttribute 'href', content
saveAnchor[0].click()
tyto::loadBarn = ->
tyto = this
$files = $ '#tytofiles'
if window.File and window.FileReader and window.FileList and window.Blob
$files[0].click()
else
alert 'tyto: the file APIs are not fully supported in your browser'
$files.on 'change', (event) ->
f = event.target.files[0]
if (f.type.match 'application/json') or (f.name.indexOf '.json' isnt -1)
reader = new FileReader()
reader.onloadend = (event) ->
result = JSON.parse tyto._decodeJSON(this.result)
if result.columns isnt `undefined` and
(result.DOMId isnt `undefined` or
result.DOMElementSelector isnt `undefined`)
tyto._loadBarnJSON result
else
alert 'tyto: incorrect json'
reader.readAsText f
else
alert 'tyto: only load a valid itemboard json file'
tyto::_getEmailContent = ->
tyto = this;
contentString = ''
itemboardJSON = tyto._createBarnJSON()
template = Handlebars.compile tyto.emailHtml
$email = $ template itemboardJSON
regex = new RegExp '<br>', 'gi'
if $email.html().trim() is "Here are your current items."
then return "You have no items on your plate so go grab a drink! :)"
else return $email.html().replace(regex, '').trim()
tyto::emailBarn = ->
tyto = this
mailto = 'mailto:'
recipient = if tyto.config.emailRecipient
then tyto.config.emailRecipient
else 'PI:EMAIL:<EMAIL>END_PI'
d = new Date()
subject = if tyto.config.emailSubject
then tyto.config.emailSubject
else 'items as of ' + d.toString()
content = tyto._getEmailContent()
content = encodeURIComponent content
mailtoString = mailto + recipient + '?subject=' +
encodeURIComponent(subject.trim()) + '&body=' + content
$('#tytoemail').attr 'href', mailtoString
$('#tytoemail')[0].click()
tyto::notify = (message, duration) ->
$message = $ '<div class= "tyto-notification notify" data-tyto-notify=" ' +
(duration / 1000) + ' ">' + message + '</div>'
$('body').prepend $message
setTimeout(->
$message.remove()
, duration)
tyto::showHelp = ->
tyto = this
if tyto.config.helpModalId
tyto.modals.helpModal = $ '#' + tyto.config.helpModalId
tyto.modals.helpModal.modal()
tyto::showInfo = ->
tyto = this
if tyto.config.infoModalId
tyto.modals.infoModal = $ '#' + tyto.config.infoModalId
tyto.modals.infoModal.modal()
tyto::_bindActions = ->
tyto = this
actionMap =
additem: 'addItem'
addcolumn: 'addColumn'
exportbarn: 'exportBarn'
loadbarn: 'loadBarn'
emailbarn: 'emailBarn'
helpbarn: 'showHelp'
infobarn: 'showInfo'
undolast: 'undoLast'
savebarn: 'saveBarn'
deletesave: 'deleteSave'
wipeboard: 'wipeBoard'
toggleautosave: 'toggleAutoSave'
action = ""
$('.actions').on 'click', '[data-action]', (e) ->
action = e.target.dataset.action
tyto[actionMap[action]]()
# set up action event listener for tracking actions to undo
$('body').on 'tyto:action', (event) ->
tyto.undo.action = event.name
tyto.undo.column = event.DOMcolumn
tyto.undo.item = event.DOMitem
tyto.undo.columnIndex = event.columnIndex
tyto.undo.itemIndex = event.itemIndex
tyto.undo.editContent = event.content
$('[data-action="undolast"]')
.removeAttr('disabled')
.removeClass('btn-disabled')
.addClass 'btn-default'
tyto
|
[
{
"context": "{\n name: 'BigSmithy'\n requires: ['Smithy']\n gainPriority: (st",
"end": 14,
"score": 0.9349634647369385,
"start": 11,
"tag": "NAME",
"value": "Big"
},
{
"context": "{\n name: 'BigSmithy'\n requires: ['Smithy']\n gainPriority: (stat",
"end": 16,
"score": 0.5667391419410706,
"start": 14,
"tag": "USERNAME",
"value": "Sm"
},
{
"context": "{\n name: 'BigSmithy'\n requires: ['Smithy']\n gainPriority: (state, m",
"end": 20,
"score": 0.5348185300827026,
"start": 16,
"tag": "NAME",
"value": "ithy"
}
] | strategies/BigSmithy.coffee | rspeer/dominiate | 65 | {
name: 'BigSmithy'
requires: ['Smithy']
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6 \
or state.countInSupply("Province") <= 6
"Duchy" if 0 < state.gainsToEndGame() <= 5
"Estate" if 0 < state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Smithy" if my.countInDeck("Smithy") < 2 \
and my.numCardsInDeck() >= 16
"Smithy" if my.countInDeck("Smithy") < 1
"Silver"
"Copper" if state.gainsToEndGame() <= 3
]
}
| 13811 | {
name: '<NAME>Sm<NAME>'
requires: ['Smithy']
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6 \
or state.countInSupply("Province") <= 6
"Duchy" if 0 < state.gainsToEndGame() <= 5
"Estate" if 0 < state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Smithy" if my.countInDeck("Smithy") < 2 \
and my.numCardsInDeck() >= 16
"Smithy" if my.countInDeck("Smithy") < 1
"Silver"
"Copper" if state.gainsToEndGame() <= 3
]
}
| true | {
name: 'PI:NAME:<NAME>END_PISmPI:NAME:<NAME>END_PI'
requires: ['Smithy']
gainPriority: (state, my) -> [
"Colony" if my.countInDeck("Platinum") > 0
"Province" if state.countInSupply("Colony") <= 6 \
or state.countInSupply("Province") <= 6
"Duchy" if 0 < state.gainsToEndGame() <= 5
"Estate" if 0 < state.gainsToEndGame() <= 2
"Platinum"
"Gold"
"Smithy" if my.countInDeck("Smithy") < 2 \
and my.numCardsInDeck() >= 16
"Smithy" if my.countInDeck("Smithy") < 1
"Silver"
"Copper" if state.gainsToEndGame() <= 3
]
}
|
[
{
"context": " label:'Apples'\n children:[\n label:'Granny Smith'\n onSelect:apple_selected\n ,\n ",
"end": 2364,
"score": 0.9996135830879211,
"start": 2352,
"tag": "NAME",
"value": "Granny Smith"
}
] | test/test_page.coffee | Synegen/angular-bootstrap-nav-tree | 0 |
deps = ['angularBootstrapNavTree']
if angular.version.full.indexOf("1.2")>=0
deps.push('ngAnimate')
app = angular.module 'AbnTest', deps
app.controller 'AbnTestController',($scope,$timeout,$sce)->
#
# a default "on-select" handler can be specified
# for the tree ( as attribute "on-select" )
#
$scope.my_tree_handler = (branch)->
$scope.output = "You selected: "+branch.label
if branch.data?.description
$scope.output += '('+branch.data.description+')'
#
# This example handler just sets "output",
# ...but your handler could do anything here...
#
#
# Each branch can define an "on-select" handler,
# which will be called instead of the default handler
#
#
# a single handler can be used on several branches, like this:
#
apple_selected = (branch)->
$scope.output = "APPLE! : "+branch.label
#
# ( your handler can do anything here )
#
#
# Example TREE DATA : Animal,Vegetable,Mineral
#
# Each branch can have the following attributes:
#
# label : the displayed text for the branch
# children : an array of branches ( or array of strings )
# onSelect : a function to run when branch is selected
# data : a place to put your own data -- can be anything
#
treedata_avm = [
label:'Animal'
children:[
label:'Dog'
data:
#
# "data" is yours -- put anything in here
# you can read it back in your on-select handler
# as "branch.data"
#
description:"man's best friend"
,
label:'Cat'
data:
description:"Felis catus"
,
label:'Hippopotamus'
data:
description:"hungry, hungry"
,
label:'Chicken'
render: (row) -> $sce.trustAsHtml("Marty's Chicken: " + row.label)
children:['White Leghorn','Rhode Island Red','Jersey Giant']
]
,
label:'Vegetable'
data:
definition:"A plant or part of a plant used as food, typically as accompaniment to meat or fish, such as a cabbage, potato, carrot, or bean."
data_can_contain_anything:true
onSelect:(branch)->
# special "on-select" function for this branch
$scope.output = "Vegetable: "+branch.data.definition
children:[
label:'Oranges'
,
label:'Apples'
children:[
label:'Granny Smith'
onSelect:apple_selected
,
label:'Red Delicous'
onSelect:apple_selected
,
label:'Fuji'
onSelect:apple_selected
]
]
,
label:'Mineral'
children:[
label:'Rock'
# children can be simply a list of strings
# if you are in a hurry
children:['Igneous','Sedimentary','Metamorphic']
,
label:'Metal'
children:['Aluminum','Steel','Copper']
,
label:'Plastic'
children:[
label:'Thermoplastic'
children:['polyethylene', 'polypropylene', 'polystyrene',' polyvinyl chloride']
,
label:'Thermosetting Polymer'
children:['polyester','polyurethane','vulcanized rubber','bakelite','urea-formaldehyde']
,
]
]
]
treedata_geography = [
label:'North America'
children:[
label:'Canada'
children:['Toronto','Vancouver']
,
label:'USA'
children:['New York','Los Angeles']
,
label:'Mexico'
children:['Mexico City','Guadalajara']
]
,
label:'South America'
children:[
label:'Venezuela'
children:['Caracas','Maracaibo']
,
label:'Brazil'
children:['Sao Paulo','Rio de Janeiro']
,
label:'Argentina'
children:['Buenos Aires','Cordoba']
]
]
$scope.my_data = treedata_avm
$scope.try_changing_the_tree_data = ()->
#
# switch between 2 sets of "treedata"
#
if $scope.my_data is treedata_avm
$scope.my_data = treedata_geography
else
$scope.my_data = treedata_avm
#
# TREE-CONTROL: the API for controlling the tree
#
$scope.my_tree = tree = {}
# just create an empty object, and pass it to the abn-tree as "tree-control"
# ...it will be populated with Tree API functions
$scope.try_every_branch = ()->
tree.for_each_branch (b)->
console.log b
$scope.try_async_load = ()->
$scope.my_data = []
$scope.doing_async = true
$timeout ->
if Math.random() < 0.5
$scope.my_data = treedata_avm
else
$scope.my_data = treedata_geography
$scope.doing_async = false
tree.expand_all()
,1000
$scope.try_deleteing_a_branch = ->
b = tree.get_selected_branch()
tree.remove_branch(b)
$scope.try_adding_a_branch = ->
b = tree.get_selected_branch()
tree.add_branch b,
label:'New Branch'
data:
something:42
else:43
| 77885 |
deps = ['angularBootstrapNavTree']
if angular.version.full.indexOf("1.2")>=0
deps.push('ngAnimate')
app = angular.module 'AbnTest', deps
app.controller 'AbnTestController',($scope,$timeout,$sce)->
#
# a default "on-select" handler can be specified
# for the tree ( as attribute "on-select" )
#
$scope.my_tree_handler = (branch)->
$scope.output = "You selected: "+branch.label
if branch.data?.description
$scope.output += '('+branch.data.description+')'
#
# This example handler just sets "output",
# ...but your handler could do anything here...
#
#
# Each branch can define an "on-select" handler,
# which will be called instead of the default handler
#
#
# a single handler can be used on several branches, like this:
#
apple_selected = (branch)->
$scope.output = "APPLE! : "+branch.label
#
# ( your handler can do anything here )
#
#
# Example TREE DATA : Animal,Vegetable,Mineral
#
# Each branch can have the following attributes:
#
# label : the displayed text for the branch
# children : an array of branches ( or array of strings )
# onSelect : a function to run when branch is selected
# data : a place to put your own data -- can be anything
#
treedata_avm = [
label:'Animal'
children:[
label:'Dog'
data:
#
# "data" is yours -- put anything in here
# you can read it back in your on-select handler
# as "branch.data"
#
description:"man's best friend"
,
label:'Cat'
data:
description:"Felis catus"
,
label:'Hippopotamus'
data:
description:"hungry, hungry"
,
label:'Chicken'
render: (row) -> $sce.trustAsHtml("Marty's Chicken: " + row.label)
children:['White Leghorn','Rhode Island Red','Jersey Giant']
]
,
label:'Vegetable'
data:
definition:"A plant or part of a plant used as food, typically as accompaniment to meat or fish, such as a cabbage, potato, carrot, or bean."
data_can_contain_anything:true
onSelect:(branch)->
# special "on-select" function for this branch
$scope.output = "Vegetable: "+branch.data.definition
children:[
label:'Oranges'
,
label:'Apples'
children:[
label:'<NAME>'
onSelect:apple_selected
,
label:'Red Delicous'
onSelect:apple_selected
,
label:'Fuji'
onSelect:apple_selected
]
]
,
label:'Mineral'
children:[
label:'Rock'
# children can be simply a list of strings
# if you are in a hurry
children:['Igneous','Sedimentary','Metamorphic']
,
label:'Metal'
children:['Aluminum','Steel','Copper']
,
label:'Plastic'
children:[
label:'Thermoplastic'
children:['polyethylene', 'polypropylene', 'polystyrene',' polyvinyl chloride']
,
label:'Thermosetting Polymer'
children:['polyester','polyurethane','vulcanized rubber','bakelite','urea-formaldehyde']
,
]
]
]
treedata_geography = [
label:'North America'
children:[
label:'Canada'
children:['Toronto','Vancouver']
,
label:'USA'
children:['New York','Los Angeles']
,
label:'Mexico'
children:['Mexico City','Guadalajara']
]
,
label:'South America'
children:[
label:'Venezuela'
children:['Caracas','Maracaibo']
,
label:'Brazil'
children:['Sao Paulo','Rio de Janeiro']
,
label:'Argentina'
children:['Buenos Aires','Cordoba']
]
]
$scope.my_data = treedata_avm
$scope.try_changing_the_tree_data = ()->
#
# switch between 2 sets of "treedata"
#
if $scope.my_data is treedata_avm
$scope.my_data = treedata_geography
else
$scope.my_data = treedata_avm
#
# TREE-CONTROL: the API for controlling the tree
#
$scope.my_tree = tree = {}
# just create an empty object, and pass it to the abn-tree as "tree-control"
# ...it will be populated with Tree API functions
$scope.try_every_branch = ()->
tree.for_each_branch (b)->
console.log b
$scope.try_async_load = ()->
$scope.my_data = []
$scope.doing_async = true
$timeout ->
if Math.random() < 0.5
$scope.my_data = treedata_avm
else
$scope.my_data = treedata_geography
$scope.doing_async = false
tree.expand_all()
,1000
$scope.try_deleteing_a_branch = ->
b = tree.get_selected_branch()
tree.remove_branch(b)
$scope.try_adding_a_branch = ->
b = tree.get_selected_branch()
tree.add_branch b,
label:'New Branch'
data:
something:42
else:43
| true |
deps = ['angularBootstrapNavTree']
if angular.version.full.indexOf("1.2")>=0
deps.push('ngAnimate')
app = angular.module 'AbnTest', deps
app.controller 'AbnTestController',($scope,$timeout,$sce)->
#
# a default "on-select" handler can be specified
# for the tree ( as attribute "on-select" )
#
$scope.my_tree_handler = (branch)->
$scope.output = "You selected: "+branch.label
if branch.data?.description
$scope.output += '('+branch.data.description+')'
#
# This example handler just sets "output",
# ...but your handler could do anything here...
#
#
# Each branch can define an "on-select" handler,
# which will be called instead of the default handler
#
#
# a single handler can be used on several branches, like this:
#
apple_selected = (branch)->
$scope.output = "APPLE! : "+branch.label
#
# ( your handler can do anything here )
#
#
# Example TREE DATA : Animal,Vegetable,Mineral
#
# Each branch can have the following attributes:
#
# label : the displayed text for the branch
# children : an array of branches ( or array of strings )
# onSelect : a function to run when branch is selected
# data : a place to put your own data -- can be anything
#
treedata_avm = [
label:'Animal'
children:[
label:'Dog'
data:
#
# "data" is yours -- put anything in here
# you can read it back in your on-select handler
# as "branch.data"
#
description:"man's best friend"
,
label:'Cat'
data:
description:"Felis catus"
,
label:'Hippopotamus'
data:
description:"hungry, hungry"
,
label:'Chicken'
render: (row) -> $sce.trustAsHtml("Marty's Chicken: " + row.label)
children:['White Leghorn','Rhode Island Red','Jersey Giant']
]
,
label:'Vegetable'
data:
definition:"A plant or part of a plant used as food, typically as accompaniment to meat or fish, such as a cabbage, potato, carrot, or bean."
data_can_contain_anything:true
onSelect:(branch)->
# special "on-select" function for this branch
$scope.output = "Vegetable: "+branch.data.definition
children:[
label:'Oranges'
,
label:'Apples'
children:[
label:'PI:NAME:<NAME>END_PI'
onSelect:apple_selected
,
label:'Red Delicous'
onSelect:apple_selected
,
label:'Fuji'
onSelect:apple_selected
]
]
,
label:'Mineral'
children:[
label:'Rock'
# children can be simply a list of strings
# if you are in a hurry
children:['Igneous','Sedimentary','Metamorphic']
,
label:'Metal'
children:['Aluminum','Steel','Copper']
,
label:'Plastic'
children:[
label:'Thermoplastic'
children:['polyethylene', 'polypropylene', 'polystyrene',' polyvinyl chloride']
,
label:'Thermosetting Polymer'
children:['polyester','polyurethane','vulcanized rubber','bakelite','urea-formaldehyde']
,
]
]
]
treedata_geography = [
label:'North America'
children:[
label:'Canada'
children:['Toronto','Vancouver']
,
label:'USA'
children:['New York','Los Angeles']
,
label:'Mexico'
children:['Mexico City','Guadalajara']
]
,
label:'South America'
children:[
label:'Venezuela'
children:['Caracas','Maracaibo']
,
label:'Brazil'
children:['Sao Paulo','Rio de Janeiro']
,
label:'Argentina'
children:['Buenos Aires','Cordoba']
]
]
$scope.my_data = treedata_avm
$scope.try_changing_the_tree_data = ()->
#
# switch between 2 sets of "treedata"
#
if $scope.my_data is treedata_avm
$scope.my_data = treedata_geography
else
$scope.my_data = treedata_avm
#
# TREE-CONTROL: the API for controlling the tree
#
$scope.my_tree = tree = {}
# just create an empty object, and pass it to the abn-tree as "tree-control"
# ...it will be populated with Tree API functions
$scope.try_every_branch = ()->
tree.for_each_branch (b)->
console.log b
$scope.try_async_load = ()->
$scope.my_data = []
$scope.doing_async = true
$timeout ->
if Math.random() < 0.5
$scope.my_data = treedata_avm
else
$scope.my_data = treedata_geography
$scope.doing_async = false
tree.expand_all()
,1000
$scope.try_deleteing_a_branch = ->
b = tree.get_selected_branch()
tree.remove_branch(b)
$scope.try_adding_a_branch = ->
b = tree.get_selected_branch()
tree.add_branch b,
label:'New Branch'
data:
something:42
else:43
|
[
{
"context": " # Some comments\n\n [group1]\n\n key1a=\"value1a\"\n\n # comment\n key1b=1\n\n # Ad",
"end": 351,
"score": 0.9973284602165222,
"start": 344,
"tag": "KEY",
"value": "value1a"
},
{
"context": " ## double comment\n key1b1 = value1b1\n following value\n [group2]\n ",
"end": 612,
"score": 0.7841576337814331,
"start": 610,
"tag": "KEY",
"value": "1b"
},
{
"context": " following value\n [group2]\n key1=value1b\n \"\"\"\n ,\n comment : '#'\n .should",
"end": 675,
"score": 0.9688859581947327,
"start": 668,
"tag": "KEY",
"value": "value1b"
},
{
"context": "me comments': null\n group1:\n key1a: '\"value1a\"'\n '# comment': null\n key1b: '1'\n ",
"end": 888,
"score": 0.997778594493866,
"start": 881,
"tag": "KEY",
"value": "value1a"
},
{
"context": "lue1a\"'\n '# comment': null\n key1b: '1'\n '# Administrators': null\n '# ----",
"end": 934,
"score": 0.7514915466308594,
"start": 933,
"tag": "KEY",
"value": "1"
},
{
"context": " '## [[[admin1aX]]]': null\n key1a1: 'value1a1'\n group1b:\n '# comment': null\n ",
"end": 1085,
"score": 0.9866245985031128,
"start": 1077,
"tag": "KEY",
"value": "value1a1"
},
{
"context": " '## double comment': null\n key1b1: \"value1b1following value\"\n group2:\n key1: 'valu",
"end": 1195,
"score": 0.8564192652702332,
"start": 1187,
"tag": "KEY",
"value": "value1b1"
},
{
"context": "omment': null\n key1b1: \"value1b1following value\"\n group2:\n key1: 'value1b'\n",
"end": 1210,
"score": 0.6531914472579956,
"start": 1205,
"tag": "KEY",
"value": "value"
},
{
"context": "e1b1following value\"\n group2:\n key1: 'value1b'\n",
"end": 1248,
"score": 0.9951807856559753,
"start": 1241,
"tag": "KEY",
"value": "value1b"
}
] | packages/core/test/misc.ini/parse_multi_brackets_multi_lines.coffee | chibanemourad/node-nikita | 1 |
ini = require '../../src/misc/ini'
{tags} = require '../test'
return unless tags.api
describe 'misc.ini parse_multi_brackets_multi_lines', ->
it 'parse', ->
ini.parse_multi_brackets_multi_lines """
###########################################################################
# Some comments
[group1]
key1a="value1a"
# comment
key1b=1
# Administrators
# ----------------
[[group1a1]]
## [[[admin1aX]]]
key1a1 = value1a1
[[group1b]]
# comment
## double comment
key1b1 = value1b1
following value
[group2]
key1=value1b
"""
,
comment : '#'
.should.eql
'###########################################################################': null
'# Some comments': null
group1:
key1a: '"value1a"'
'# comment': null
key1b: '1'
'# Administrators': null
'# ----------------': null
group1a1:
'## [[[admin1aX]]]': null
key1a1: 'value1a1'
group1b:
'# comment': null
'## double comment': null
key1b1: "value1b1following value"
group2:
key1: 'value1b'
| 208514 |
ini = require '../../src/misc/ini'
{tags} = require '../test'
return unless tags.api
describe 'misc.ini parse_multi_brackets_multi_lines', ->
it 'parse', ->
ini.parse_multi_brackets_multi_lines """
###########################################################################
# Some comments
[group1]
key1a="<KEY>"
# comment
key1b=1
# Administrators
# ----------------
[[group1a1]]
## [[[admin1aX]]]
key1a1 = value1a1
[[group1b]]
# comment
## double comment
key1b1 = value<KEY>1
following value
[group2]
key1=<KEY>
"""
,
comment : '#'
.should.eql
'###########################################################################': null
'# Some comments': null
group1:
key1a: '"<KEY>"'
'# comment': null
key1b: '<KEY>'
'# Administrators': null
'# ----------------': null
group1a1:
'## [[[admin1aX]]]': null
key1a1: '<KEY>'
group1b:
'# comment': null
'## double comment': null
key1b1: "<KEY>following <KEY>"
group2:
key1: '<KEY>'
| true |
ini = require '../../src/misc/ini'
{tags} = require '../test'
return unless tags.api
describe 'misc.ini parse_multi_brackets_multi_lines', ->
it 'parse', ->
ini.parse_multi_brackets_multi_lines """
###########################################################################
# Some comments
[group1]
key1a="PI:KEY:<KEY>END_PI"
# comment
key1b=1
# Administrators
# ----------------
[[group1a1]]
## [[[admin1aX]]]
key1a1 = value1a1
[[group1b]]
# comment
## double comment
key1b1 = valuePI:KEY:<KEY>END_PI1
following value
[group2]
key1=PI:KEY:<KEY>END_PI
"""
,
comment : '#'
.should.eql
'###########################################################################': null
'# Some comments': null
group1:
key1a: '"PI:KEY:<KEY>END_PI"'
'# comment': null
key1b: 'PI:KEY:<KEY>END_PI'
'# Administrators': null
'# ----------------': null
group1a1:
'## [[[admin1aX]]]': null
key1a1: 'PI:KEY:<KEY>END_PI'
group1b:
'# comment': null
'## double comment': null
key1b1: "PI:KEY:<KEY>END_PIfollowing PI:KEY:<KEY>END_PI"
group2:
key1: 'PI:KEY:<KEY>END_PI'
|
[
{
"context": "eIndex({ userName: 1 }, { unique: true })\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n@abstract\r\n###\r\nclass User",
"end": 377,
"score": 0.9998463988304138,
"start": 365,
"tag": "NAME",
"value": "Nathan Klick"
}
] | Workspace/QRef/NodeServer/src/schema/UserSchema.coffee | qrefdev/qref | 0 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
###
Schema representing an individual user object including their associated credentials, email address, and password recovery information.
@example MongoDB Collection
db.users
@example MongoDB Indexes
db.users.ensureIndex({ userName: 1 }, { unique: true })
@author Nathan Klick
@copyright QRef 2012
@abstract
###
class UserSchemaInternal
###
@property [String] (Required) The username used to perform authentication. This should always be the user's email address.
###
userName:
type: String
required: true
unique: true
###
@property [String] (Required) A SHA-512 HMAC representing the user's password.
###
passwordHash:
type: String
required: true
###
@property [String] (Required) A random SHA-512 hash used as a salt value in the password HMAC.
###
passwordSalt:
type: String
required: true
###
@property [String] (Optional) The first name of the user.
###
firstName:
type: String
required: false
###
@property [String] (Optional) The last name (surname) of the user.
###
lastName:
type: String
required: false
###
@property [String] (Required) The user's email address.
###
emailAddress:
type: String
required: true
###
@property [Array<ObjectId>] (Optional) The list of roles possessed by this user.
###
roles: [
type: ObjectId,
ref: 'user.roles'
]
###
@property [ObjectId] (Optional) The chosen recovery question for this user.
###
recoveryQuestion:
type: ObjectId
ref: 'user.recovery.questions'
required: false
###
@property [String] (Optional) An SHA-512 HMAC represting the user's answer to their recovery question.
###
recoveryAnswer:
type: String
required: false
timestamp:
type: Date
required: false
default: new Date()
UserSchema = new Schema(new UserSchemaInternal())
module.exports = UserSchema
| 190863 | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
###
Schema representing an individual user object including their associated credentials, email address, and password recovery information.
@example MongoDB Collection
db.users
@example MongoDB Indexes
db.users.ensureIndex({ userName: 1 }, { unique: true })
@author <NAME>
@copyright QRef 2012
@abstract
###
class UserSchemaInternal
###
@property [String] (Required) The username used to perform authentication. This should always be the user's email address.
###
userName:
type: String
required: true
unique: true
###
@property [String] (Required) A SHA-512 HMAC representing the user's password.
###
passwordHash:
type: String
required: true
###
@property [String] (Required) A random SHA-512 hash used as a salt value in the password HMAC.
###
passwordSalt:
type: String
required: true
###
@property [String] (Optional) The first name of the user.
###
firstName:
type: String
required: false
###
@property [String] (Optional) The last name (surname) of the user.
###
lastName:
type: String
required: false
###
@property [String] (Required) The user's email address.
###
emailAddress:
type: String
required: true
###
@property [Array<ObjectId>] (Optional) The list of roles possessed by this user.
###
roles: [
type: ObjectId,
ref: 'user.roles'
]
###
@property [ObjectId] (Optional) The chosen recovery question for this user.
###
recoveryQuestion:
type: ObjectId
ref: 'user.recovery.questions'
required: false
###
@property [String] (Optional) An SHA-512 HMAC represting the user's answer to their recovery question.
###
recoveryAnswer:
type: String
required: false
timestamp:
type: Date
required: false
default: new Date()
UserSchema = new Schema(new UserSchemaInternal())
module.exports = UserSchema
| true | mongoose = require('mongoose')
Schema = mongoose.Schema
ObjectId = Schema.ObjectId
###
Schema representing an individual user object including their associated credentials, email address, and password recovery information.
@example MongoDB Collection
db.users
@example MongoDB Indexes
db.users.ensureIndex({ userName: 1 }, { unique: true })
@author PI:NAME:<NAME>END_PI
@copyright QRef 2012
@abstract
###
class UserSchemaInternal
###
@property [String] (Required) The username used to perform authentication. This should always be the user's email address.
###
userName:
type: String
required: true
unique: true
###
@property [String] (Required) A SHA-512 HMAC representing the user's password.
###
passwordHash:
type: String
required: true
###
@property [String] (Required) A random SHA-512 hash used as a salt value in the password HMAC.
###
passwordSalt:
type: String
required: true
###
@property [String] (Optional) The first name of the user.
###
firstName:
type: String
required: false
###
@property [String] (Optional) The last name (surname) of the user.
###
lastName:
type: String
required: false
###
@property [String] (Required) The user's email address.
###
emailAddress:
type: String
required: true
###
@property [Array<ObjectId>] (Optional) The list of roles possessed by this user.
###
roles: [
type: ObjectId,
ref: 'user.roles'
]
###
@property [ObjectId] (Optional) The chosen recovery question for this user.
###
recoveryQuestion:
type: ObjectId
ref: 'user.recovery.questions'
required: false
###
@property [String] (Optional) An SHA-512 HMAC represting the user's answer to their recovery question.
###
recoveryAnswer:
type: String
required: false
timestamp:
type: Date
required: false
default: new Date()
UserSchema = new Schema(new UserSchemaInternal())
module.exports = UserSchema
|
[
{
"context": "able\n\t# @memberof defaults\n\t###\n\tapiKeyVariable: 'RESIN_API_KEY'\n",
"end": 2803,
"score": 0.9552525877952576,
"start": 2790,
"tag": "KEY",
"value": "RESIN_API_KEY"
}
] | packages/resin-settings-client/lib/defaults.coffee | resin-io-playground/resin-sdk-lerna | 0 | ###
Copyright 2016 Resin.io
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.
###
path = require('path')
userHome = require('home-or-tmp')
hidepath = require('hidepath')
###*
# @summary Default settings
# @namespace defaults
# @protected
###
module.exports =
###*
# @property {String} resinUrl - Resin.io url
# @memberof defaults
###
resinUrl: 'resin.io'
###*
# @property {Function} apiUrl - Resin.io API url
# @memberof defaults
###
apiUrl: ->
return "https://api.#{@resinUrl}"
###*
# @property {Function} vpnUrl - Resin.io VPN url
# @memberof defaults
###
vpnUrl: ->
return "vpn.#{@resinUrl}"
###*
# @property {Function} registryUrl - Resin.io Registry url
# @memberof defaults
###
registryUrl: ->
return "registry.#{@resinUrl}"
###*
# @property {Function} imageMakerUrl - Resin.io Image Maker url
# @memberof defaults
###
imageMakerUrl: ->
return "https://img.#{@resinUrl}"
###*
# @property {Function} deltaUrl - Resin.io Delta url
# @memberof defaults
###
deltaUrl: ->
return "https://delta.#{@resinUrl}"
###*
# @property {Function} dashboardUrl - Resin.io dashboard url
# @memberof defaults
###
dashboardUrl: ->
return "https://dashboard.#{@resinUrl}"
###*
# @property {Function} proxyUrl - Resin.io Proxy url
# @memberof defaults
###
proxyUrl: ->
if @resinUrl is 'resin.io'
return 'resindevice.io'
return "devices.#{@resinUrl}"
###*
# @property {String} dataDirectory - data directory path
# @memberof defaults
###
dataDirectory: path.join(userHome, hidepath('resin'))
###*
# @property {String} projectsDirectory - projects directory path
# @memberof defaults
###
projectsDirectory: path.join(userHome, 'ResinProjects')
###*
# @property {Function} cacheDirectory - cache directory path
# @memberof defaults
###
cacheDirectory: ->
return path.join(@dataDirectory, 'cache')
###*
# @property {Number} imageCacheTime - image cache time
# @memberof defaults
###
imageCacheTime: 1 * 1000 * 60 * 60 * 24 * 7 # 1 week in milliseconds
###*
# @property {Number} tokenRefreshInterval - token refresh interval
# @memberof defaults
###
tokenRefreshInterval: 1 * 1000 * 60 * 60 # 1 hour in milliseconds
###*
# @property {String} apiKeyVariable - api key environment variable
# @memberof defaults
###
apiKeyVariable: 'RESIN_API_KEY'
| 83440 | ###
Copyright 2016 Resin.io
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.
###
path = require('path')
userHome = require('home-or-tmp')
hidepath = require('hidepath')
###*
# @summary Default settings
# @namespace defaults
# @protected
###
module.exports =
###*
# @property {String} resinUrl - Resin.io url
# @memberof defaults
###
resinUrl: 'resin.io'
###*
# @property {Function} apiUrl - Resin.io API url
# @memberof defaults
###
apiUrl: ->
return "https://api.#{@resinUrl}"
###*
# @property {Function} vpnUrl - Resin.io VPN url
# @memberof defaults
###
vpnUrl: ->
return "vpn.#{@resinUrl}"
###*
# @property {Function} registryUrl - Resin.io Registry url
# @memberof defaults
###
registryUrl: ->
return "registry.#{@resinUrl}"
###*
# @property {Function} imageMakerUrl - Resin.io Image Maker url
# @memberof defaults
###
imageMakerUrl: ->
return "https://img.#{@resinUrl}"
###*
# @property {Function} deltaUrl - Resin.io Delta url
# @memberof defaults
###
deltaUrl: ->
return "https://delta.#{@resinUrl}"
###*
# @property {Function} dashboardUrl - Resin.io dashboard url
# @memberof defaults
###
dashboardUrl: ->
return "https://dashboard.#{@resinUrl}"
###*
# @property {Function} proxyUrl - Resin.io Proxy url
# @memberof defaults
###
proxyUrl: ->
if @resinUrl is 'resin.io'
return 'resindevice.io'
return "devices.#{@resinUrl}"
###*
# @property {String} dataDirectory - data directory path
# @memberof defaults
###
dataDirectory: path.join(userHome, hidepath('resin'))
###*
# @property {String} projectsDirectory - projects directory path
# @memberof defaults
###
projectsDirectory: path.join(userHome, 'ResinProjects')
###*
# @property {Function} cacheDirectory - cache directory path
# @memberof defaults
###
cacheDirectory: ->
return path.join(@dataDirectory, 'cache')
###*
# @property {Number} imageCacheTime - image cache time
# @memberof defaults
###
imageCacheTime: 1 * 1000 * 60 * 60 * 24 * 7 # 1 week in milliseconds
###*
# @property {Number} tokenRefreshInterval - token refresh interval
# @memberof defaults
###
tokenRefreshInterval: 1 * 1000 * 60 * 60 # 1 hour in milliseconds
###*
# @property {String} apiKeyVariable - api key environment variable
# @memberof defaults
###
apiKeyVariable: '<KEY>'
| true | ###
Copyright 2016 Resin.io
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.
###
path = require('path')
userHome = require('home-or-tmp')
hidepath = require('hidepath')
###*
# @summary Default settings
# @namespace defaults
# @protected
###
module.exports =
###*
# @property {String} resinUrl - Resin.io url
# @memberof defaults
###
resinUrl: 'resin.io'
###*
# @property {Function} apiUrl - Resin.io API url
# @memberof defaults
###
apiUrl: ->
return "https://api.#{@resinUrl}"
###*
# @property {Function} vpnUrl - Resin.io VPN url
# @memberof defaults
###
vpnUrl: ->
return "vpn.#{@resinUrl}"
###*
# @property {Function} registryUrl - Resin.io Registry url
# @memberof defaults
###
registryUrl: ->
return "registry.#{@resinUrl}"
###*
# @property {Function} imageMakerUrl - Resin.io Image Maker url
# @memberof defaults
###
imageMakerUrl: ->
return "https://img.#{@resinUrl}"
###*
# @property {Function} deltaUrl - Resin.io Delta url
# @memberof defaults
###
deltaUrl: ->
return "https://delta.#{@resinUrl}"
###*
# @property {Function} dashboardUrl - Resin.io dashboard url
# @memberof defaults
###
dashboardUrl: ->
return "https://dashboard.#{@resinUrl}"
###*
# @property {Function} proxyUrl - Resin.io Proxy url
# @memberof defaults
###
proxyUrl: ->
if @resinUrl is 'resin.io'
return 'resindevice.io'
return "devices.#{@resinUrl}"
###*
# @property {String} dataDirectory - data directory path
# @memberof defaults
###
dataDirectory: path.join(userHome, hidepath('resin'))
###*
# @property {String} projectsDirectory - projects directory path
# @memberof defaults
###
projectsDirectory: path.join(userHome, 'ResinProjects')
###*
# @property {Function} cacheDirectory - cache directory path
# @memberof defaults
###
cacheDirectory: ->
return path.join(@dataDirectory, 'cache')
###*
# @property {Number} imageCacheTime - image cache time
# @memberof defaults
###
imageCacheTime: 1 * 1000 * 60 * 60 * 24 * 7 # 1 week in milliseconds
###*
# @property {Number} tokenRefreshInterval - token refresh interval
# @memberof defaults
###
tokenRefreshInterval: 1 * 1000 * 60 * 60 # 1 hour in milliseconds
###*
# @property {String} apiKeyVariable - api key environment variable
# @memberof defaults
###
apiKeyVariable: 'PI:KEY:<KEY>END_PI'
|
[
{
"context": "classes have access to it\n constructor: (@db,@allDB)->\n #\n # section storyHeadMatter\n #\n storyHea",
"end": 216,
"score": 0.7461900115013123,
"start": 214,
"tag": "USERNAME",
"value": "DB"
},
{
"context": "ponent/\"\n T.meta name: \"author\", content: \"James A. Hinds: The Celarien's best friend. I'm not him, I wear",
"end": 485,
"score": 0.9998871684074402,
"start": 471,
"tag": "NAME",
"value": "James A. Hinds"
},
{
"context": " T.a \".github-corner\",href:\"https://github.com/jahbini/aframe-lowroller-component\", ->\n T.tag \"svg\"",
"end": 7500,
"score": 0.9995365738868713,
"start": 7493,
"tag": "USERNAME",
"value": "jahbini"
},
{
"context": "oter.panel\", bg: \"white\", =>\n T.h2 => T.raw \"James A. Hinds\"\n T.p => T.raw \"The ideas are yours to keep ",
"end": 9136,
"score": 0.999860405921936,
"start": 9122,
"tag": "NAME",
"value": "James A. Hinds"
},
{
"context": "Home\"\n allMeta = [[[\"name\",\"author\"],[\"content\",\"James A. Hinds: The Celarien's best friend. I'm not him, I wear",
"end": 10501,
"score": 0.9998660087585449,
"start": 10487,
"tag": "NAME",
"value": "James A. Hinds"
}
] | templates/lowrollertemplate.coffee | jahbini/aframe-lowroller-component | 0 | #
T = require 'halvalla'
#include card.coffee
console.log "SITE TEMPLATE"
module.exports = class lowrollerTemplate
#pass the db entry into the class so that the classes have access to it
constructor: (@db,@allDB)->
#
# section storyHeadMatter
#
storyHeadMatter: =>
return
#
# section html
#
html: =>
T.doctype 'html'
T.html =>
T.head =>
T.base href: "/aframe-lowroller-component/"
T.meta name: "author", content: "James A. Hinds: The Celarien's best friend. I'm not him, I wear glasses"
T.meta "http-equiv": "Content-Type", content: "text/html", charset: "UTF-8"
T.meta name: "viewport", content: "width=device-width, initial-scale=1"
T.title => T.raw (@db.title || "The LowRoller -- an example of an active defense against tragic shootings.")
T.meta name: "description", content: "some good thoughts. Maybe."
T.meta name: "keywords", content: "peace, how to wage peace, wisdom, tarot"
T.meta property: "fb:admins", content: "1981510532097452"
if false
T.script """
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
//console.log('statusChangeCallback');
//console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('fb-status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1981510532097452',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = \"//connect.facebook.net/en_US/sdk.js\";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
//console.log('Welcome! Fetching your information.... ');
FB.api('/me', 'get', {'fields':'first_name,gender'}, function(response) {
//console.log('Successful login for: ', response);
$('.FBname').text(response.first_name);
document.getElementById('fb-status').innerHTML =
'Thanks for logging in, ' + response.first_name + '!';
});
}
"""
T.script "document.styling = {\"palx\":\"#03c\",\"black\":\"#000\",\"white\":\"#fff\"}"
T.link rel: "apple-touch-icon", sizes: "57x57", href: "assets/icons/apple-icon-57x57.png"
T.link rel: "apple-touch-icon", sizes: "60x60", href: "assets/icons/apple-icon-60x60.png"
T.link rel: "apple-touch-icon", sizes: "72x72", href: "assets/icons/apple-icon-72x72.png"
T.link rel: "apple-touch-icon", sizes: "76x76", href: "assets/icons/apple-icon-76x76.png"
T.link rel: "apple-touch-icon", sizes: "114x114", href: "assets/icons/apple-icon-114x114.png"
T.link rel: "apple-touch-icon", sizes: "120x120", href: "assets/icons/apple-icon-120x120.png"
T.link rel: "apple-touch-icon", sizes: "144x144", href: "assets/icons/apple-icon-144x144.png"
T.link rel: "apple-touch-icon", sizes: "152x152", href: "assets/icons/apple-icon-152x152.png"
T.link rel: "apple-touch-icon", sizes: "180x180", href: "assets/icons/apple-icon-180x180.png"
T.link rel: "icon", type: "image/png", sizes: "192x192", href: "assets/icons/android-icon-192x192.png"
T.link rel: "icon", type: "image/png", sizes: "32x32", href: "assets/icons/favicon-32x32.png"
T.link rel: "icon", type: "image/png", sizes: "96x96", href: "assets/icons/favicon-96x96.png"
T.link rel: "icon", type: "image/png", sizes: "16x16", href: "assets/icons/favicon-16x16.png"
T.link rel: "manifest", href: "assets/manifest.json"
T.meta name: "msapplication-TileColor", content: "#ffffff"
T.meta name: "msapplication-TileImage", content: "assets/icons/ms-icon-144x144.png"
T.meta name: "theme-color", content: "#ffffff"
T.link rel: "stylesheet", href: "assets/css/vendor.css", "-content--encoding": "gzip"
T.link rel: "stylesheet", href: "assets/css/app.css", "-content--encoding": "gzip"
#T.link rel: "stylesheet", href: "app.css", "-content--encoding": "gzip"
T.link rel: "shortcut icon", href: "assets/icons/favicon.ico", type: "image/x-icon"
T.link rel: "icon", href: "assets/icons/favicon.ico", type: "image/x-icon"
T.script src: "allstories.json"
T.script src: "mystories.json"
T.script src: "assets/js/vendor.js", "-content--type": "text/javascript", "-content--encoding": "gzip"
T.script src: "assets/js/app.js", "-content--type": "text/javascript", "-content--encoding": "gzip"
T.script "siteHandle = 'lowroller'; topDomain = 'jahbini.github.io'; require('initialize');"
@storyHeadMatter()
T.body =>
@lowroller_body()
#
# section lowroller_body
#
lowroller_body: =>
T.div "#lowroller-body.c-text.o-grid.o-grid--full", =>
T.div ".style.c-hero", style: "{ border-bottom: 1px solid #333; }"
T.div ".c-hero.o-grid__cell.u-higher", =>
@header()
T.div ".o-grid__cell", style: "min-height:100vh", =>
T.div ".o-grid", =>
T.div "#storybar.o-grid__cell.order-2",=>
@storyBar()
@sidebar()
@sidecar()
@footer()
@cover()
#
# section storyBar
#
storyBar: =>
headlines = @db.headlines
headline = '---'
if l=headlines?.length
r = Math.floor (Math.random() * l)
headline = headlines[r ]
HalvallaCard "#main.bg-silver",{
shadow:"highest"
divider:true
footerText: "that's all--"
headerText: @db?.title
subHeaderText: headline
content: @bloviation
}
#
# section cover
#
cover: =>
T.div "#cover", style: "background-image:url(assets/images/hooray-fade2.jpg);-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH"
# <!-- GitHub Corner. -->
T.a ".github-corner",href:"https://github.com/jahbini/aframe-lowroller-component", ->
T.tag "svg", width:"80", height:"80", "viewBox":"0 0 250 250", style:"fill:#222; color:#fff; position: absolute; top: 0; border: 0; right: 0;",->
T.tag "path", d:"M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"
T.tag "path",".octo-arm", d:"M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2",fill:"currentColor", style:"transform-origin: 130px 106px;"
T.tag "path", ".octo-body", d:"M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z", fill:"currentColor"
T.style '',".github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}"
#<!-- End GitHub Corner. -->
#
# section footer
#
footer: =>
T.div "#footer.panel", bg: "white", =>
T.h2 => T.raw "James A. Hinds"
T.p => T.raw "The ideas are yours to keep and share, the wording is mine."
#
# section sidecar
#
sidecar: =>
return
T.div "#sidecar.o-grid__cell.o-grid__cell--width-fixed.order-last.bg-darken-2", style: "min-width:240", =>
T.div ".fb-login-button", width: "200", "data-width": "200", "data-max-rows": "1", "data-size": "medium", "data-button-type": "login_with", "data-show-faces": "true", "data-auto-logout-link": "true", "data-use-continue-as": "true"
@fb_status()
#
# section fb_status
#
fb_status: =>
T.div "#fb-status"
#
# section sidebar
#
sidebar: =>
T.aside "#sidebar.o-grid__cell.o-grid__cell--width-20.p2.bg-darken-2", style: "min-width:240"
#
# section storybar
#
#
# section bloviation
#
#
# section header
#
header: =>
T.header "#header.o-grid.o-grid--bottom", style: "height:250px", =>
T.div ".c-avatar.u-super", =>
T.img ".c-avatar__img", style: "-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH", src: "https://www.gravatar.com/avatar/c105eda1978979dfb13059b8878ef95d?s=90"
T.div ".o-grid__cell.o-grid__cell--width-30", =>
T.h3 =>
T.a ".fa.fa-home", href: "/", => T.raw "Home"
allMeta = [[["name","author"],["content","James A. Hinds: The Celarien's best friend. I'm not him, I wear glasses"]],[["http-equiv","Content-Type"],["content","text/html"],["charset","UTF-8"]],[["name","viewport"],["content","width=device-width, initial-scale=1"]],[["name","description"],["content","some good thoughts. Maybe."]],[["name","keywords"],["content","romance, wisdom, tarot"]],[["property","fb:admins"],["content","1981510532097452"]],[["name","msapplication-TileColor"],["content","#ffffff"]],[["name","msapplication-TileImage"],["content","assets/icons/ms-icon-144x144.png"]],[["name","theme-color"],["content","#ffffff"]]]
htmlTitle = "Practical Metaphysics and Harmonious Mana." | 48764 | #
T = require 'halvalla'
#include card.coffee
console.log "SITE TEMPLATE"
module.exports = class lowrollerTemplate
#pass the db entry into the class so that the classes have access to it
constructor: (@db,@allDB)->
#
# section storyHeadMatter
#
storyHeadMatter: =>
return
#
# section html
#
html: =>
T.doctype 'html'
T.html =>
T.head =>
T.base href: "/aframe-lowroller-component/"
T.meta name: "author", content: "<NAME>: The Celarien's best friend. I'm not him, I wear glasses"
T.meta "http-equiv": "Content-Type", content: "text/html", charset: "UTF-8"
T.meta name: "viewport", content: "width=device-width, initial-scale=1"
T.title => T.raw (@db.title || "The LowRoller -- an example of an active defense against tragic shootings.")
T.meta name: "description", content: "some good thoughts. Maybe."
T.meta name: "keywords", content: "peace, how to wage peace, wisdom, tarot"
T.meta property: "fb:admins", content: "1981510532097452"
if false
T.script """
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
//console.log('statusChangeCallback');
//console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('fb-status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1981510532097452',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = \"//connect.facebook.net/en_US/sdk.js\";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
//console.log('Welcome! Fetching your information.... ');
FB.api('/me', 'get', {'fields':'first_name,gender'}, function(response) {
//console.log('Successful login for: ', response);
$('.FBname').text(response.first_name);
document.getElementById('fb-status').innerHTML =
'Thanks for logging in, ' + response.first_name + '!';
});
}
"""
T.script "document.styling = {\"palx\":\"#03c\",\"black\":\"#000\",\"white\":\"#fff\"}"
T.link rel: "apple-touch-icon", sizes: "57x57", href: "assets/icons/apple-icon-57x57.png"
T.link rel: "apple-touch-icon", sizes: "60x60", href: "assets/icons/apple-icon-60x60.png"
T.link rel: "apple-touch-icon", sizes: "72x72", href: "assets/icons/apple-icon-72x72.png"
T.link rel: "apple-touch-icon", sizes: "76x76", href: "assets/icons/apple-icon-76x76.png"
T.link rel: "apple-touch-icon", sizes: "114x114", href: "assets/icons/apple-icon-114x114.png"
T.link rel: "apple-touch-icon", sizes: "120x120", href: "assets/icons/apple-icon-120x120.png"
T.link rel: "apple-touch-icon", sizes: "144x144", href: "assets/icons/apple-icon-144x144.png"
T.link rel: "apple-touch-icon", sizes: "152x152", href: "assets/icons/apple-icon-152x152.png"
T.link rel: "apple-touch-icon", sizes: "180x180", href: "assets/icons/apple-icon-180x180.png"
T.link rel: "icon", type: "image/png", sizes: "192x192", href: "assets/icons/android-icon-192x192.png"
T.link rel: "icon", type: "image/png", sizes: "32x32", href: "assets/icons/favicon-32x32.png"
T.link rel: "icon", type: "image/png", sizes: "96x96", href: "assets/icons/favicon-96x96.png"
T.link rel: "icon", type: "image/png", sizes: "16x16", href: "assets/icons/favicon-16x16.png"
T.link rel: "manifest", href: "assets/manifest.json"
T.meta name: "msapplication-TileColor", content: "#ffffff"
T.meta name: "msapplication-TileImage", content: "assets/icons/ms-icon-144x144.png"
T.meta name: "theme-color", content: "#ffffff"
T.link rel: "stylesheet", href: "assets/css/vendor.css", "-content--encoding": "gzip"
T.link rel: "stylesheet", href: "assets/css/app.css", "-content--encoding": "gzip"
#T.link rel: "stylesheet", href: "app.css", "-content--encoding": "gzip"
T.link rel: "shortcut icon", href: "assets/icons/favicon.ico", type: "image/x-icon"
T.link rel: "icon", href: "assets/icons/favicon.ico", type: "image/x-icon"
T.script src: "allstories.json"
T.script src: "mystories.json"
T.script src: "assets/js/vendor.js", "-content--type": "text/javascript", "-content--encoding": "gzip"
T.script src: "assets/js/app.js", "-content--type": "text/javascript", "-content--encoding": "gzip"
T.script "siteHandle = 'lowroller'; topDomain = 'jahbini.github.io'; require('initialize');"
@storyHeadMatter()
T.body =>
@lowroller_body()
#
# section lowroller_body
#
lowroller_body: =>
T.div "#lowroller-body.c-text.o-grid.o-grid--full", =>
T.div ".style.c-hero", style: "{ border-bottom: 1px solid #333; }"
T.div ".c-hero.o-grid__cell.u-higher", =>
@header()
T.div ".o-grid__cell", style: "min-height:100vh", =>
T.div ".o-grid", =>
T.div "#storybar.o-grid__cell.order-2",=>
@storyBar()
@sidebar()
@sidecar()
@footer()
@cover()
#
# section storyBar
#
storyBar: =>
headlines = @db.headlines
headline = '---'
if l=headlines?.length
r = Math.floor (Math.random() * l)
headline = headlines[r ]
HalvallaCard "#main.bg-silver",{
shadow:"highest"
divider:true
footerText: "that's all--"
headerText: @db?.title
subHeaderText: headline
content: @bloviation
}
#
# section cover
#
cover: =>
T.div "#cover", style: "background-image:url(assets/images/hooray-fade2.jpg);-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH"
# <!-- GitHub Corner. -->
T.a ".github-corner",href:"https://github.com/jahbini/aframe-lowroller-component", ->
T.tag "svg", width:"80", height:"80", "viewBox":"0 0 250 250", style:"fill:#222; color:#fff; position: absolute; top: 0; border: 0; right: 0;",->
T.tag "path", d:"M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"
T.tag "path",".octo-arm", d:"M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2",fill:"currentColor", style:"transform-origin: 130px 106px;"
T.tag "path", ".octo-body", d:"M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z", fill:"currentColor"
T.style '',".github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}"
#<!-- End GitHub Corner. -->
#
# section footer
#
footer: =>
T.div "#footer.panel", bg: "white", =>
T.h2 => T.raw "<NAME>"
T.p => T.raw "The ideas are yours to keep and share, the wording is mine."
#
# section sidecar
#
sidecar: =>
return
T.div "#sidecar.o-grid__cell.o-grid__cell--width-fixed.order-last.bg-darken-2", style: "min-width:240", =>
T.div ".fb-login-button", width: "200", "data-width": "200", "data-max-rows": "1", "data-size": "medium", "data-button-type": "login_with", "data-show-faces": "true", "data-auto-logout-link": "true", "data-use-continue-as": "true"
@fb_status()
#
# section fb_status
#
fb_status: =>
T.div "#fb-status"
#
# section sidebar
#
sidebar: =>
T.aside "#sidebar.o-grid__cell.o-grid__cell--width-20.p2.bg-darken-2", style: "min-width:240"
#
# section storybar
#
#
# section bloviation
#
#
# section header
#
header: =>
T.header "#header.o-grid.o-grid--bottom", style: "height:250px", =>
T.div ".c-avatar.u-super", =>
T.img ".c-avatar__img", style: "-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH", src: "https://www.gravatar.com/avatar/c105eda1978979dfb13059b8878ef95d?s=90"
T.div ".o-grid__cell.o-grid__cell--width-30", =>
T.h3 =>
T.a ".fa.fa-home", href: "/", => T.raw "Home"
allMeta = [[["name","author"],["content","<NAME>: The Celarien's best friend. I'm not him, I wear glasses"]],[["http-equiv","Content-Type"],["content","text/html"],["charset","UTF-8"]],[["name","viewport"],["content","width=device-width, initial-scale=1"]],[["name","description"],["content","some good thoughts. Maybe."]],[["name","keywords"],["content","romance, wisdom, tarot"]],[["property","fb:admins"],["content","1981510532097452"]],[["name","msapplication-TileColor"],["content","#ffffff"]],[["name","msapplication-TileImage"],["content","assets/icons/ms-icon-144x144.png"]],[["name","theme-color"],["content","#ffffff"]]]
htmlTitle = "Practical Metaphysics and Harmonious Mana." | true | #
T = require 'halvalla'
#include card.coffee
console.log "SITE TEMPLATE"
module.exports = class lowrollerTemplate
#pass the db entry into the class so that the classes have access to it
constructor: (@db,@allDB)->
#
# section storyHeadMatter
#
storyHeadMatter: =>
return
#
# section html
#
html: =>
T.doctype 'html'
T.html =>
T.head =>
T.base href: "/aframe-lowroller-component/"
T.meta name: "author", content: "PI:NAME:<NAME>END_PI: The Celarien's best friend. I'm not him, I wear glasses"
T.meta "http-equiv": "Content-Type", content: "text/html", charset: "UTF-8"
T.meta name: "viewport", content: "width=device-width, initial-scale=1"
T.title => T.raw (@db.title || "The LowRoller -- an example of an active defense against tragic shootings.")
T.meta name: "description", content: "some good thoughts. Maybe."
T.meta name: "keywords", content: "peace, how to wage peace, wisdom, tarot"
T.meta property: "fb:admins", content: "1981510532097452"
if false
T.script """
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
//console.log('statusChangeCallback');
//console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
testAPI();
} else {
// The person is not logged into your app or we are unable to tell.
document.getElementById('fb-status').innerHTML = 'Please log ' +
'into this app.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '1981510532097452',
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = \"//connect.facebook.net/en_US/sdk.js\";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
//console.log('Welcome! Fetching your information.... ');
FB.api('/me', 'get', {'fields':'first_name,gender'}, function(response) {
//console.log('Successful login for: ', response);
$('.FBname').text(response.first_name);
document.getElementById('fb-status').innerHTML =
'Thanks for logging in, ' + response.first_name + '!';
});
}
"""
T.script "document.styling = {\"palx\":\"#03c\",\"black\":\"#000\",\"white\":\"#fff\"}"
T.link rel: "apple-touch-icon", sizes: "57x57", href: "assets/icons/apple-icon-57x57.png"
T.link rel: "apple-touch-icon", sizes: "60x60", href: "assets/icons/apple-icon-60x60.png"
T.link rel: "apple-touch-icon", sizes: "72x72", href: "assets/icons/apple-icon-72x72.png"
T.link rel: "apple-touch-icon", sizes: "76x76", href: "assets/icons/apple-icon-76x76.png"
T.link rel: "apple-touch-icon", sizes: "114x114", href: "assets/icons/apple-icon-114x114.png"
T.link rel: "apple-touch-icon", sizes: "120x120", href: "assets/icons/apple-icon-120x120.png"
T.link rel: "apple-touch-icon", sizes: "144x144", href: "assets/icons/apple-icon-144x144.png"
T.link rel: "apple-touch-icon", sizes: "152x152", href: "assets/icons/apple-icon-152x152.png"
T.link rel: "apple-touch-icon", sizes: "180x180", href: "assets/icons/apple-icon-180x180.png"
T.link rel: "icon", type: "image/png", sizes: "192x192", href: "assets/icons/android-icon-192x192.png"
T.link rel: "icon", type: "image/png", sizes: "32x32", href: "assets/icons/favicon-32x32.png"
T.link rel: "icon", type: "image/png", sizes: "96x96", href: "assets/icons/favicon-96x96.png"
T.link rel: "icon", type: "image/png", sizes: "16x16", href: "assets/icons/favicon-16x16.png"
T.link rel: "manifest", href: "assets/manifest.json"
T.meta name: "msapplication-TileColor", content: "#ffffff"
T.meta name: "msapplication-TileImage", content: "assets/icons/ms-icon-144x144.png"
T.meta name: "theme-color", content: "#ffffff"
T.link rel: "stylesheet", href: "assets/css/vendor.css", "-content--encoding": "gzip"
T.link rel: "stylesheet", href: "assets/css/app.css", "-content--encoding": "gzip"
#T.link rel: "stylesheet", href: "app.css", "-content--encoding": "gzip"
T.link rel: "shortcut icon", href: "assets/icons/favicon.ico", type: "image/x-icon"
T.link rel: "icon", href: "assets/icons/favicon.ico", type: "image/x-icon"
T.script src: "allstories.json"
T.script src: "mystories.json"
T.script src: "assets/js/vendor.js", "-content--type": "text/javascript", "-content--encoding": "gzip"
T.script src: "assets/js/app.js", "-content--type": "text/javascript", "-content--encoding": "gzip"
T.script "siteHandle = 'lowroller'; topDomain = 'jahbini.github.io'; require('initialize');"
@storyHeadMatter()
T.body =>
@lowroller_body()
#
# section lowroller_body
#
lowroller_body: =>
T.div "#lowroller-body.c-text.o-grid.o-grid--full", =>
T.div ".style.c-hero", style: "{ border-bottom: 1px solid #333; }"
T.div ".c-hero.o-grid__cell.u-higher", =>
@header()
T.div ".o-grid__cell", style: "min-height:100vh", =>
T.div ".o-grid", =>
T.div "#storybar.o-grid__cell.order-2",=>
@storyBar()
@sidebar()
@sidecar()
@footer()
@cover()
#
# section storyBar
#
storyBar: =>
headlines = @db.headlines
headline = '---'
if l=headlines?.length
r = Math.floor (Math.random() * l)
headline = headlines[r ]
HalvallaCard "#main.bg-silver",{
shadow:"highest"
divider:true
footerText: "that's all--"
headerText: @db?.title
subHeaderText: headline
content: @bloviation
}
#
# section cover
#
cover: =>
T.div "#cover", style: "background-image:url(assets/images/hooray-fade2.jpg);-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH"
# <!-- GitHub Corner. -->
T.a ".github-corner",href:"https://github.com/jahbini/aframe-lowroller-component", ->
T.tag "svg", width:"80", height:"80", "viewBox":"0 0 250 250", style:"fill:#222; color:#fff; position: absolute; top: 0; border: 0; right: 0;",->
T.tag "path", d:"M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"
T.tag "path",".octo-arm", d:"M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2",fill:"currentColor", style:"transform-origin: 130px 106px;"
T.tag "path", ".octo-body", d:"M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z", fill:"currentColor"
T.style '',".github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}"
#<!-- End GitHub Corner. -->
#
# section footer
#
footer: =>
T.div "#footer.panel", bg: "white", =>
T.h2 => T.raw "PI:NAME:<NAME>END_PI"
T.p => T.raw "The ideas are yours to keep and share, the wording is mine."
#
# section sidecar
#
sidecar: =>
return
T.div "#sidecar.o-grid__cell.o-grid__cell--width-fixed.order-last.bg-darken-2", style: "min-width:240", =>
T.div ".fb-login-button", width: "200", "data-width": "200", "data-max-rows": "1", "data-size": "medium", "data-button-type": "login_with", "data-show-faces": "true", "data-auto-logout-link": "true", "data-use-continue-as": "true"
@fb_status()
#
# section fb_status
#
fb_status: =>
T.div "#fb-status"
#
# section sidebar
#
sidebar: =>
T.aside "#sidebar.o-grid__cell.o-grid__cell--width-20.p2.bg-darken-2", style: "min-width:240"
#
# section storybar
#
#
# section bloviation
#
#
# section header
#
header: =>
T.header "#header.o-grid.o-grid--bottom", style: "height:250px", =>
T.div ".c-avatar.u-super", =>
T.img ".c-avatar__img", style: "-moz-transform:scaleX(-1);-o-transform:scaleX(-1);-webkit-transform:scaleX(-1);transform:scaleX(-1);filter:FlipH;ms-filter:FlipH", src: "https://www.gravatar.com/avatar/c105eda1978979dfb13059b8878ef95d?s=90"
T.div ".o-grid__cell.o-grid__cell--width-30", =>
T.h3 =>
T.a ".fa.fa-home", href: "/", => T.raw "Home"
allMeta = [[["name","author"],["content","PI:NAME:<NAME>END_PI: The Celarien's best friend. I'm not him, I wear glasses"]],[["http-equiv","Content-Type"],["content","text/html"],["charset","UTF-8"]],[["name","viewport"],["content","width=device-width, initial-scale=1"]],[["name","description"],["content","some good thoughts. Maybe."]],[["name","keywords"],["content","romance, wisdom, tarot"]],[["property","fb:admins"],["content","1981510532097452"]],[["name","msapplication-TileColor"],["content","#ffffff"]],[["name","msapplication-TileImage"],["content","assets/icons/ms-icon-144x144.png"]],[["name","theme-color"],["content","#ffffff"]]]
htmlTitle = "Practical Metaphysics and Harmonious Mana." |
[
{
"context": "# @link http://podstats.org/\n# @author Dennis Morhardt <info@dennismorhardt.de>\n# @copyright Copyright",
"end": 93,
"score": 0.9998798370361328,
"start": 78,
"tag": "NAME",
"value": "Dennis Morhardt"
},
{
"context": "p://podstats.org/\n# @author Dennis Morhardt <info@dennismorhardt.de>\n# @copyright Copyright 2014, Dennis Morhardt\n#",
"end": 117,
"score": 0.9999352693557739,
"start": 95,
"tag": "EMAIL",
"value": "info@dennismorhardt.de"
},
{
"context": "@dennismorhardt.de>\n# @copyright Copyright 2014, Dennis Morhardt\n# @license BSD-3-Clause, http://opensource.or",
"end": 165,
"score": 0.9998688101768494,
"start": 150,
"tag": "NAME",
"value": "Dennis Morhardt"
}
] | Application/Assets/javascripts/components/download-clients.coffee | gglnx/podstats | 0 | ##
# @package Podstats
# @link http://podstats.org/
# @author Dennis Morhardt <info@dennismorhardt.de>
# @copyright Copyright 2014, Dennis Morhardt
# @license BSD-3-Clause, http://opensource.org/licenses/BSD-3-Clause
##
# Download clients
define ['jquery', 'moment', 'Raphael', 'morris'], ($, moment, Raphael) -> $ ()->
$('[data-type="download-clients"]').each (index, el)->
# Setup moment
moment.lang 'de'
# 1. Get data from API
$.ajax
url: $(el).data 'source'
dataType: 'json'
# 2. Generate graph
.done (response)->
# Check if response is ok and we got data
if response.ok == false or response.data? == false
return
# Remove loading class
$(el).removeClass 'graph-loading'
# No data? Show message
if response.data.length == 0
$(el).addClass 'no-data'
$(el).parent().addClass 'no-data'
$(el).append 'Keine Daten für diesen Zeitraum vorhanden.'
return
# Init morris
new Morris.Donut
element: $(el).attr 'id'
data: response.data
resize: true
formatter: (y)-> return y + '%'
| 29006 | ##
# @package Podstats
# @link http://podstats.org/
# @author <NAME> <<EMAIL>>
# @copyright Copyright 2014, <NAME>
# @license BSD-3-Clause, http://opensource.org/licenses/BSD-3-Clause
##
# Download clients
define ['jquery', 'moment', 'Raphael', 'morris'], ($, moment, Raphael) -> $ ()->
$('[data-type="download-clients"]').each (index, el)->
# Setup moment
moment.lang 'de'
# 1. Get data from API
$.ajax
url: $(el).data 'source'
dataType: 'json'
# 2. Generate graph
.done (response)->
# Check if response is ok and we got data
if response.ok == false or response.data? == false
return
# Remove loading class
$(el).removeClass 'graph-loading'
# No data? Show message
if response.data.length == 0
$(el).addClass 'no-data'
$(el).parent().addClass 'no-data'
$(el).append 'Keine Daten für diesen Zeitraum vorhanden.'
return
# Init morris
new Morris.Donut
element: $(el).attr 'id'
data: response.data
resize: true
formatter: (y)-> return y + '%'
| true | ##
# @package Podstats
# @link http://podstats.org/
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# @copyright Copyright 2014, PI:NAME:<NAME>END_PI
# @license BSD-3-Clause, http://opensource.org/licenses/BSD-3-Clause
##
# Download clients
define ['jquery', 'moment', 'Raphael', 'morris'], ($, moment, Raphael) -> $ ()->
$('[data-type="download-clients"]').each (index, el)->
# Setup moment
moment.lang 'de'
# 1. Get data from API
$.ajax
url: $(el).data 'source'
dataType: 'json'
# 2. Generate graph
.done (response)->
# Check if response is ok and we got data
if response.ok == false or response.data? == false
return
# Remove loading class
$(el).removeClass 'graph-loading'
# No data? Show message
if response.data.length == 0
$(el).addClass 'no-data'
$(el).parent().addClass 'no-data'
$(el).append 'Keine Daten für diesen Zeitraum vorhanden.'
return
# Init morris
new Morris.Donut
element: $(el).attr 'id'
data: response.data
resize: true
formatter: (y)-> return y + '%'
|
[
{
"context": "###\n# config/env/development.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# Development en",
"end": 58,
"score": 0.9995800256729126,
"start": 47,
"tag": "NAME",
"value": "Dan Nichols"
}
] | lib/config/env/development.coffee | dlnichols/h_media | 0 | ###
# config/env/development.coffee
#
# © 2014 Dan Nichols
# See LICENSE for more details
#
# Development environment configuration details
###
'use strict'
###
# Development environment
###
module.exports = exports =
env: 'development'
logger: 'dev'
mongo:
uri: 'mongodb://localhost/h_media-dev'
| 140377 | ###
# config/env/development.coffee
#
# © 2014 <NAME>
# See LICENSE for more details
#
# Development environment configuration details
###
'use strict'
###
# Development environment
###
module.exports = exports =
env: 'development'
logger: 'dev'
mongo:
uri: 'mongodb://localhost/h_media-dev'
| true | ###
# config/env/development.coffee
#
# © 2014 PI:NAME:<NAME>END_PI
# See LICENSE for more details
#
# Development environment configuration details
###
'use strict'
###
# Development environment
###
module.exports = exports =
env: 'development'
logger: 'dev'
mongo:
uri: 'mongodb://localhost/h_media-dev'
|
[
{
"context": "p.test \"gist bugs url\", (t) ->\n d = repository: \"git@gist.github.com:123456.git\"\n normalize d\n t.same d.repository,\n",
"end": 3332,
"score": 0.99737548828125,
"start": 3313,
"tag": "EMAIL",
"value": "git@gist.github.com"
},
{
"context": "\n t.same d.repository,\n type: \"git\"\n url: \"git@gist.github.com:123456.git\"\n\n t.same d.bugs,\n url: \"https://g",
"end": 3427,
"score": 0.9380389451980591,
"start": 3408,
"tag": "EMAIL",
"value": "git@gist.github.com"
},
{
"context": "arize repositories\", (t) ->\n d = repositories: [\"git@gist.github.com:123456.git\"]\n normalize d\n t.same d.repository,",
"end": 3606,
"score": 0.9754751324653625,
"start": 3587,
"tag": "EMAIL",
"value": "git@gist.github.com"
},
{
"context": "\n t.same d.repository,\n type: \"git\"\n url: \"git@gist.github.com:123456.git\"\n\n t.end()\n return\n\ntap.test \"treat ",
"end": 3702,
"score": 0.9986518621444702,
"start": 3683,
"tag": "EMAIL",
"value": "git@gist.github.com"
},
{
"context": "m:123456.git\"\n\n t.end()\n return\n\ntap.test \"treat visionmedia/express as github repo\", (t) ->\n d = repository:",
"end": 3763,
"score": 0.9155145883560181,
"start": 3752,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "t) ->\n d = repository:\n type: \"git\"\n url: \"visionmedia/express\"\n\n normalize d\n t.same d.repository,\n ",
"end": 3851,
"score": 0.9696840643882751,
"start": 3840,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "ory,\n type: \"git\"\n url: \"https://github.com/visionmedia/express\"\n\n t.end()\n return\n\ntap.test \"treat isa",
"end": 3955,
"score": 0.9982291460037231,
"start": 3944,
"tag": "USERNAME",
"value": "visionmedia"
},
{
"context": "edia/express\"\n\n t.end()\n return\n\ntap.test \"treat isaacs/node-graceful-fs as github repo\", (t) ->\n d = re",
"end": 4008,
"score": 0.9993498921394348,
"start": 4002,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": "t) ->\n d = repository:\n type: \"git\"\n url: \"isaacs/node-graceful-fs\"\n\n normalize d\n t.same d.repos",
"end": 4100,
"score": 0.9992243051528931,
"start": 4094,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": "ory,\n type: \"git\"\n url: \"https://github.com/isaacs/node-graceful-fs\"\n\n t.end()\n return\n\ntap.test \"",
"end": 4208,
"score": 0.9995489716529846,
"start": 4202,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": "ory:\n type: \"git\"\n url: \"https://github.com/isaacs/node-graceful-fs\"\n\n t.same a.homepage, \"https://",
"end": 4431,
"score": 0.9995077848434448,
"start": 4425,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": "ful-fs\"\n\n t.same a.homepage, \"https://github.com/isaacs/node-graceful-fs\"\n t.end()\n return\n\ntap.test \"h",
"end": 4498,
"score": 0.9993517398834229,
"start": 4492,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": "rmalize a = repository:\n type: \"git\"\n url: \"git@gist.github.com:123456.git\"\n\n t.same a.homepage, \"https://gist.g",
"end": 4712,
"score": 0.9981551170349121,
"start": 4693,
"tag": "EMAIL",
"value": "git@gist.github.com"
},
{
"context": "rmalize a = repository:\n type: \"git\"\n url: \"sindresorhus/chalk\"\n\n t.same a.homepage, \"https://github.com/",
"end": 4983,
"score": 0.9997037649154663,
"start": 4971,
"tag": "USERNAME",
"value": "sindresorhus"
},
{
"context": "/chalk\"\n\n t.same a.homepage, \"https://github.com/sindresorhus/chalk\"\n t.end()\n return\n\ntap.test \"treat isaacs",
"end": 5045,
"score": 0.9997138977050781,
"start": 5033,
"tag": "USERNAME",
"value": "sindresorhus"
},
{
"context": "esorhus/chalk\"\n t.end()\n return\n\ntap.test \"treat isaacs/node-graceful-fs as github repo in dependencies\",",
"end": 5095,
"score": 0.9974009990692139,
"start": 5089,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": ") ->\n d = dependencies:\n \"node-graceful-fs\": \"isaacs/node-graceful-fs\"\n\n normalize d\n t.same d.depen",
"end": 5204,
"score": 0.9993619918823242,
"start": 5198,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": ",\n \"node-graceful-fs\": \"git+https://github.com/isaacs/node-graceful-fs\"\n\n t.end()\n return\n\ntap.test \"",
"end": 5317,
"score": 0.9996916055679321,
"start": 5311,
"tag": "USERNAME",
"value": "isaacs"
}
] | deps/npm/node_modules/normalize-package-data/test/normalize.coffee | lxe/io.coffee | 0 | tap = require("tap")
fs = require("fs")
path = require("path")
globals = Object.keys(global)
normalize = require("../lib/normalize")
warningMessages = require("../lib/warning_messages.json")
safeFormat = require("../lib/safe_format")
rpjPath = path.resolve(__dirname, "./fixtures/read-package-json.json")
tap.test "normalize some package data", (t) ->
packageData = require(rpjPath)
warnings = []
normalize packageData, (warning) ->
warnings.push warning
return
# there's no readme data in this particular object
t.equal warnings.length, 1, "There's exactly one warning."
fs.readFile rpjPath, (err, data) ->
throw err if err
# Various changes have been made
t.notEqual packageData, JSON.parse(data), "Output is different from input."
t.end()
return
return
tap.test "runs without passing warning function", (t) ->
packageData = require(rpjPath)
fs.readFile rpjPath, (err, data) ->
throw err if err
normalize JSON.parse(data)
t.ok true, "If you read this, this means I'm still alive."
t.end()
return
return
tap.test "empty object", (t) ->
warn = (m) ->
warnings.push m
return
packageData = {}
expect =
name: ""
version: ""
readme: "ERROR: No README data found!"
_id: "@"
warnings = []
normalize packageData, warn
t.same packageData, expect
t.same warnings, [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
]
t.end()
return
tap.test "core module name", (t) ->
warn = (m) ->
warnings.push m
return
warnings = []
a = undefined
normalize a =
name: "http"
readme: "read yourself how about"
homepage: 123
bugs: "what is this i don't even"
repository: "Hello."
, warn
expect = [
safeFormat(warningMessages.conflictingName, "http")
warningMessages.nonEmailUrlBugsString
warningMessages.emptyNormalizedBugs
warningMessages.nonUrlHomepage
]
t.same warnings, expect
t.end()
return
tap.test "urls required", (t) ->
warn = (w) ->
warnings.push w
return
warnings = []
normalize
bugs:
url: "/1"
email: "not an email address"
, warn
a = undefined
normalize a =
readme: "read yourself how about"
homepage: 123
bugs: "what is this i don't even"
repository: "Hello."
, warn
console.error a
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.nonUrlBugsUrlField
warningMessages.nonEmailBugsEmailField
warningMessages.emptyNormalizedBugs
warningMessages.missingReadme
warningMessages.nonEmailUrlBugsString
warningMessages.emptyNormalizedBugs
warningMessages.nonUrlHomepage
]
t.same warnings, expect
t.end()
return
tap.test "homepage field must start with a protocol.", (t) ->
warn = (w) ->
warnings.push w
return
warnings = []
a = undefined
normalize a = homepage: "example.org", warn
console.error a
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
warningMessages.missingProtocolHomepage
]
t.same warnings, expect
t.same a.homepage, "http://example.org"
t.end()
return
tap.test "gist bugs url", (t) ->
d = repository: "git@gist.github.com:123456.git"
normalize d
t.same d.repository,
type: "git"
url: "git@gist.github.com:123456.git"
t.same d.bugs,
url: "https://gist.github.com/123456"
t.end()
return
tap.test "singularize repositories", (t) ->
d = repositories: ["git@gist.github.com:123456.git"]
normalize d
t.same d.repository,
type: "git"
url: "git@gist.github.com:123456.git"
t.end()
return
tap.test "treat visionmedia/express as github repo", (t) ->
d = repository:
type: "git"
url: "visionmedia/express"
normalize d
t.same d.repository,
type: "git"
url: "https://github.com/visionmedia/express"
t.end()
return
tap.test "treat isaacs/node-graceful-fs as github repo", (t) ->
d = repository:
type: "git"
url: "isaacs/node-graceful-fs"
normalize d
t.same d.repository,
type: "git"
url: "https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "homepage field will set to github url if repository is a github repo", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "https://github.com/isaacs/node-graceful-fs"
t.same a.homepage, "https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "homepage field will set to github gist url if repository is a gist", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "git@gist.github.com:123456.git"
t.same a.homepage, "https://gist.github.com/123456"
t.end()
return
tap.test "homepage field will set to github gist url if repository is a shorthand reference", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "sindresorhus/chalk"
t.same a.homepage, "https://github.com/sindresorhus/chalk"
t.end()
return
tap.test "treat isaacs/node-graceful-fs as github repo in dependencies", (t) ->
d = dependencies:
"node-graceful-fs": "isaacs/node-graceful-fs"
normalize d
t.same d.dependencies,
"node-graceful-fs": "git+https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "deprecation warning for array in dependencies fields", (t) ->
warn = (w) ->
warnings.push w
return
a = undefined
warnings = []
normalize a =
dependencies: []
devDependencies: []
optionalDependencies: []
, warn
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "dependencies")), "deprecation warning"
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "devDependencies")), "deprecation warning"
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "optionalDependencies")), "deprecation warning"
t.end()
return
tap.test "no new globals", (t) ->
t.same Object.keys(global), globals
t.end()
return
| 15464 | tap = require("tap")
fs = require("fs")
path = require("path")
globals = Object.keys(global)
normalize = require("../lib/normalize")
warningMessages = require("../lib/warning_messages.json")
safeFormat = require("../lib/safe_format")
rpjPath = path.resolve(__dirname, "./fixtures/read-package-json.json")
tap.test "normalize some package data", (t) ->
packageData = require(rpjPath)
warnings = []
normalize packageData, (warning) ->
warnings.push warning
return
# there's no readme data in this particular object
t.equal warnings.length, 1, "There's exactly one warning."
fs.readFile rpjPath, (err, data) ->
throw err if err
# Various changes have been made
t.notEqual packageData, JSON.parse(data), "Output is different from input."
t.end()
return
return
tap.test "runs without passing warning function", (t) ->
packageData = require(rpjPath)
fs.readFile rpjPath, (err, data) ->
throw err if err
normalize JSON.parse(data)
t.ok true, "If you read this, this means I'm still alive."
t.end()
return
return
tap.test "empty object", (t) ->
warn = (m) ->
warnings.push m
return
packageData = {}
expect =
name: ""
version: ""
readme: "ERROR: No README data found!"
_id: "@"
warnings = []
normalize packageData, warn
t.same packageData, expect
t.same warnings, [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
]
t.end()
return
tap.test "core module name", (t) ->
warn = (m) ->
warnings.push m
return
warnings = []
a = undefined
normalize a =
name: "http"
readme: "read yourself how about"
homepage: 123
bugs: "what is this i don't even"
repository: "Hello."
, warn
expect = [
safeFormat(warningMessages.conflictingName, "http")
warningMessages.nonEmailUrlBugsString
warningMessages.emptyNormalizedBugs
warningMessages.nonUrlHomepage
]
t.same warnings, expect
t.end()
return
tap.test "urls required", (t) ->
warn = (w) ->
warnings.push w
return
warnings = []
normalize
bugs:
url: "/1"
email: "not an email address"
, warn
a = undefined
normalize a =
readme: "read yourself how about"
homepage: 123
bugs: "what is this i don't even"
repository: "Hello."
, warn
console.error a
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.nonUrlBugsUrlField
warningMessages.nonEmailBugsEmailField
warningMessages.emptyNormalizedBugs
warningMessages.missingReadme
warningMessages.nonEmailUrlBugsString
warningMessages.emptyNormalizedBugs
warningMessages.nonUrlHomepage
]
t.same warnings, expect
t.end()
return
tap.test "homepage field must start with a protocol.", (t) ->
warn = (w) ->
warnings.push w
return
warnings = []
a = undefined
normalize a = homepage: "example.org", warn
console.error a
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
warningMessages.missingProtocolHomepage
]
t.same warnings, expect
t.same a.homepage, "http://example.org"
t.end()
return
tap.test "gist bugs url", (t) ->
d = repository: "<EMAIL>:123456.git"
normalize d
t.same d.repository,
type: "git"
url: "<EMAIL>:123456.git"
t.same d.bugs,
url: "https://gist.github.com/123456"
t.end()
return
tap.test "singularize repositories", (t) ->
d = repositories: ["<EMAIL>:123456.git"]
normalize d
t.same d.repository,
type: "git"
url: "<EMAIL>:123456.git"
t.end()
return
tap.test "treat visionmedia/express as github repo", (t) ->
d = repository:
type: "git"
url: "visionmedia/express"
normalize d
t.same d.repository,
type: "git"
url: "https://github.com/visionmedia/express"
t.end()
return
tap.test "treat isaacs/node-graceful-fs as github repo", (t) ->
d = repository:
type: "git"
url: "isaacs/node-graceful-fs"
normalize d
t.same d.repository,
type: "git"
url: "https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "homepage field will set to github url if repository is a github repo", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "https://github.com/isaacs/node-graceful-fs"
t.same a.homepage, "https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "homepage field will set to github gist url if repository is a gist", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "<EMAIL>:123456.git"
t.same a.homepage, "https://gist.github.com/123456"
t.end()
return
tap.test "homepage field will set to github gist url if repository is a shorthand reference", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "sindresorhus/chalk"
t.same a.homepage, "https://github.com/sindresorhus/chalk"
t.end()
return
tap.test "treat isaacs/node-graceful-fs as github repo in dependencies", (t) ->
d = dependencies:
"node-graceful-fs": "isaacs/node-graceful-fs"
normalize d
t.same d.dependencies,
"node-graceful-fs": "git+https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "deprecation warning for array in dependencies fields", (t) ->
warn = (w) ->
warnings.push w
return
a = undefined
warnings = []
normalize a =
dependencies: []
devDependencies: []
optionalDependencies: []
, warn
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "dependencies")), "deprecation warning"
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "devDependencies")), "deprecation warning"
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "optionalDependencies")), "deprecation warning"
t.end()
return
tap.test "no new globals", (t) ->
t.same Object.keys(global), globals
t.end()
return
| true | tap = require("tap")
fs = require("fs")
path = require("path")
globals = Object.keys(global)
normalize = require("../lib/normalize")
warningMessages = require("../lib/warning_messages.json")
safeFormat = require("../lib/safe_format")
rpjPath = path.resolve(__dirname, "./fixtures/read-package-json.json")
tap.test "normalize some package data", (t) ->
packageData = require(rpjPath)
warnings = []
normalize packageData, (warning) ->
warnings.push warning
return
# there's no readme data in this particular object
t.equal warnings.length, 1, "There's exactly one warning."
fs.readFile rpjPath, (err, data) ->
throw err if err
# Various changes have been made
t.notEqual packageData, JSON.parse(data), "Output is different from input."
t.end()
return
return
tap.test "runs without passing warning function", (t) ->
packageData = require(rpjPath)
fs.readFile rpjPath, (err, data) ->
throw err if err
normalize JSON.parse(data)
t.ok true, "If you read this, this means I'm still alive."
t.end()
return
return
tap.test "empty object", (t) ->
warn = (m) ->
warnings.push m
return
packageData = {}
expect =
name: ""
version: ""
readme: "ERROR: No README data found!"
_id: "@"
warnings = []
normalize packageData, warn
t.same packageData, expect
t.same warnings, [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
]
t.end()
return
tap.test "core module name", (t) ->
warn = (m) ->
warnings.push m
return
warnings = []
a = undefined
normalize a =
name: "http"
readme: "read yourself how about"
homepage: 123
bugs: "what is this i don't even"
repository: "Hello."
, warn
expect = [
safeFormat(warningMessages.conflictingName, "http")
warningMessages.nonEmailUrlBugsString
warningMessages.emptyNormalizedBugs
warningMessages.nonUrlHomepage
]
t.same warnings, expect
t.end()
return
tap.test "urls required", (t) ->
warn = (w) ->
warnings.push w
return
warnings = []
normalize
bugs:
url: "/1"
email: "not an email address"
, warn
a = undefined
normalize a =
readme: "read yourself how about"
homepage: 123
bugs: "what is this i don't even"
repository: "Hello."
, warn
console.error a
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.nonUrlBugsUrlField
warningMessages.nonEmailBugsEmailField
warningMessages.emptyNormalizedBugs
warningMessages.missingReadme
warningMessages.nonEmailUrlBugsString
warningMessages.emptyNormalizedBugs
warningMessages.nonUrlHomepage
]
t.same warnings, expect
t.end()
return
tap.test "homepage field must start with a protocol.", (t) ->
warn = (w) ->
warnings.push w
return
warnings = []
a = undefined
normalize a = homepage: "example.org", warn
console.error a
expect = [
warningMessages.missingDescription
warningMessages.missingRepository
warningMessages.missingReadme
warningMessages.missingProtocolHomepage
]
t.same warnings, expect
t.same a.homepage, "http://example.org"
t.end()
return
tap.test "gist bugs url", (t) ->
d = repository: "PI:EMAIL:<EMAIL>END_PI:123456.git"
normalize d
t.same d.repository,
type: "git"
url: "PI:EMAIL:<EMAIL>END_PI:123456.git"
t.same d.bugs,
url: "https://gist.github.com/123456"
t.end()
return
tap.test "singularize repositories", (t) ->
d = repositories: ["PI:EMAIL:<EMAIL>END_PI:123456.git"]
normalize d
t.same d.repository,
type: "git"
url: "PI:EMAIL:<EMAIL>END_PI:123456.git"
t.end()
return
tap.test "treat visionmedia/express as github repo", (t) ->
d = repository:
type: "git"
url: "visionmedia/express"
normalize d
t.same d.repository,
type: "git"
url: "https://github.com/visionmedia/express"
t.end()
return
tap.test "treat isaacs/node-graceful-fs as github repo", (t) ->
d = repository:
type: "git"
url: "isaacs/node-graceful-fs"
normalize d
t.same d.repository,
type: "git"
url: "https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "homepage field will set to github url if repository is a github repo", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "https://github.com/isaacs/node-graceful-fs"
t.same a.homepage, "https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "homepage field will set to github gist url if repository is a gist", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "PI:EMAIL:<EMAIL>END_PI:123456.git"
t.same a.homepage, "https://gist.github.com/123456"
t.end()
return
tap.test "homepage field will set to github gist url if repository is a shorthand reference", (t) ->
a = undefined
normalize a = repository:
type: "git"
url: "sindresorhus/chalk"
t.same a.homepage, "https://github.com/sindresorhus/chalk"
t.end()
return
tap.test "treat isaacs/node-graceful-fs as github repo in dependencies", (t) ->
d = dependencies:
"node-graceful-fs": "isaacs/node-graceful-fs"
normalize d
t.same d.dependencies,
"node-graceful-fs": "git+https://github.com/isaacs/node-graceful-fs"
t.end()
return
tap.test "deprecation warning for array in dependencies fields", (t) ->
warn = (w) ->
warnings.push w
return
a = undefined
warnings = []
normalize a =
dependencies: []
devDependencies: []
optionalDependencies: []
, warn
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "dependencies")), "deprecation warning"
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "devDependencies")), "deprecation warning"
t.ok ~warnings.indexOf(safeFormat(warningMessages.deprecatedArrayDependencies, "optionalDependencies")), "deprecation warning"
t.end()
return
tap.test "no new globals", (t) ->
t.same Object.keys(global), globals
t.end()
return
|
[
{
"context": "EmailFinder = ->\n {\n full_name: @full_name\n domain: @domain\n email: @email\n ",
"end": 35,
"score": 0.6885184645652771,
"start": 35,
"tag": "NAME",
"value": ""
},
{
"context": "EmailFinder = ->\n {\n full_name: @full_name\n domain: @domain\n email: @email\n sc",
"end": 41,
"score": 0.4417552947998047,
"start": 37,
"tag": "NAME",
"value": "full"
}
] | src/browser_action/js/email_finder.coffee | hunter-io/browser-extension | 10 | EmailFinder = ->
{
full_name: @full_name
domain: @domain
email: @email
score: @score
sources: @sources
validateForm: ->
_this = @
$("#full-name-field").one "keyup", (e) ->
setTimeout (->
if (
$("#full-name-field").val().indexOf(" ") != -1 &&
$("#full-name-field").val().length > 4
)
if (
$("#email-finder").is(":hidden") &&
$("#flash .alert-danger").length == 0 &&
typeof $("#full-name-field").data("bs.tooltip") == "undefined"
)
$("#full-name-field").tooltip(title: "Press enter to find the email address.").tooltip("show")
), 6000
$("#email-finder-search").unbind().submit ->
if (
$("#full-name-field").val().indexOf(" ") == -1 ||
$("#full-name-field").val().length <= 4
)
$("#full-name-field").tooltip(title: "Please enter the full name of the person to find the email address.").tooltip("show")
else
_this.submit()
false
submit: ->
$(".email-finder-loader").show()
@domain = window.domain
@full_name = $("#full-name-field").val()
@fetch()
fetch: ->
@cleanFinderResults()
if typeof $("#full-name-field").data("bs.tooltip") != "undefined"
$("#full-name-field").tooltip("destroy")
_this = @
$.ajax
url: Api.emailFinder(_this.domain, _this.full_name, window.api_key)
headers: "Email-Hunter-Origin": "chrome_extension"
type: "GET"
data: format: "json"
dataType: "json"
jsonp: false
error: (xhr, statusText, err) ->
$(".email-finder-loader").hide()
if xhr.status == 400
displayError "Sorry, something went wrong with the query."
else if xhr.status == 401
$(".connect-again-container").show()
else if xhr.status == 403
$("#domain-search").hide()
$("#blocked-notification").show()
else if xhr.status == 429
unless _this.trial
Account.returnRequestsError (e) ->
displayError e
else
$(".connect-container").show()
else
displayError DOMPurify.sanitize(xhr.responseJSON["errors"][0]["details"])
success: (result) ->
if result.data.email == null
$(".email-finder-loader").hide()
displayError "We didn't find the email address of this person."
else
_this.domain = result.data.domain
_this.email = result.data.email
_this.score = result.data.score
_this.accept_all = result.data.accept_all
_this.verification = result.data.verification
_this.position = result.data.position
_this.company = result.data.company
_this.twitter = result.data.twitter
_this.linkedin = result.data.linkedin
_this.sources = result.data.sources
_this.first_name = Utilities.toTitleCase(result.data.first_name)
_this.last_name = Utilities.toTitleCase(result.data.last_name)
_this.render()
render: ->
$(".email-finder-loader").hide()
# Display: complete search link or Sign up CTA
unless @trial
$(".header-search-link").attr "href", "https://hunter.io/search/" + @domain + "?utm_source=chrome_extension&utm_medium=chrome_extension&utm_campaign=extension&utm_content=browser_popup"
$(".header-search-link").show()
else
$(".header-signup-link").show()
# Confidence score color
if @score < 30
@confidence_score_class = "low-score"
else if @score > 70
@confidence_score_class = "high-score"
else
@confidence_score_class = "average-score"
# The title of the profile
if @position? && @company?
@title = "#{@position} at #{@company}"
else if @position?
@title = "#{@position} at #{@domain}"
else if @company?
@title = @company
else
@title = @domain
# Display: the method used
if @sources.length > 0
s = if @sources.length == 1 then "" else "s"
@method = "We found this email address <strong>" + @sources.length + "</strong> time"+s+" on the web."
else
@method = "This email address is our best guess for this person. We haven't found it on the web."
# Prepare the template
Handlebars.registerHelper "ifIsVerified", (verification_status, options) ->
if verification_status == "valid"
return options.fn(this)
options.inverse this
Handlebars.registerHelper "md5", (options) ->
new Handlebars.SafeString(Utilities.MD5(options.fn(this)))
template = JST["src/browser_action/templates/finder.hbs"]
finder_html = $(template(@))
# Generate the DOM with the template and display it
$("#email-finder").html finder_html
$("#email-finder").slideDown 200
# Display: the sources if any
if @sources.length > 0
$(".finder-result-sources").show()
# Display: the tooltips
$("[data-toggle='tooltip']").tooltip()
# Event: the copy action
Utilities.copyEmailListener()
$(".finder-result-pic img").on "load", ->
$(this).css "opacity", "1"
# Display: the button to save the lead
lead_button = $(".finder-result-email .save-lead-button")
lead_button.data
first_name: @first_name
last_name: @last_name
email: @email
confidence_score: @score
lead = new LeadButton
lead.saveButtonListener(lead_button)
lead.disableSaveLeadButtonIfLeadExists(lead_button)
cleanFinderResults: ->
$("#email-finder").html ""
$("#email-finder").hide()
}
| 222782 | EmailFinder = ->
{
full_name:<NAME> @<NAME>_name
domain: @domain
email: @email
score: @score
sources: @sources
validateForm: ->
_this = @
$("#full-name-field").one "keyup", (e) ->
setTimeout (->
if (
$("#full-name-field").val().indexOf(" ") != -1 &&
$("#full-name-field").val().length > 4
)
if (
$("#email-finder").is(":hidden") &&
$("#flash .alert-danger").length == 0 &&
typeof $("#full-name-field").data("bs.tooltip") == "undefined"
)
$("#full-name-field").tooltip(title: "Press enter to find the email address.").tooltip("show")
), 6000
$("#email-finder-search").unbind().submit ->
if (
$("#full-name-field").val().indexOf(" ") == -1 ||
$("#full-name-field").val().length <= 4
)
$("#full-name-field").tooltip(title: "Please enter the full name of the person to find the email address.").tooltip("show")
else
_this.submit()
false
submit: ->
$(".email-finder-loader").show()
@domain = window.domain
@full_name = $("#full-name-field").val()
@fetch()
fetch: ->
@cleanFinderResults()
if typeof $("#full-name-field").data("bs.tooltip") != "undefined"
$("#full-name-field").tooltip("destroy")
_this = @
$.ajax
url: Api.emailFinder(_this.domain, _this.full_name, window.api_key)
headers: "Email-Hunter-Origin": "chrome_extension"
type: "GET"
data: format: "json"
dataType: "json"
jsonp: false
error: (xhr, statusText, err) ->
$(".email-finder-loader").hide()
if xhr.status == 400
displayError "Sorry, something went wrong with the query."
else if xhr.status == 401
$(".connect-again-container").show()
else if xhr.status == 403
$("#domain-search").hide()
$("#blocked-notification").show()
else if xhr.status == 429
unless _this.trial
Account.returnRequestsError (e) ->
displayError e
else
$(".connect-container").show()
else
displayError DOMPurify.sanitize(xhr.responseJSON["errors"][0]["details"])
success: (result) ->
if result.data.email == null
$(".email-finder-loader").hide()
displayError "We didn't find the email address of this person."
else
_this.domain = result.data.domain
_this.email = result.data.email
_this.score = result.data.score
_this.accept_all = result.data.accept_all
_this.verification = result.data.verification
_this.position = result.data.position
_this.company = result.data.company
_this.twitter = result.data.twitter
_this.linkedin = result.data.linkedin
_this.sources = result.data.sources
_this.first_name = Utilities.toTitleCase(result.data.first_name)
_this.last_name = Utilities.toTitleCase(result.data.last_name)
_this.render()
render: ->
$(".email-finder-loader").hide()
# Display: complete search link or Sign up CTA
unless @trial
$(".header-search-link").attr "href", "https://hunter.io/search/" + @domain + "?utm_source=chrome_extension&utm_medium=chrome_extension&utm_campaign=extension&utm_content=browser_popup"
$(".header-search-link").show()
else
$(".header-signup-link").show()
# Confidence score color
if @score < 30
@confidence_score_class = "low-score"
else if @score > 70
@confidence_score_class = "high-score"
else
@confidence_score_class = "average-score"
# The title of the profile
if @position? && @company?
@title = "#{@position} at #{@company}"
else if @position?
@title = "#{@position} at #{@domain}"
else if @company?
@title = @company
else
@title = @domain
# Display: the method used
if @sources.length > 0
s = if @sources.length == 1 then "" else "s"
@method = "We found this email address <strong>" + @sources.length + "</strong> time"+s+" on the web."
else
@method = "This email address is our best guess for this person. We haven't found it on the web."
# Prepare the template
Handlebars.registerHelper "ifIsVerified", (verification_status, options) ->
if verification_status == "valid"
return options.fn(this)
options.inverse this
Handlebars.registerHelper "md5", (options) ->
new Handlebars.SafeString(Utilities.MD5(options.fn(this)))
template = JST["src/browser_action/templates/finder.hbs"]
finder_html = $(template(@))
# Generate the DOM with the template and display it
$("#email-finder").html finder_html
$("#email-finder").slideDown 200
# Display: the sources if any
if @sources.length > 0
$(".finder-result-sources").show()
# Display: the tooltips
$("[data-toggle='tooltip']").tooltip()
# Event: the copy action
Utilities.copyEmailListener()
$(".finder-result-pic img").on "load", ->
$(this).css "opacity", "1"
# Display: the button to save the lead
lead_button = $(".finder-result-email .save-lead-button")
lead_button.data
first_name: @first_name
last_name: @last_name
email: @email
confidence_score: @score
lead = new LeadButton
lead.saveButtonListener(lead_button)
lead.disableSaveLeadButtonIfLeadExists(lead_button)
cleanFinderResults: ->
$("#email-finder").html ""
$("#email-finder").hide()
}
| true | EmailFinder = ->
{
full_name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI_name
domain: @domain
email: @email
score: @score
sources: @sources
validateForm: ->
_this = @
$("#full-name-field").one "keyup", (e) ->
setTimeout (->
if (
$("#full-name-field").val().indexOf(" ") != -1 &&
$("#full-name-field").val().length > 4
)
if (
$("#email-finder").is(":hidden") &&
$("#flash .alert-danger").length == 0 &&
typeof $("#full-name-field").data("bs.tooltip") == "undefined"
)
$("#full-name-field").tooltip(title: "Press enter to find the email address.").tooltip("show")
), 6000
$("#email-finder-search").unbind().submit ->
if (
$("#full-name-field").val().indexOf(" ") == -1 ||
$("#full-name-field").val().length <= 4
)
$("#full-name-field").tooltip(title: "Please enter the full name of the person to find the email address.").tooltip("show")
else
_this.submit()
false
submit: ->
$(".email-finder-loader").show()
@domain = window.domain
@full_name = $("#full-name-field").val()
@fetch()
fetch: ->
@cleanFinderResults()
if typeof $("#full-name-field").data("bs.tooltip") != "undefined"
$("#full-name-field").tooltip("destroy")
_this = @
$.ajax
url: Api.emailFinder(_this.domain, _this.full_name, window.api_key)
headers: "Email-Hunter-Origin": "chrome_extension"
type: "GET"
data: format: "json"
dataType: "json"
jsonp: false
error: (xhr, statusText, err) ->
$(".email-finder-loader").hide()
if xhr.status == 400
displayError "Sorry, something went wrong with the query."
else if xhr.status == 401
$(".connect-again-container").show()
else if xhr.status == 403
$("#domain-search").hide()
$("#blocked-notification").show()
else if xhr.status == 429
unless _this.trial
Account.returnRequestsError (e) ->
displayError e
else
$(".connect-container").show()
else
displayError DOMPurify.sanitize(xhr.responseJSON["errors"][0]["details"])
success: (result) ->
if result.data.email == null
$(".email-finder-loader").hide()
displayError "We didn't find the email address of this person."
else
_this.domain = result.data.domain
_this.email = result.data.email
_this.score = result.data.score
_this.accept_all = result.data.accept_all
_this.verification = result.data.verification
_this.position = result.data.position
_this.company = result.data.company
_this.twitter = result.data.twitter
_this.linkedin = result.data.linkedin
_this.sources = result.data.sources
_this.first_name = Utilities.toTitleCase(result.data.first_name)
_this.last_name = Utilities.toTitleCase(result.data.last_name)
_this.render()
render: ->
$(".email-finder-loader").hide()
# Display: complete search link or Sign up CTA
unless @trial
$(".header-search-link").attr "href", "https://hunter.io/search/" + @domain + "?utm_source=chrome_extension&utm_medium=chrome_extension&utm_campaign=extension&utm_content=browser_popup"
$(".header-search-link").show()
else
$(".header-signup-link").show()
# Confidence score color
if @score < 30
@confidence_score_class = "low-score"
else if @score > 70
@confidence_score_class = "high-score"
else
@confidence_score_class = "average-score"
# The title of the profile
if @position? && @company?
@title = "#{@position} at #{@company}"
else if @position?
@title = "#{@position} at #{@domain}"
else if @company?
@title = @company
else
@title = @domain
# Display: the method used
if @sources.length > 0
s = if @sources.length == 1 then "" else "s"
@method = "We found this email address <strong>" + @sources.length + "</strong> time"+s+" on the web."
else
@method = "This email address is our best guess for this person. We haven't found it on the web."
# Prepare the template
Handlebars.registerHelper "ifIsVerified", (verification_status, options) ->
if verification_status == "valid"
return options.fn(this)
options.inverse this
Handlebars.registerHelper "md5", (options) ->
new Handlebars.SafeString(Utilities.MD5(options.fn(this)))
template = JST["src/browser_action/templates/finder.hbs"]
finder_html = $(template(@))
# Generate the DOM with the template and display it
$("#email-finder").html finder_html
$("#email-finder").slideDown 200
# Display: the sources if any
if @sources.length > 0
$(".finder-result-sources").show()
# Display: the tooltips
$("[data-toggle='tooltip']").tooltip()
# Event: the copy action
Utilities.copyEmailListener()
$(".finder-result-pic img").on "load", ->
$(this).css "opacity", "1"
# Display: the button to save the lead
lead_button = $(".finder-result-email .save-lead-button")
lead_button.data
first_name: @first_name
last_name: @last_name
email: @email
confidence_score: @score
lead = new LeadButton
lead.saveButtonListener(lead_button)
lead.disableSaveLeadButtonIfLeadExists(lead_button)
cleanFinderResults: ->
$("#email-finder").html ""
$("#email-finder").hide()
}
|
[
{
"context": "g required dependency: sax-js (https://github.com/isaacs/sax-js)')\n\n\t\t@sax = sax ? root.sax\n\t\t@xml = xml\n\t",
"end": 1469,
"score": 0.9996234178543091,
"start": 1463,
"tag": "USERNAME",
"value": "isaacs"
},
{
"context": ")\n\n\t\t\tif @last.key\n\t\t\t\t@last.node.key = @last.key.valueOf()\n\t\t\t\t@last.key = null\n\n\t\t\tif (node.name == 'dict",
"end": 3195,
"score": 0.9728719592094421,
"start": 3188,
"tag": "KEY",
"value": "valueOf"
},
{
"context": "'\n\t\t\t\tif @last.value\n\t\t\t\t\t@last.key = @last.value.valueOf()\n\t\t\t\t\t@last.value = null\n\t\t\telse if @last.node\n\t",
"end": 3550,
"score": 0.9640461206436157,
"start": 3543,
"tag": "KEY",
"value": "valueOf"
}
] | src/plist-parser.coffee | lasar/plist-parser | 0 | root = exports ? this
class PlistNode
constructor: (type, processors) ->
@type = type
@processors = processors
@key = null
@value = null
@parent = null
@children = []
return @
addChild: (node) ->
node.parent = @
@children.push(node)
return node
getParent: () ->
if @parent
return @parent
return @
convert: () ->
if not @children.length
if @processors? and @processors[@type]?
return @processors[@type](@value)
if @type == 'integer'
return parseInt(@value, 10)
else if @type == 'string'
return @value
else if @type == 'date'
try
return new Date(@value)
catch e
return null
else if @type == 'true'
return true
else if @type == 'false'
return false
else if @type == 'real'
return parseFloat(@value)
else if @type == 'data'
return @value
else if @type == 'dict'
return {}
else if @type == 'array'
return []
else
return @value
else
if @type == 'dict'
iterable = {}
for child in @children
if child.key
iterable[child.key] = child.convert()
else if @type == 'array'
iterable = []
for child in @children
iterable.push(child.convert())
return iterable
class PlistParser
constructor: (xml, opts=null) ->
if exports? and not exports.sax?
try
sax = require('sax')
catch e
if not sax? and not root.sax?
return new Error('Missing required dependency: sax-js (https://github.com/isaacs/sax-js)')
@sax = sax ? root.sax
@xml = xml
@traverser = null
@last = {
'parent': null,
'node': null,
'key': null,
'tag': null,
'value': null
}
@error = null
@opts = {
'processors': {
'integer': opts?.processors?.integer ? null,
'string': opts?.processors?.string ? null,
'date': opts?.processors?.date ? null,
'true': opts?.processors?.true ? null,
'false': opts?.processors?.false ? null,
'real': opts?.processors?.real ? null,
'data': opts?.processors?.data ? null,
'dict': opts?.processors?.dict ? null,
'array': opts?.processors?.array ? null
}
}
return @
validate: ->
parser = @sax.parser(true)
parser.onopentag = (node) ->
if not @first
@first = true
if node.name != 'plist'
@error = new Error('Invalid Property List contents (<plist> missing)')
parser.ondoctype = (doctype) =>
if doctype != ' plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"' ||
doctype != ' plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"'
@error = new Error('Invalid Property List DOCTYPE')
parser.onerror = (error) =>
@error = error
parser.write(@xml).close()
if @error
return false
return true
parse: ->
parser = @sax.parser(true)
parser.onopentag = (node) =>
if (node.name == 'plist')
return
else if (node.name == 'key')
@last.key = null
return
if not @traverser
@traverser = @last.node = new PlistNode(node.name, @opts.processors)
return
@last.node = @traverser.addChild(new PlistNode(node.name, @opts.processors))
if @last.key
@last.node.key = @last.key.valueOf()
@last.key = null
if (node.name == 'dict') or (node.name == 'array')
@traverser = @last.node
parser.ontext = (text) =>
@last.value = text
parser.onclosetag = (name) =>
if (name == 'dict') or (name == 'array')
@traverser = @traverser.getParent()
else if name == 'key'
if @last.value
@last.key = @last.value.valueOf()
@last.value = null
else if @last.node
if @last.value
@last.node.value = @last.value.valueOf()
@last.node = null
parser.write(@xml).close()
return @traverser.convert()
root.PlistParser = PlistParser
root.PlistNode = PlistNode
| 168815 | root = exports ? this
class PlistNode
constructor: (type, processors) ->
@type = type
@processors = processors
@key = null
@value = null
@parent = null
@children = []
return @
addChild: (node) ->
node.parent = @
@children.push(node)
return node
getParent: () ->
if @parent
return @parent
return @
convert: () ->
if not @children.length
if @processors? and @processors[@type]?
return @processors[@type](@value)
if @type == 'integer'
return parseInt(@value, 10)
else if @type == 'string'
return @value
else if @type == 'date'
try
return new Date(@value)
catch e
return null
else if @type == 'true'
return true
else if @type == 'false'
return false
else if @type == 'real'
return parseFloat(@value)
else if @type == 'data'
return @value
else if @type == 'dict'
return {}
else if @type == 'array'
return []
else
return @value
else
if @type == 'dict'
iterable = {}
for child in @children
if child.key
iterable[child.key] = child.convert()
else if @type == 'array'
iterable = []
for child in @children
iterable.push(child.convert())
return iterable
class PlistParser
constructor: (xml, opts=null) ->
if exports? and not exports.sax?
try
sax = require('sax')
catch e
if not sax? and not root.sax?
return new Error('Missing required dependency: sax-js (https://github.com/isaacs/sax-js)')
@sax = sax ? root.sax
@xml = xml
@traverser = null
@last = {
'parent': null,
'node': null,
'key': null,
'tag': null,
'value': null
}
@error = null
@opts = {
'processors': {
'integer': opts?.processors?.integer ? null,
'string': opts?.processors?.string ? null,
'date': opts?.processors?.date ? null,
'true': opts?.processors?.true ? null,
'false': opts?.processors?.false ? null,
'real': opts?.processors?.real ? null,
'data': opts?.processors?.data ? null,
'dict': opts?.processors?.dict ? null,
'array': opts?.processors?.array ? null
}
}
return @
validate: ->
parser = @sax.parser(true)
parser.onopentag = (node) ->
if not @first
@first = true
if node.name != 'plist'
@error = new Error('Invalid Property List contents (<plist> missing)')
parser.ondoctype = (doctype) =>
if doctype != ' plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"' ||
doctype != ' plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"'
@error = new Error('Invalid Property List DOCTYPE')
parser.onerror = (error) =>
@error = error
parser.write(@xml).close()
if @error
return false
return true
parse: ->
parser = @sax.parser(true)
parser.onopentag = (node) =>
if (node.name == 'plist')
return
else if (node.name == 'key')
@last.key = null
return
if not @traverser
@traverser = @last.node = new PlistNode(node.name, @opts.processors)
return
@last.node = @traverser.addChild(new PlistNode(node.name, @opts.processors))
if @last.key
@last.node.key = @last.key.<KEY>()
@last.key = null
if (node.name == 'dict') or (node.name == 'array')
@traverser = @last.node
parser.ontext = (text) =>
@last.value = text
parser.onclosetag = (name) =>
if (name == 'dict') or (name == 'array')
@traverser = @traverser.getParent()
else if name == 'key'
if @last.value
@last.key = @last.value.<KEY>()
@last.value = null
else if @last.node
if @last.value
@last.node.value = @last.value.valueOf()
@last.node = null
parser.write(@xml).close()
return @traverser.convert()
root.PlistParser = PlistParser
root.PlistNode = PlistNode
| true | root = exports ? this
class PlistNode
constructor: (type, processors) ->
@type = type
@processors = processors
@key = null
@value = null
@parent = null
@children = []
return @
addChild: (node) ->
node.parent = @
@children.push(node)
return node
getParent: () ->
if @parent
return @parent
return @
convert: () ->
if not @children.length
if @processors? and @processors[@type]?
return @processors[@type](@value)
if @type == 'integer'
return parseInt(@value, 10)
else if @type == 'string'
return @value
else if @type == 'date'
try
return new Date(@value)
catch e
return null
else if @type == 'true'
return true
else if @type == 'false'
return false
else if @type == 'real'
return parseFloat(@value)
else if @type == 'data'
return @value
else if @type == 'dict'
return {}
else if @type == 'array'
return []
else
return @value
else
if @type == 'dict'
iterable = {}
for child in @children
if child.key
iterable[child.key] = child.convert()
else if @type == 'array'
iterable = []
for child in @children
iterable.push(child.convert())
return iterable
class PlistParser
constructor: (xml, opts=null) ->
if exports? and not exports.sax?
try
sax = require('sax')
catch e
if not sax? and not root.sax?
return new Error('Missing required dependency: sax-js (https://github.com/isaacs/sax-js)')
@sax = sax ? root.sax
@xml = xml
@traverser = null
@last = {
'parent': null,
'node': null,
'key': null,
'tag': null,
'value': null
}
@error = null
@opts = {
'processors': {
'integer': opts?.processors?.integer ? null,
'string': opts?.processors?.string ? null,
'date': opts?.processors?.date ? null,
'true': opts?.processors?.true ? null,
'false': opts?.processors?.false ? null,
'real': opts?.processors?.real ? null,
'data': opts?.processors?.data ? null,
'dict': opts?.processors?.dict ? null,
'array': opts?.processors?.array ? null
}
}
return @
validate: ->
parser = @sax.parser(true)
parser.onopentag = (node) ->
if not @first
@first = true
if node.name != 'plist'
@error = new Error('Invalid Property List contents (<plist> missing)')
parser.ondoctype = (doctype) =>
if doctype != ' plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"' ||
doctype != ' plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"'
@error = new Error('Invalid Property List DOCTYPE')
parser.onerror = (error) =>
@error = error
parser.write(@xml).close()
if @error
return false
return true
parse: ->
parser = @sax.parser(true)
parser.onopentag = (node) =>
if (node.name == 'plist')
return
else if (node.name == 'key')
@last.key = null
return
if not @traverser
@traverser = @last.node = new PlistNode(node.name, @opts.processors)
return
@last.node = @traverser.addChild(new PlistNode(node.name, @opts.processors))
if @last.key
@last.node.key = @last.key.PI:KEY:<KEY>END_PI()
@last.key = null
if (node.name == 'dict') or (node.name == 'array')
@traverser = @last.node
parser.ontext = (text) =>
@last.value = text
parser.onclosetag = (name) =>
if (name == 'dict') or (name == 'array')
@traverser = @traverser.getParent()
else if name == 'key'
if @last.value
@last.key = @last.value.PI:KEY:<KEY>END_PI()
@last.value = null
else if @last.node
if @last.value
@last.node.value = @last.value.valueOf()
@last.node = null
parser.write(@xml).close()
return @traverser.convert()
root.PlistParser = PlistParser
root.PlistNode = PlistNode
|
[
{
"context": " @file Defines the API for MD Underline\n * @author Derek Gransaull <derek@dgtlife.com>\n * @copyright DGTLife, LLC 20",
"end": 72,
"score": 0.9998725652694702,
"start": 57,
"tag": "NAME",
"value": "Derek Gransaull"
},
{
"context": " API for MD Underline\n * @author Derek Gransaull <derek@dgtlife.com>\n * @copyright DGTLife, LLC 2016\n###\neqS = requir",
"end": 91,
"score": 0.9999347925186157,
"start": 74,
"tag": "EMAIL",
"value": "derek@dgtlife.com"
}
] | client/imports/api/md-underline-api.coffee | dgtlife/material-for-meteor | 12 | ###
* @file Defines the API for MD Underline
* @author Derek Gransaull <derek@dgtlife.com>
* @copyright DGTLife, LLC 2016
###
eqS = require('./md-utils.js').eqS
###*
# Set the style of the underline in a text field when the associated input has
# focus.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineFocused = (field) ->
eqS(field, '[data-underline]').classList.add 'focused'
eqS(field, '[data-underline--modified]').classList.add 'focused'
###*
# Set the style of the underline in a text field when the associated input has
# lost focus.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineUnfocused = (field) ->
eqS(field, '[data-underline]').classList.remove 'focused'
eqS(field, '[data-underline--modified]').classList.remove 'focused'
###*
# Set the style of the underline in a text field when the associated input is
# in error.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineErrored = (field) ->
eqS(field, '[data-underline]').classList.add 'errored'
eqS(field, '[data-underline--modified]').classList.add 'errored'
###*
# Set the style of the underline in a text field when the associated input is
# valid.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineValid = (field) ->
eqS(field, '[data-underline]').classList.remove 'errored'
eqS(field, '[data-underline--modified]').classList.remove 'errored'
| 42138 | ###
* @file Defines the API for MD Underline
* @author <NAME> <<EMAIL>>
* @copyright DGTLife, LLC 2016
###
eqS = require('./md-utils.js').eqS
###*
# Set the style of the underline in a text field when the associated input has
# focus.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineFocused = (field) ->
eqS(field, '[data-underline]').classList.add 'focused'
eqS(field, '[data-underline--modified]').classList.add 'focused'
###*
# Set the style of the underline in a text field when the associated input has
# lost focus.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineUnfocused = (field) ->
eqS(field, '[data-underline]').classList.remove 'focused'
eqS(field, '[data-underline--modified]').classList.remove 'focused'
###*
# Set the style of the underline in a text field when the associated input is
# in error.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineErrored = (field) ->
eqS(field, '[data-underline]').classList.add 'errored'
eqS(field, '[data-underline--modified]').classList.add 'errored'
###*
# Set the style of the underline in a text field when the associated input is
# valid.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineValid = (field) ->
eqS(field, '[data-underline]').classList.remove 'errored'
eqS(field, '[data-underline--modified]').classList.remove 'errored'
| true | ###
* @file Defines the API for MD Underline
* @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* @copyright DGTLife, LLC 2016
###
eqS = require('./md-utils.js').eqS
###*
# Set the style of the underline in a text field when the associated input has
# focus.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineFocused = (field) ->
eqS(field, '[data-underline]').classList.add 'focused'
eqS(field, '[data-underline--modified]').classList.add 'focused'
###*
# Set the style of the underline in a text field when the associated input has
# lost focus.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineUnfocused = (field) ->
eqS(field, '[data-underline]').classList.remove 'focused'
eqS(field, '[data-underline--modified]').classList.remove 'focused'
###*
# Set the style of the underline in a text field when the associated input is
# in error.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineErrored = (field) ->
eqS(field, '[data-underline]').classList.add 'errored'
eqS(field, '[data-underline--modified]').classList.add 'errored'
###*
# Set the style of the underline in a text field when the associated input is
# valid.
# @param {Element} field - the text field (.md-field) element that contains
# the underline
###
module.exports.setStyleOfUnderlineValid = (field) ->
eqS(field, '[data-underline]').classList.remove 'errored'
eqS(field, '[data-underline--modified]').classList.remove 'errored'
|
[
{
"context": "#Copyright 2014 - 2015\n#Author: Varuna Jayasiri http://blog.varunajayasiri.com\n\nFS = require 'fs'",
"end": 47,
"score": 0.9998885989189148,
"start": 32,
"tag": "NAME",
"value": "Varuna Jayasiri"
}
] | build-script/fs_util.coffee | chethiya/wallapatta | 86 | #Copyright 2014 - 2015
#Author: Varuna Jayasiri http://blog.varunajayasiri.com
FS = require 'fs'
PATH = require 'path'
rm_r = (path) ->
try
stat = FS.lstatSync path
catch e
return false
if stat.isDirectory()
files = FS.readdirSync path
for file in files
rm_r PATH.join path, file
FS.rmdirSync path
else
FS.unlinkSync path
_mkdir_p = (parts) ->
base = '/'
create = []
for segment in parts
base = PATH.join base, segment
if not FS.existsSync base
create.push base
for path in create
console.log path
FS.mkdirSync path
mkdir_p = (path) -> _mkdir_p (PATH.normalize path).split PATH.sep
cp = (src, dst) ->
BLOCK_SIZE = 4096
buf = new Buffer BLOCK_SIZE
fdSrc = FS.openSync src, 'r'
fdDst = FS.openSync dst, 'w'
offset = 0
remain = (FS.statSync src).size
while remain > 0
readSize = Math.min remain, BLOCK_SIZE
FS.readSync fdSrc, buf, 0, readSize, offset
FS.writeSync fdDst, buf, 0, readSize, offset
remain -= readSize
offset += readSize
FS.closeSync fdSrc
FS.closeSync fdDst
cp_r = (src, dst) ->
stat = FS.statSync src
if stat.isDirectory()
if not FS.existsSync dst
FS.mkdirSync dst
files = FS.readdirSync src
for file in files
cp_r (PATH.join src, file), (PATH.join dst, file)
else
cp src, dst
chown_r = (path, uid, gid) ->
stat = FS.statSync src
if stat.isDirectory()
files = FS.readdirSync src
for file in files
chown_r (PATH.join path, file), uid, gid
FS.chownSync path, uid, gid
module.exports =
rm_r: rm_r
cp: cp
cp_r: cp_r
mkdir: FS.mkdirSync
mv: FS.renameSync
exists: FS.existsSync
| 205253 | #Copyright 2014 - 2015
#Author: <NAME> http://blog.varunajayasiri.com
FS = require 'fs'
PATH = require 'path'
rm_r = (path) ->
try
stat = FS.lstatSync path
catch e
return false
if stat.isDirectory()
files = FS.readdirSync path
for file in files
rm_r PATH.join path, file
FS.rmdirSync path
else
FS.unlinkSync path
_mkdir_p = (parts) ->
base = '/'
create = []
for segment in parts
base = PATH.join base, segment
if not FS.existsSync base
create.push base
for path in create
console.log path
FS.mkdirSync path
mkdir_p = (path) -> _mkdir_p (PATH.normalize path).split PATH.sep
cp = (src, dst) ->
BLOCK_SIZE = 4096
buf = new Buffer BLOCK_SIZE
fdSrc = FS.openSync src, 'r'
fdDst = FS.openSync dst, 'w'
offset = 0
remain = (FS.statSync src).size
while remain > 0
readSize = Math.min remain, BLOCK_SIZE
FS.readSync fdSrc, buf, 0, readSize, offset
FS.writeSync fdDst, buf, 0, readSize, offset
remain -= readSize
offset += readSize
FS.closeSync fdSrc
FS.closeSync fdDst
cp_r = (src, dst) ->
stat = FS.statSync src
if stat.isDirectory()
if not FS.existsSync dst
FS.mkdirSync dst
files = FS.readdirSync src
for file in files
cp_r (PATH.join src, file), (PATH.join dst, file)
else
cp src, dst
chown_r = (path, uid, gid) ->
stat = FS.statSync src
if stat.isDirectory()
files = FS.readdirSync src
for file in files
chown_r (PATH.join path, file), uid, gid
FS.chownSync path, uid, gid
module.exports =
rm_r: rm_r
cp: cp
cp_r: cp_r
mkdir: FS.mkdirSync
mv: FS.renameSync
exists: FS.existsSync
| true | #Copyright 2014 - 2015
#Author: PI:NAME:<NAME>END_PI http://blog.varunajayasiri.com
FS = require 'fs'
PATH = require 'path'
rm_r = (path) ->
try
stat = FS.lstatSync path
catch e
return false
if stat.isDirectory()
files = FS.readdirSync path
for file in files
rm_r PATH.join path, file
FS.rmdirSync path
else
FS.unlinkSync path
_mkdir_p = (parts) ->
base = '/'
create = []
for segment in parts
base = PATH.join base, segment
if not FS.existsSync base
create.push base
for path in create
console.log path
FS.mkdirSync path
mkdir_p = (path) -> _mkdir_p (PATH.normalize path).split PATH.sep
cp = (src, dst) ->
BLOCK_SIZE = 4096
buf = new Buffer BLOCK_SIZE
fdSrc = FS.openSync src, 'r'
fdDst = FS.openSync dst, 'w'
offset = 0
remain = (FS.statSync src).size
while remain > 0
readSize = Math.min remain, BLOCK_SIZE
FS.readSync fdSrc, buf, 0, readSize, offset
FS.writeSync fdDst, buf, 0, readSize, offset
remain -= readSize
offset += readSize
FS.closeSync fdSrc
FS.closeSync fdDst
cp_r = (src, dst) ->
stat = FS.statSync src
if stat.isDirectory()
if not FS.existsSync dst
FS.mkdirSync dst
files = FS.readdirSync src
for file in files
cp_r (PATH.join src, file), (PATH.join dst, file)
else
cp src, dst
chown_r = (path, uid, gid) ->
stat = FS.statSync src
if stat.isDirectory()
files = FS.readdirSync src
for file in files
chown_r (PATH.join path, file), uid, gid
FS.chownSync path, uid, gid
module.exports =
rm_r: rm_r
cp: cp
cp_r: cp_r
mkdir: FS.mkdirSync
mv: FS.renameSync
exists: FS.existsSync
|
[
{
"context": "tes if he's currently taking notes\n#\n# Author:\n# benjamin eidelman\n\nenv = process.env\nfs = require('fs')\n\nmodule.exp",
"end": 713,
"score": 0.999853789806366,
"start": 696,
"tag": "NAME",
"value": "benjamin eidelman"
},
{
"context": " notes[name] ?= {}\n key = keyValue[1].toLowerCase()\n if (key in messageKeys)\n notes",
"end": 1778,
"score": 0.9365520477294922,
"start": 1767,
"tag": "KEY",
"value": "toLowerCase"
},
{
"context": "own user, userNotes of notes\n if user != '_raw'\n response.push(user, ':\\n')\n f",
"end": 2874,
"score": 0.8363355398178101,
"start": 2871,
"tag": "USERNAME",
"value": "raw"
}
] | src/scripts/scrumnotes.coffee | Reelhouse/hubot-scripts | 1,450 | # Description:
# Take notes on scrum daily meetings
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_SCRUMNOTES_PATH - if set, folder where daily notes should be saved as json files (otherwise they just stay on robot brain)
#
# Commands:
# hubot take scrum notes - Starts taking notes from all users in the room (records all messages starting with yesterday, today, tomorrow, sun, mon, tue, wed, thu, fri, sat, blocking)
# hubot stop taking notes - Stops taking scrum notes (if a path is configured saves day notes to a json file)
# hubot scrum notes - shows scrum notes taken so far
# hubot are you taking notes? - hubot indicates if he's currently taking notes
#
# Author:
# benjamin eidelman
env = process.env
fs = require('fs')
module.exports = (robot) ->
# rooms where hubot is hearing for notes
hearingRooms = {}
messageKeys = ['blocking', 'blocker', 'yesterday', 'today', 'tomorrow', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
getDate = ->
today = new Date()
dd = today.getDate()
mm = today.getMonth()+1
yyyy = today.getFullYear()
if (dd<10)
dd='0'+dd
if (mm<10)
mm='0'+mm
return yyyy+'-'+mm+'-'+dd
listener = null
startHearing = ->
if (listener)
return
listenersCount = robot.catchAll (msg) ->
if (!hearingRooms[msg.message.user.room])
return
today = getDate()
name = msg.message.user.name
robot.brain.data.scrumNotes ?= {};
notes = robot.brain.data.scrumNotes[today] ?= {}
notes._raw ?= [];
notes._raw.push([new Date().getTime(), name, msg.message.text])
keyValue = /^([^ :\n\r\t]+)[ :\n\t](.+)$/m.exec(msg.message.text)
if (keyValue)
notes[name] ?= {}
key = keyValue[1].toLowerCase()
if (key in messageKeys)
notes[name][key] ?= [];
notes[name][key].push(keyValue[2])
listener = robot.listeners[listenersCount - 1]
stopHearing = ->
if (!listener)
return
listenerIndex = -1
for list, i in robot.listeners
if list is listener
listenerIndex = i
break
if (listenerIndex >= 0)
setTimeout ->
robot.listeners.splice(i, 1)
, 0
listener = null
mkdir = (path, root) ->
dirs = path.split('/')
dir = dirs.shift()
root = (root||'')+dir+'/'
try
fs.mkdirSync(root)
catch e
# dir wasn't made, something went wrong
if (!fs.statSync(root).isDirectory())
throw new Error(e)
return !dirs.length || mkdir(dirs.join('/'), root)
robot.respond /(?:show )?scrum notes/i, (msg) ->
today = getDate()
notes = robot.brain.data.scrumNotes?[today]
if !notes
msg.reply('no notes so far')
else
# build a pretty version
response = []
for own user, userNotes of notes
if user != '_raw'
response.push(user, ':\n')
for key in messageKeys
if userNotes[key]
response.push(' ', key, ': ', userNotes[key].join(', '), '\n')
msg.reply(response.join(''))
robot.respond /take scrum notes/i, (msg) ->
startHearing()
hearingRooms[msg.message.user.room] = true
msg.reply('taking scrum notes, I hear you');
robot.respond /are you taking (scrum )?notes\?/i, (msg) ->
takingNotes = !!hearingRooms[msg.message.user.room]
msg.reply(if takingNotes then 'Yes, I\'m taking scrum notes' else 'No, I\'m not taking scrum notes')
robot.respond /stop taking (?:scrum )?notes/i, (msg) ->
delete hearingRooms[msg.message.user.room];
msg.reply("not taking scrum notes anymore");
today = getDate()
notes = robot.brain.data.scrumNotes?[today]
users = (user for user in Object.keys(notes) when user isnt '_raw')
count = if notes then users.length else 0
status = "I got no notes today"
if count > 0
status = ["I got notes from ", users.slice(0,Math.min(3, users.length - 1)).join(', '), " and ", if users.length > 3 then (users.length-3)+' more' else users[users.length-1]].join('')
msg.reply(status);
if (Object.keys(hearingRooms).length < 1)
stopHearing()
saveTo = process.env.HUBOT_SCRUMNOTES_PATH
if (saveTo)
mkdir(saveTo + '/scrumnotes')
fs.writeFileSync(saveTo + '/scrumnotes/' + today + '.json', JSON.stringify(notes, null, 2))
msg.send('scrum notes saved at: /scrumnotes/' + today + '.json')
| 151840 | # Description:
# Take notes on scrum daily meetings
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_SCRUMNOTES_PATH - if set, folder where daily notes should be saved as json files (otherwise they just stay on robot brain)
#
# Commands:
# hubot take scrum notes - Starts taking notes from all users in the room (records all messages starting with yesterday, today, tomorrow, sun, mon, tue, wed, thu, fri, sat, blocking)
# hubot stop taking notes - Stops taking scrum notes (if a path is configured saves day notes to a json file)
# hubot scrum notes - shows scrum notes taken so far
# hubot are you taking notes? - hubot indicates if he's currently taking notes
#
# Author:
# <NAME>
env = process.env
fs = require('fs')
module.exports = (robot) ->
# rooms where hubot is hearing for notes
hearingRooms = {}
messageKeys = ['blocking', 'blocker', 'yesterday', 'today', 'tomorrow', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
getDate = ->
today = new Date()
dd = today.getDate()
mm = today.getMonth()+1
yyyy = today.getFullYear()
if (dd<10)
dd='0'+dd
if (mm<10)
mm='0'+mm
return yyyy+'-'+mm+'-'+dd
listener = null
startHearing = ->
if (listener)
return
listenersCount = robot.catchAll (msg) ->
if (!hearingRooms[msg.message.user.room])
return
today = getDate()
name = msg.message.user.name
robot.brain.data.scrumNotes ?= {};
notes = robot.brain.data.scrumNotes[today] ?= {}
notes._raw ?= [];
notes._raw.push([new Date().getTime(), name, msg.message.text])
keyValue = /^([^ :\n\r\t]+)[ :\n\t](.+)$/m.exec(msg.message.text)
if (keyValue)
notes[name] ?= {}
key = keyValue[1].<KEY>()
if (key in messageKeys)
notes[name][key] ?= [];
notes[name][key].push(keyValue[2])
listener = robot.listeners[listenersCount - 1]
stopHearing = ->
if (!listener)
return
listenerIndex = -1
for list, i in robot.listeners
if list is listener
listenerIndex = i
break
if (listenerIndex >= 0)
setTimeout ->
robot.listeners.splice(i, 1)
, 0
listener = null
mkdir = (path, root) ->
dirs = path.split('/')
dir = dirs.shift()
root = (root||'')+dir+'/'
try
fs.mkdirSync(root)
catch e
# dir wasn't made, something went wrong
if (!fs.statSync(root).isDirectory())
throw new Error(e)
return !dirs.length || mkdir(dirs.join('/'), root)
robot.respond /(?:show )?scrum notes/i, (msg) ->
today = getDate()
notes = robot.brain.data.scrumNotes?[today]
if !notes
msg.reply('no notes so far')
else
# build a pretty version
response = []
for own user, userNotes of notes
if user != '_raw'
response.push(user, ':\n')
for key in messageKeys
if userNotes[key]
response.push(' ', key, ': ', userNotes[key].join(', '), '\n')
msg.reply(response.join(''))
robot.respond /take scrum notes/i, (msg) ->
startHearing()
hearingRooms[msg.message.user.room] = true
msg.reply('taking scrum notes, I hear you');
robot.respond /are you taking (scrum )?notes\?/i, (msg) ->
takingNotes = !!hearingRooms[msg.message.user.room]
msg.reply(if takingNotes then 'Yes, I\'m taking scrum notes' else 'No, I\'m not taking scrum notes')
robot.respond /stop taking (?:scrum )?notes/i, (msg) ->
delete hearingRooms[msg.message.user.room];
msg.reply("not taking scrum notes anymore");
today = getDate()
notes = robot.brain.data.scrumNotes?[today]
users = (user for user in Object.keys(notes) when user isnt '_raw')
count = if notes then users.length else 0
status = "I got no notes today"
if count > 0
status = ["I got notes from ", users.slice(0,Math.min(3, users.length - 1)).join(', '), " and ", if users.length > 3 then (users.length-3)+' more' else users[users.length-1]].join('')
msg.reply(status);
if (Object.keys(hearingRooms).length < 1)
stopHearing()
saveTo = process.env.HUBOT_SCRUMNOTES_PATH
if (saveTo)
mkdir(saveTo + '/scrumnotes')
fs.writeFileSync(saveTo + '/scrumnotes/' + today + '.json', JSON.stringify(notes, null, 2))
msg.send('scrum notes saved at: /scrumnotes/' + today + '.json')
| true | # Description:
# Take notes on scrum daily meetings
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_SCRUMNOTES_PATH - if set, folder where daily notes should be saved as json files (otherwise they just stay on robot brain)
#
# Commands:
# hubot take scrum notes - Starts taking notes from all users in the room (records all messages starting with yesterday, today, tomorrow, sun, mon, tue, wed, thu, fri, sat, blocking)
# hubot stop taking notes - Stops taking scrum notes (if a path is configured saves day notes to a json file)
# hubot scrum notes - shows scrum notes taken so far
# hubot are you taking notes? - hubot indicates if he's currently taking notes
#
# Author:
# PI:NAME:<NAME>END_PI
env = process.env
fs = require('fs')
module.exports = (robot) ->
# rooms where hubot is hearing for notes
hearingRooms = {}
messageKeys = ['blocking', 'blocker', 'yesterday', 'today', 'tomorrow', 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
getDate = ->
today = new Date()
dd = today.getDate()
mm = today.getMonth()+1
yyyy = today.getFullYear()
if (dd<10)
dd='0'+dd
if (mm<10)
mm='0'+mm
return yyyy+'-'+mm+'-'+dd
listener = null
startHearing = ->
if (listener)
return
listenersCount = robot.catchAll (msg) ->
if (!hearingRooms[msg.message.user.room])
return
today = getDate()
name = msg.message.user.name
robot.brain.data.scrumNotes ?= {};
notes = robot.brain.data.scrumNotes[today] ?= {}
notes._raw ?= [];
notes._raw.push([new Date().getTime(), name, msg.message.text])
keyValue = /^([^ :\n\r\t]+)[ :\n\t](.+)$/m.exec(msg.message.text)
if (keyValue)
notes[name] ?= {}
key = keyValue[1].PI:KEY:<KEY>END_PI()
if (key in messageKeys)
notes[name][key] ?= [];
notes[name][key].push(keyValue[2])
listener = robot.listeners[listenersCount - 1]
stopHearing = ->
if (!listener)
return
listenerIndex = -1
for list, i in robot.listeners
if list is listener
listenerIndex = i
break
if (listenerIndex >= 0)
setTimeout ->
robot.listeners.splice(i, 1)
, 0
listener = null
mkdir = (path, root) ->
dirs = path.split('/')
dir = dirs.shift()
root = (root||'')+dir+'/'
try
fs.mkdirSync(root)
catch e
# dir wasn't made, something went wrong
if (!fs.statSync(root).isDirectory())
throw new Error(e)
return !dirs.length || mkdir(dirs.join('/'), root)
robot.respond /(?:show )?scrum notes/i, (msg) ->
today = getDate()
notes = robot.brain.data.scrumNotes?[today]
if !notes
msg.reply('no notes so far')
else
# build a pretty version
response = []
for own user, userNotes of notes
if user != '_raw'
response.push(user, ':\n')
for key in messageKeys
if userNotes[key]
response.push(' ', key, ': ', userNotes[key].join(', '), '\n')
msg.reply(response.join(''))
robot.respond /take scrum notes/i, (msg) ->
startHearing()
hearingRooms[msg.message.user.room] = true
msg.reply('taking scrum notes, I hear you');
robot.respond /are you taking (scrum )?notes\?/i, (msg) ->
takingNotes = !!hearingRooms[msg.message.user.room]
msg.reply(if takingNotes then 'Yes, I\'m taking scrum notes' else 'No, I\'m not taking scrum notes')
robot.respond /stop taking (?:scrum )?notes/i, (msg) ->
delete hearingRooms[msg.message.user.room];
msg.reply("not taking scrum notes anymore");
today = getDate()
notes = robot.brain.data.scrumNotes?[today]
users = (user for user in Object.keys(notes) when user isnt '_raw')
count = if notes then users.length else 0
status = "I got no notes today"
if count > 0
status = ["I got notes from ", users.slice(0,Math.min(3, users.length - 1)).join(', '), " and ", if users.length > 3 then (users.length-3)+' more' else users[users.length-1]].join('')
msg.reply(status);
if (Object.keys(hearingRooms).length < 1)
stopHearing()
saveTo = process.env.HUBOT_SCRUMNOTES_PATH
if (saveTo)
mkdir(saveTo + '/scrumnotes')
fs.writeFileSync(saveTo + '/scrumnotes/' + today + '.json', JSON.stringify(notes, null, 2))
msg.send('scrum notes saved at: /scrumnotes/' + today + '.json')
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9985228180885315,
"start": 12,
"tag": "NAME",
"value": "Joyent"
},
{
"context": "+ rinfo.port\n assert.strictEqual rinfo.address, \"127.0.0.1\"\n assert.strictEqual msg.toString(), message_to_",
"end": 1528,
"score": 0.9997333884239197,
"start": 1519,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "dress.port\n assert.strictEqual rinfo.address, \"127.0.0.1\"\n assert.strictEqual rinfo.port, server_port\n ",
"end": 2008,
"score": 0.9995527267456055,
"start": 1999,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | test/simple/test-dgram-udp4.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")
dgram = require("dgram")
server = undefined
client = undefined
server_port = 20989
message_to_send = "A message to send"
timer = undefined
server = dgram.createSocket("udp4")
server.on "message", (msg, rinfo) ->
console.log "server got: " + msg + " from " + rinfo.address + ":" + rinfo.port
assert.strictEqual rinfo.address, "127.0.0.1"
assert.strictEqual msg.toString(), message_to_send.toString()
server.send msg, 0, msg.length, rinfo.port, rinfo.address
return
server.on "listening", ->
address = server.address()
console.log "server is listening on " + address.address + ":" + address.port
client = dgram.createSocket("udp4")
client.on "message", (msg, rinfo) ->
console.log "client got: " + msg + " from " + rinfo.address + ":" + address.port
assert.strictEqual rinfo.address, "127.0.0.1"
assert.strictEqual rinfo.port, server_port
assert.strictEqual msg.toString(), message_to_send.toString()
client.close()
server.close()
return
client.send message_to_send, 0, message_to_send.length, server_port, "localhost", (err) ->
if err
console.log "Caught error in client send."
throw err
return
client.on "close", ->
clearTimeout timer if server.fd is null
return
return
server.on "close", ->
clearTimeout timer if client.fd is null
return
server.bind server_port
timer = setTimeout(->
throw new Error("Timeout")return
, 200)
| 146567 | # 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")
dgram = require("dgram")
server = undefined
client = undefined
server_port = 20989
message_to_send = "A message to send"
timer = undefined
server = dgram.createSocket("udp4")
server.on "message", (msg, rinfo) ->
console.log "server got: " + msg + " from " + rinfo.address + ":" + rinfo.port
assert.strictEqual rinfo.address, "127.0.0.1"
assert.strictEqual msg.toString(), message_to_send.toString()
server.send msg, 0, msg.length, rinfo.port, rinfo.address
return
server.on "listening", ->
address = server.address()
console.log "server is listening on " + address.address + ":" + address.port
client = dgram.createSocket("udp4")
client.on "message", (msg, rinfo) ->
console.log "client got: " + msg + " from " + rinfo.address + ":" + address.port
assert.strictEqual rinfo.address, "127.0.0.1"
assert.strictEqual rinfo.port, server_port
assert.strictEqual msg.toString(), message_to_send.toString()
client.close()
server.close()
return
client.send message_to_send, 0, message_to_send.length, server_port, "localhost", (err) ->
if err
console.log "Caught error in client send."
throw err
return
client.on "close", ->
clearTimeout timer if server.fd is null
return
return
server.on "close", ->
clearTimeout timer if client.fd is null
return
server.bind server_port
timer = setTimeout(->
throw new Error("Timeout")return
, 200)
| 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")
dgram = require("dgram")
server = undefined
client = undefined
server_port = 20989
message_to_send = "A message to send"
timer = undefined
server = dgram.createSocket("udp4")
server.on "message", (msg, rinfo) ->
console.log "server got: " + msg + " from " + rinfo.address + ":" + rinfo.port
assert.strictEqual rinfo.address, "127.0.0.1"
assert.strictEqual msg.toString(), message_to_send.toString()
server.send msg, 0, msg.length, rinfo.port, rinfo.address
return
server.on "listening", ->
address = server.address()
console.log "server is listening on " + address.address + ":" + address.port
client = dgram.createSocket("udp4")
client.on "message", (msg, rinfo) ->
console.log "client got: " + msg + " from " + rinfo.address + ":" + address.port
assert.strictEqual rinfo.address, "127.0.0.1"
assert.strictEqual rinfo.port, server_port
assert.strictEqual msg.toString(), message_to_send.toString()
client.close()
server.close()
return
client.send message_to_send, 0, message_to_send.length, server_port, "localhost", (err) ->
if err
console.log "Caught error in client send."
throw err
return
client.on "close", ->
clearTimeout timer if server.fd is null
return
return
server.on "close", ->
clearTimeout timer if client.fd is null
return
server.bind server_port
timer = setTimeout(->
throw new Error("Timeout")return
, 200)
|
[
{
"context": "#################\n# Copyright (C) 2014-2016 by Vaughn Iverson\n# job-collection is free software released un",
"end": 124,
"score": 0.9997904896736145,
"start": 110,
"tag": "NAME",
"value": "Vaughn Iverson"
}
] | test/job_collection_tests.coffee | peerlibrary/meteor-job-collection | 1 | ############################################################################
# Copyright (C) 2014-2016 by Vaughn Iverson
# job-collection is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
bind_env = (func) ->
if Meteor.isServer and typeof func is 'function'
return Meteor.bindEnvironment func, (err) -> throw err
else
return func
subWrapper = (sub, func) ->
(test, onComplete) ->
if Meteor.isClient
Deps.autorun () ->
if sub.ready()
func test, onComplete
else
func test, onComplete
validId = (v) ->
Match.test(v, Match.OneOf(String, Meteor.Collection.ObjectID))
defaultColl = new JobCollection()
validJobDoc = (d) ->
Match.test(d, defaultColl.jobDocPattern)
Tinytest.add 'JobCollection default constructor', (test) ->
test.instanceOf defaultColl, JobCollection, "JobCollection constructor failed"
test.equal defaultColl.root, 'queue', "default root isn't 'queue'"
if Meteor.isServer
test.equal defaultColl.stopped, true, "isn't initially stopped"
test.equal defaultColl.logStream, null, "Doesn't have a logStream"
test.instanceOf defaultColl.allows, Object, "allows isn't an object"
test.equal Object.keys(defaultColl.allows).length, 22, "allows not properly initialized"
test.instanceOf defaultColl.denys, Object, "denys isn't an object"
test.equal Object.keys(defaultColl.denys).length, 22, "denys not properly initialized"
else
test.equal defaultColl.logConsole, false, "Doesn't have a logConsole"
clientTestColl = new JobCollection 'ClientTest', { idGeneration: 'MONGO' }
serverTestColl = new JobCollection 'ServerTest', { idGeneration: 'STRING' }
# The line below is a regression test for issue #51
dummyTestColl = new JobCollection 'DummyTest', { idGeneration: 'STRING' }
if Meteor.isServer
remoteTestColl = new JobCollection 'RemoteTest', { idGeneration: 'STRING' }
remoteTestColl.allow
admin: () -> true
else
remoteConnection = DDP.connect Meteor.absoluteUrl()
remoteServerTestColl = new JobCollection 'RemoteTest', { idGeneration: 'STRING', connection: remoteConnection }
testColl = null # This will be defined differently for client / server
if Meteor.isServer
clientTestColl.allow
admin: () -> true
Tinytest.add 'Set permissions to allow admin on ClientTest', (test) ->
test.equal clientTestColl.allows.admin[0](), true
Tinytest.add 'Set polling interval', (test) ->
interval = clientTestColl.interval
clientTestColl.promote 250
test.notEqual interval, clientTestColl.interval, "clientTestColl interval not updated"
interval = serverTestColl.interval
serverTestColl.promote 250
test.notEqual interval, serverTestColl.interval, "serverTestColl interval not updated"
testColl = if Meteor.isClient then clientTestColl else serverTestColl
# Tinytest.addAsync 'Run startJobs on new job collection', (test, onComplete) ->
# testColl.startJobs (err, res) ->
# test.fail(err) if err
# test.equal res, true, "startJobs failed in callback result"
# if Meteor.isServer
# test.equal testColl.stopped, false, "startJobs didn't start job collection"
# onComplete()
Tinytest.addAsync 'Run startJobServer on new job collection', (test, onComplete) ->
testColl.startJobServer (err, res) ->
test.fail(err) if err
test.equal res, true, "startJobServer failed in callback result"
if Meteor.isServer
test.equal testColl.stopped, false, "startJobServer didn't start job collection"
onComplete()
if Meteor.isServer
Tinytest.addAsync 'Create a server-side job and see that it is added to the collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
res = job.save()
test.ok validId(res), "job.save() failed in sync result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
ev = testColl.events.once 'jobDone', (msg) ->
test.equal msg.method, 'jobDone'
if msg.params[0] is res
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Create a job and see that it is added to the collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Create an invalid job and see that errors correctly propagate', (test, onComplete) ->
console.warn "****************************************************************************************************"
console.warn "***** The following exception dump is a Normal and Expected part of error handling unit tests: *****"
console.warn "****************************************************************************************************"
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
delete job.doc.status
test.equal validJobDoc(job.doc), false
if Meteor.isServer
eventFlag = false
err = null
ev = testColl.events.once 'jobSave', (msg) ->
eventFlag = true
test.fail(new Error "Server error event didn't dispatch") unless msg.error
try
job.save()
catch e
err = e
finally
test.ok eventFlag
test.fail(new Error "Server exception wasn't thrown") unless err
onComplete()
else
job.save (err, res) ->
test.fail(new Error "Error did not propagate to Client") unless err
onComplete()
Tinytest.addAsync 'Create a job and then make a new doc with its document', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job2 = new Job testColl, jobType, { some: 'data' }
if Meteor.isServer
job = new Job 'ServerTest', job2.doc
else
job = new Job 'ClientTest', job2.doc
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A repeating job that returns the _id of the next job', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).repeat({ repeats: 1, wait: 250 })
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
if counter is 1
test.equal job.doc._id, res
job.done "Result1", { repeatId: true }, (err, res) ->
test.fail(err) if err
test.ok res?
test.notEqual res, true
testColl.getJob res, (err, j) ->
test.fail(err) if err
test.equal j._doc._id, res
cb()
else
test.notEqual job.doc._id, res
job.done "Result2", { repeatId: true }, (err, res) ->
test.fail(err) if err
test.equal res, true
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Dependent jobs run in the correct order', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { order: 1 }
job2 = new Job testColl, jobType, { order: 2 }
job.delay 1000 # Ensure that job2 has the opportunity to run first
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
job2.depends [job]
job2.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
count = 0
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
count++
test.equal count, job.data.order
job.done()
cb()
if count is 2
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Dependent job with delayDeps is delayed', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { order: 1 }
job2 = new Job testColl, jobType, { order: 2 }
job.delay 1000 # Ensure that job2 has the opportunity to run first
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
job2.depends [job]
job2.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
count = 0
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
count++
test.equal count, job.data.order
timer = new Date()
job.done(null, { delayDeps: 1500 })
cb()
if count is 2
test.ok new Date() > timer + 1500
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Job priority is respected', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
jobs = []
jobs[0] = new Job(testColl, jobType, {count: 3}).priority('low')
jobs[1] = new Job(testColl, jobType, {count: 1}).priority('high')
jobs[2] = new Job(testColl, jobType, {count: 2})
jobs[0].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[0].save() failed in callback result"
jobs[1].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[1].save() failed in callback result"
jobs[2].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[2].save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.data.count, counter
job.done()
cb()
if counter is 3
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A forever retrying job can be scheduled and run', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: testColl.forever, wait: 0})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter < 3
job.fail('Fail test')
cb()
else
job.fail('Fail test', { fatal: true })
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Retrying job with exponential backoff', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: 2, wait: 200, backoff: 'exponential'})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter < 3
job.fail('Fail test')
cb()
else
job.fail('Fail test')
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A forever retrying job with "until"', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({until: new Date(new Date().valueOf() + 1500), wait: 500})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
job.fail('Fail test')
cb()
Meteor.setTimeout(() ->
job.refresh () ->
test.equal job._doc.status, 'failed', "Until didn't cause job to stop retrying"
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
,
2500
)
Tinytest.addAsync 'Autofail and retry a job', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: 2, wait: 0})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250, workTimeout: 500 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter is 2
job.done('Success')
# Will be called without done/fail on first attempt
cb()
Meteor.setTimeout(() ->
job.refresh () ->
test.equal job._doc.status, 'completed', "Job didn't successfully autofail and retry"
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
,
2500
)
if Meteor.isServer
Tinytest.addAsync 'Save, cancel, restart, refresh: retries are correct.', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
j = new Job(testColl, jobType, { foo: "bar" })
j.save()
j.cancel()
j.restart({ retries: 0 })
j.refresh()
test.equal j._doc.repeatRetries, j._doc.retries + j._doc.retried
onComplete()
Tinytest.addAsync 'Add, cancel and remove a large number of jobs', (test, onComplete) ->
c = count = 500
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
for i in [1..count]
j = new Job(testColl, jobType, { idx: i })
j.save (err, res) ->
test.fail(err) if err
test.fail("job.save() Invalid _id value returned") unless validId(res)
c--
unless c
ids = testColl.find({ type: jobType, status: 'ready'}).map((d) -> d._id)
test.equal count, ids.length
testColl.cancelJobs ids, (err, res) ->
test.fail(err) if err
test.fail("cancelJobs Failed") unless res
ids = testColl.find({ type: jobType, status: 'cancelled'}).map((d) -> d._id)
test.equal count, ids.length
testColl.removeJobs ids, (err, res) ->
test.fail(err) if err
test.fail("removeJobs Failed") unless res
ids = testColl.find { type: jobType }
test.equal 0, ids.count()
onComplete()
Tinytest.addAsync 'A forever repeating job with "schedule" and "until"', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'})
.repeat({
until: new Date(new Date().valueOf() + 2500),
schedule: testColl.later.parse.text("every 1 second")})
.delay(1000)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
if counter is 1
test.equal job.doc._id, res
else
test.notEqual job.doc._id, res
job.done({}, { repeatId: true })
cb()
listener = (msg) ->
if counter is 2
job.refresh () ->
test.equal job._doc.status, 'completed'
q.shutdown { level: 'soft', quiet: true }, () ->
ev.removeListener 'jobDone', listener
onComplete()
ev = testColl.events.on 'jobDone', listener
# Tinytest.addAsync 'Run stopJobs on the job collection', (test, onComplete) ->
# testColl.stopJobs { timeout: 1 }, (err, res) ->
# test.fail(err) if err
# test.equal res, true, "stopJobs failed in callback result"
# if Meteor.isServer
# test.notEqual testColl.stopped, false, "stopJobs didn't stop job collection"
# onComplete()
Tinytest.addAsync 'Run shutdownJobServer on the job collection', (test, onComplete) ->
testColl.shutdownJobServer { timeout: 1 }, (err, res) ->
test.fail(err) if err
test.equal res, true, "shutdownJobServer failed in callback result"
if Meteor.isServer
test.notEqual testColl.stopped, false, "shutdownJobServer didn't stop job collection"
onComplete()
if Meteor.isClient
Tinytest.addAsync 'Run startJobServer on remote job collection', (test, onComplete) ->
remoteServerTestColl.startJobServer (err, res) ->
test.fail(err) if err
test.equal res, true, "startJobServer failed in callback result"
onComplete()
Tinytest.addAsync 'Create a job and see that it is added to a remote server collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job remoteServerTestColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = remoteServerTestColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Run shutdownJobServer on remote job collection', (test, onComplete) ->
remoteServerTestColl.shutdownJobServer { timeout: 1 }, (err, res) ->
test.fail(err) if err
test.equal res, true, "shutdownJobServer failed in callback result"
onComplete()
| 71572 | ############################################################################
# Copyright (C) 2014-2016 by <NAME>
# job-collection is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
bind_env = (func) ->
if Meteor.isServer and typeof func is 'function'
return Meteor.bindEnvironment func, (err) -> throw err
else
return func
subWrapper = (sub, func) ->
(test, onComplete) ->
if Meteor.isClient
Deps.autorun () ->
if sub.ready()
func test, onComplete
else
func test, onComplete
validId = (v) ->
Match.test(v, Match.OneOf(String, Meteor.Collection.ObjectID))
defaultColl = new JobCollection()
validJobDoc = (d) ->
Match.test(d, defaultColl.jobDocPattern)
Tinytest.add 'JobCollection default constructor', (test) ->
test.instanceOf defaultColl, JobCollection, "JobCollection constructor failed"
test.equal defaultColl.root, 'queue', "default root isn't 'queue'"
if Meteor.isServer
test.equal defaultColl.stopped, true, "isn't initially stopped"
test.equal defaultColl.logStream, null, "Doesn't have a logStream"
test.instanceOf defaultColl.allows, Object, "allows isn't an object"
test.equal Object.keys(defaultColl.allows).length, 22, "allows not properly initialized"
test.instanceOf defaultColl.denys, Object, "denys isn't an object"
test.equal Object.keys(defaultColl.denys).length, 22, "denys not properly initialized"
else
test.equal defaultColl.logConsole, false, "Doesn't have a logConsole"
clientTestColl = new JobCollection 'ClientTest', { idGeneration: 'MONGO' }
serverTestColl = new JobCollection 'ServerTest', { idGeneration: 'STRING' }
# The line below is a regression test for issue #51
dummyTestColl = new JobCollection 'DummyTest', { idGeneration: 'STRING' }
if Meteor.isServer
remoteTestColl = new JobCollection 'RemoteTest', { idGeneration: 'STRING' }
remoteTestColl.allow
admin: () -> true
else
remoteConnection = DDP.connect Meteor.absoluteUrl()
remoteServerTestColl = new JobCollection 'RemoteTest', { idGeneration: 'STRING', connection: remoteConnection }
testColl = null # This will be defined differently for client / server
if Meteor.isServer
clientTestColl.allow
admin: () -> true
Tinytest.add 'Set permissions to allow admin on ClientTest', (test) ->
test.equal clientTestColl.allows.admin[0](), true
Tinytest.add 'Set polling interval', (test) ->
interval = clientTestColl.interval
clientTestColl.promote 250
test.notEqual interval, clientTestColl.interval, "clientTestColl interval not updated"
interval = serverTestColl.interval
serverTestColl.promote 250
test.notEqual interval, serverTestColl.interval, "serverTestColl interval not updated"
testColl = if Meteor.isClient then clientTestColl else serverTestColl
# Tinytest.addAsync 'Run startJobs on new job collection', (test, onComplete) ->
# testColl.startJobs (err, res) ->
# test.fail(err) if err
# test.equal res, true, "startJobs failed in callback result"
# if Meteor.isServer
# test.equal testColl.stopped, false, "startJobs didn't start job collection"
# onComplete()
Tinytest.addAsync 'Run startJobServer on new job collection', (test, onComplete) ->
testColl.startJobServer (err, res) ->
test.fail(err) if err
test.equal res, true, "startJobServer failed in callback result"
if Meteor.isServer
test.equal testColl.stopped, false, "startJobServer didn't start job collection"
onComplete()
if Meteor.isServer
Tinytest.addAsync 'Create a server-side job and see that it is added to the collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
res = job.save()
test.ok validId(res), "job.save() failed in sync result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
ev = testColl.events.once 'jobDone', (msg) ->
test.equal msg.method, 'jobDone'
if msg.params[0] is res
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Create a job and see that it is added to the collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Create an invalid job and see that errors correctly propagate', (test, onComplete) ->
console.warn "****************************************************************************************************"
console.warn "***** The following exception dump is a Normal and Expected part of error handling unit tests: *****"
console.warn "****************************************************************************************************"
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
delete job.doc.status
test.equal validJobDoc(job.doc), false
if Meteor.isServer
eventFlag = false
err = null
ev = testColl.events.once 'jobSave', (msg) ->
eventFlag = true
test.fail(new Error "Server error event didn't dispatch") unless msg.error
try
job.save()
catch e
err = e
finally
test.ok eventFlag
test.fail(new Error "Server exception wasn't thrown") unless err
onComplete()
else
job.save (err, res) ->
test.fail(new Error "Error did not propagate to Client") unless err
onComplete()
Tinytest.addAsync 'Create a job and then make a new doc with its document', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job2 = new Job testColl, jobType, { some: 'data' }
if Meteor.isServer
job = new Job 'ServerTest', job2.doc
else
job = new Job 'ClientTest', job2.doc
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A repeating job that returns the _id of the next job', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).repeat({ repeats: 1, wait: 250 })
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
if counter is 1
test.equal job.doc._id, res
job.done "Result1", { repeatId: true }, (err, res) ->
test.fail(err) if err
test.ok res?
test.notEqual res, true
testColl.getJob res, (err, j) ->
test.fail(err) if err
test.equal j._doc._id, res
cb()
else
test.notEqual job.doc._id, res
job.done "Result2", { repeatId: true }, (err, res) ->
test.fail(err) if err
test.equal res, true
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Dependent jobs run in the correct order', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { order: 1 }
job2 = new Job testColl, jobType, { order: 2 }
job.delay 1000 # Ensure that job2 has the opportunity to run first
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
job2.depends [job]
job2.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
count = 0
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
count++
test.equal count, job.data.order
job.done()
cb()
if count is 2
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Dependent job with delayDeps is delayed', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { order: 1 }
job2 = new Job testColl, jobType, { order: 2 }
job.delay 1000 # Ensure that job2 has the opportunity to run first
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
job2.depends [job]
job2.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
count = 0
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
count++
test.equal count, job.data.order
timer = new Date()
job.done(null, { delayDeps: 1500 })
cb()
if count is 2
test.ok new Date() > timer + 1500
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Job priority is respected', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
jobs = []
jobs[0] = new Job(testColl, jobType, {count: 3}).priority('low')
jobs[1] = new Job(testColl, jobType, {count: 1}).priority('high')
jobs[2] = new Job(testColl, jobType, {count: 2})
jobs[0].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[0].save() failed in callback result"
jobs[1].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[1].save() failed in callback result"
jobs[2].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[2].save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.data.count, counter
job.done()
cb()
if counter is 3
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A forever retrying job can be scheduled and run', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: testColl.forever, wait: 0})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter < 3
job.fail('Fail test')
cb()
else
job.fail('Fail test', { fatal: true })
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Retrying job with exponential backoff', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: 2, wait: 200, backoff: 'exponential'})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter < 3
job.fail('Fail test')
cb()
else
job.fail('Fail test')
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A forever retrying job with "until"', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({until: new Date(new Date().valueOf() + 1500), wait: 500})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
job.fail('Fail test')
cb()
Meteor.setTimeout(() ->
job.refresh () ->
test.equal job._doc.status, 'failed', "Until didn't cause job to stop retrying"
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
,
2500
)
Tinytest.addAsync 'Autofail and retry a job', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: 2, wait: 0})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250, workTimeout: 500 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter is 2
job.done('Success')
# Will be called without done/fail on first attempt
cb()
Meteor.setTimeout(() ->
job.refresh () ->
test.equal job._doc.status, 'completed', "Job didn't successfully autofail and retry"
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
,
2500
)
if Meteor.isServer
Tinytest.addAsync 'Save, cancel, restart, refresh: retries are correct.', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
j = new Job(testColl, jobType, { foo: "bar" })
j.save()
j.cancel()
j.restart({ retries: 0 })
j.refresh()
test.equal j._doc.repeatRetries, j._doc.retries + j._doc.retried
onComplete()
Tinytest.addAsync 'Add, cancel and remove a large number of jobs', (test, onComplete) ->
c = count = 500
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
for i in [1..count]
j = new Job(testColl, jobType, { idx: i })
j.save (err, res) ->
test.fail(err) if err
test.fail("job.save() Invalid _id value returned") unless validId(res)
c--
unless c
ids = testColl.find({ type: jobType, status: 'ready'}).map((d) -> d._id)
test.equal count, ids.length
testColl.cancelJobs ids, (err, res) ->
test.fail(err) if err
test.fail("cancelJobs Failed") unless res
ids = testColl.find({ type: jobType, status: 'cancelled'}).map((d) -> d._id)
test.equal count, ids.length
testColl.removeJobs ids, (err, res) ->
test.fail(err) if err
test.fail("removeJobs Failed") unless res
ids = testColl.find { type: jobType }
test.equal 0, ids.count()
onComplete()
Tinytest.addAsync 'A forever repeating job with "schedule" and "until"', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'})
.repeat({
until: new Date(new Date().valueOf() + 2500),
schedule: testColl.later.parse.text("every 1 second")})
.delay(1000)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
if counter is 1
test.equal job.doc._id, res
else
test.notEqual job.doc._id, res
job.done({}, { repeatId: true })
cb()
listener = (msg) ->
if counter is 2
job.refresh () ->
test.equal job._doc.status, 'completed'
q.shutdown { level: 'soft', quiet: true }, () ->
ev.removeListener 'jobDone', listener
onComplete()
ev = testColl.events.on 'jobDone', listener
# Tinytest.addAsync 'Run stopJobs on the job collection', (test, onComplete) ->
# testColl.stopJobs { timeout: 1 }, (err, res) ->
# test.fail(err) if err
# test.equal res, true, "stopJobs failed in callback result"
# if Meteor.isServer
# test.notEqual testColl.stopped, false, "stopJobs didn't stop job collection"
# onComplete()
Tinytest.addAsync 'Run shutdownJobServer on the job collection', (test, onComplete) ->
testColl.shutdownJobServer { timeout: 1 }, (err, res) ->
test.fail(err) if err
test.equal res, true, "shutdownJobServer failed in callback result"
if Meteor.isServer
test.notEqual testColl.stopped, false, "shutdownJobServer didn't stop job collection"
onComplete()
if Meteor.isClient
Tinytest.addAsync 'Run startJobServer on remote job collection', (test, onComplete) ->
remoteServerTestColl.startJobServer (err, res) ->
test.fail(err) if err
test.equal res, true, "startJobServer failed in callback result"
onComplete()
Tinytest.addAsync 'Create a job and see that it is added to a remote server collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job remoteServerTestColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = remoteServerTestColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Run shutdownJobServer on remote job collection', (test, onComplete) ->
remoteServerTestColl.shutdownJobServer { timeout: 1 }, (err, res) ->
test.fail(err) if err
test.equal res, true, "shutdownJobServer failed in callback result"
onComplete()
| true | ############################################################################
# Copyright (C) 2014-2016 by PI:NAME:<NAME>END_PI
# job-collection is free software released under the MIT/X11 license.
# See included LICENSE file for details.
############################################################################
bind_env = (func) ->
if Meteor.isServer and typeof func is 'function'
return Meteor.bindEnvironment func, (err) -> throw err
else
return func
subWrapper = (sub, func) ->
(test, onComplete) ->
if Meteor.isClient
Deps.autorun () ->
if sub.ready()
func test, onComplete
else
func test, onComplete
validId = (v) ->
Match.test(v, Match.OneOf(String, Meteor.Collection.ObjectID))
defaultColl = new JobCollection()
validJobDoc = (d) ->
Match.test(d, defaultColl.jobDocPattern)
Tinytest.add 'JobCollection default constructor', (test) ->
test.instanceOf defaultColl, JobCollection, "JobCollection constructor failed"
test.equal defaultColl.root, 'queue', "default root isn't 'queue'"
if Meteor.isServer
test.equal defaultColl.stopped, true, "isn't initially stopped"
test.equal defaultColl.logStream, null, "Doesn't have a logStream"
test.instanceOf defaultColl.allows, Object, "allows isn't an object"
test.equal Object.keys(defaultColl.allows).length, 22, "allows not properly initialized"
test.instanceOf defaultColl.denys, Object, "denys isn't an object"
test.equal Object.keys(defaultColl.denys).length, 22, "denys not properly initialized"
else
test.equal defaultColl.logConsole, false, "Doesn't have a logConsole"
clientTestColl = new JobCollection 'ClientTest', { idGeneration: 'MONGO' }
serverTestColl = new JobCollection 'ServerTest', { idGeneration: 'STRING' }
# The line below is a regression test for issue #51
dummyTestColl = new JobCollection 'DummyTest', { idGeneration: 'STRING' }
if Meteor.isServer
remoteTestColl = new JobCollection 'RemoteTest', { idGeneration: 'STRING' }
remoteTestColl.allow
admin: () -> true
else
remoteConnection = DDP.connect Meteor.absoluteUrl()
remoteServerTestColl = new JobCollection 'RemoteTest', { idGeneration: 'STRING', connection: remoteConnection }
testColl = null # This will be defined differently for client / server
if Meteor.isServer
clientTestColl.allow
admin: () -> true
Tinytest.add 'Set permissions to allow admin on ClientTest', (test) ->
test.equal clientTestColl.allows.admin[0](), true
Tinytest.add 'Set polling interval', (test) ->
interval = clientTestColl.interval
clientTestColl.promote 250
test.notEqual interval, clientTestColl.interval, "clientTestColl interval not updated"
interval = serverTestColl.interval
serverTestColl.promote 250
test.notEqual interval, serverTestColl.interval, "serverTestColl interval not updated"
testColl = if Meteor.isClient then clientTestColl else serverTestColl
# Tinytest.addAsync 'Run startJobs on new job collection', (test, onComplete) ->
# testColl.startJobs (err, res) ->
# test.fail(err) if err
# test.equal res, true, "startJobs failed in callback result"
# if Meteor.isServer
# test.equal testColl.stopped, false, "startJobs didn't start job collection"
# onComplete()
Tinytest.addAsync 'Run startJobServer on new job collection', (test, onComplete) ->
testColl.startJobServer (err, res) ->
test.fail(err) if err
test.equal res, true, "startJobServer failed in callback result"
if Meteor.isServer
test.equal testColl.stopped, false, "startJobServer didn't start job collection"
onComplete()
if Meteor.isServer
Tinytest.addAsync 'Create a server-side job and see that it is added to the collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
res = job.save()
test.ok validId(res), "job.save() failed in sync result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
ev = testColl.events.once 'jobDone', (msg) ->
test.equal msg.method, 'jobDone'
if msg.params[0] is res
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Create a job and see that it is added to the collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Create an invalid job and see that errors correctly propagate', (test, onComplete) ->
console.warn "****************************************************************************************************"
console.warn "***** The following exception dump is a Normal and Expected part of error handling unit tests: *****"
console.warn "****************************************************************************************************"
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { some: 'data' }
delete job.doc.status
test.equal validJobDoc(job.doc), false
if Meteor.isServer
eventFlag = false
err = null
ev = testColl.events.once 'jobSave', (msg) ->
eventFlag = true
test.fail(new Error "Server error event didn't dispatch") unless msg.error
try
job.save()
catch e
err = e
finally
test.ok eventFlag
test.fail(new Error "Server exception wasn't thrown") unless err
onComplete()
else
job.save (err, res) ->
test.fail(new Error "Error did not propagate to Client") unless err
onComplete()
Tinytest.addAsync 'Create a job and then make a new doc with its document', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job2 = new Job testColl, jobType, { some: 'data' }
if Meteor.isServer
job = new Job 'ServerTest', job2.doc
else
job = new Job 'ClientTest', job2.doc
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A repeating job that returns the _id of the next job', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).repeat({ repeats: 1, wait: 250 })
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
if counter is 1
test.equal job.doc._id, res
job.done "Result1", { repeatId: true }, (err, res) ->
test.fail(err) if err
test.ok res?
test.notEqual res, true
testColl.getJob res, (err, j) ->
test.fail(err) if err
test.equal j._doc._id, res
cb()
else
test.notEqual job.doc._id, res
job.done "Result2", { repeatId: true }, (err, res) ->
test.fail(err) if err
test.equal res, true
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Dependent jobs run in the correct order', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { order: 1 }
job2 = new Job testColl, jobType, { order: 2 }
job.delay 1000 # Ensure that job2 has the opportunity to run first
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
job2.depends [job]
job2.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
count = 0
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
count++
test.equal count, job.data.order
job.done()
cb()
if count is 2
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Dependent job with delayDeps is delayed', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job testColl, jobType, { order: 1 }
job2 = new Job testColl, jobType, { order: 2 }
job.delay 1000 # Ensure that job2 has the opportunity to run first
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
job2.depends [job]
job2.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
count = 0
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
count++
test.equal count, job.data.order
timer = new Date()
job.done(null, { delayDeps: 1500 })
cb()
if count is 2
test.ok new Date() > timer + 1500
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Job priority is respected', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
jobs = []
jobs[0] = new Job(testColl, jobType, {count: 3}).priority('low')
jobs[1] = new Job(testColl, jobType, {count: 1}).priority('high')
jobs[2] = new Job(testColl, jobType, {count: 2})
jobs[0].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[0].save() failed in callback result"
jobs[1].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[1].save() failed in callback result"
jobs[2].save (err, res) ->
test.fail(err) if err
test.ok validId(res), "jobs[2].save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.data.count, counter
job.done()
cb()
if counter is 3
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A forever retrying job can be scheduled and run', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: testColl.forever, wait: 0})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter < 3
job.fail('Fail test')
cb()
else
job.fail('Fail test', { fatal: true })
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Retrying job with exponential backoff', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: 2, wait: 200, backoff: 'exponential'})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter < 3
job.fail('Fail test')
cb()
else
job.fail('Fail test')
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'A forever retrying job with "until"', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({until: new Date(new Date().valueOf() + 1500), wait: 500})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
test.equal job.doc._id, res
job.fail('Fail test')
cb()
Meteor.setTimeout(() ->
job.refresh () ->
test.equal job._doc.status, 'failed', "Until didn't cause job to stop retrying"
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
,
2500
)
Tinytest.addAsync 'Autofail and retry a job', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'}).retry({retries: 2, wait: 0})
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250, workTimeout: 500 }, (job, cb) ->
counter++
test.equal job.doc._id, res
if counter is 2
job.done('Success')
# Will be called without done/fail on first attempt
cb()
Meteor.setTimeout(() ->
job.refresh () ->
test.equal job._doc.status, 'completed', "Job didn't successfully autofail and retry"
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
,
2500
)
if Meteor.isServer
Tinytest.addAsync 'Save, cancel, restart, refresh: retries are correct.', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
j = new Job(testColl, jobType, { foo: "bar" })
j.save()
j.cancel()
j.restart({ retries: 0 })
j.refresh()
test.equal j._doc.repeatRetries, j._doc.retries + j._doc.retried
onComplete()
Tinytest.addAsync 'Add, cancel and remove a large number of jobs', (test, onComplete) ->
c = count = 500
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
for i in [1..count]
j = new Job(testColl, jobType, { idx: i })
j.save (err, res) ->
test.fail(err) if err
test.fail("job.save() Invalid _id value returned") unless validId(res)
c--
unless c
ids = testColl.find({ type: jobType, status: 'ready'}).map((d) -> d._id)
test.equal count, ids.length
testColl.cancelJobs ids, (err, res) ->
test.fail(err) if err
test.fail("cancelJobs Failed") unless res
ids = testColl.find({ type: jobType, status: 'cancelled'}).map((d) -> d._id)
test.equal count, ids.length
testColl.removeJobs ids, (err, res) ->
test.fail(err) if err
test.fail("removeJobs Failed") unless res
ids = testColl.find { type: jobType }
test.equal 0, ids.count()
onComplete()
Tinytest.addAsync 'A forever repeating job with "schedule" and "until"', (test, onComplete) ->
counter = 0
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job(testColl, jobType, {some: 'data'})
.repeat({
until: new Date(new Date().valueOf() + 2500),
schedule: testColl.later.parse.text("every 1 second")})
.delay(1000)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = testColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
counter++
if counter is 1
test.equal job.doc._id, res
else
test.notEqual job.doc._id, res
job.done({}, { repeatId: true })
cb()
listener = (msg) ->
if counter is 2
job.refresh () ->
test.equal job._doc.status, 'completed'
q.shutdown { level: 'soft', quiet: true }, () ->
ev.removeListener 'jobDone', listener
onComplete()
ev = testColl.events.on 'jobDone', listener
# Tinytest.addAsync 'Run stopJobs on the job collection', (test, onComplete) ->
# testColl.stopJobs { timeout: 1 }, (err, res) ->
# test.fail(err) if err
# test.equal res, true, "stopJobs failed in callback result"
# if Meteor.isServer
# test.notEqual testColl.stopped, false, "stopJobs didn't stop job collection"
# onComplete()
Tinytest.addAsync 'Run shutdownJobServer on the job collection', (test, onComplete) ->
testColl.shutdownJobServer { timeout: 1 }, (err, res) ->
test.fail(err) if err
test.equal res, true, "shutdownJobServer failed in callback result"
if Meteor.isServer
test.notEqual testColl.stopped, false, "shutdownJobServer didn't stop job collection"
onComplete()
if Meteor.isClient
Tinytest.addAsync 'Run startJobServer on remote job collection', (test, onComplete) ->
remoteServerTestColl.startJobServer (err, res) ->
test.fail(err) if err
test.equal res, true, "startJobServer failed in callback result"
onComplete()
Tinytest.addAsync 'Create a job and see that it is added to a remote server collection and runs', (test, onComplete) ->
jobType = "TestJob_#{Math.round(Math.random()*1000000000)}"
job = new Job remoteServerTestColl, jobType, { some: 'data' }
test.ok validJobDoc(job.doc)
job.save (err, res) ->
test.fail(err) if err
test.ok validId(res), "job.save() failed in callback result"
q = remoteServerTestColl.processJobs jobType, { pollInterval: 250 }, (job, cb) ->
test.equal job._doc._id, res
job.done()
cb()
q.shutdown { level: 'soft', quiet: true }, () ->
onComplete()
Tinytest.addAsync 'Run shutdownJobServer on remote job collection', (test, onComplete) ->
remoteServerTestColl.shutdownJobServer { timeout: 1 }, (err, res) ->
test.fail(err) if err
test.equal res, true, "shutdownJobServer failed in callback result"
onComplete()
|
[
{
"context": "s manager\n\n@namespace Quo\n@class Gestures\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\nQ",
"end": 87,
"score": 0.9998689889907837,
"start": 66,
"tag": "NAME",
"value": "Javier Jimenez Villar"
},
{
"context": "o\n@class Gestures\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\nQuo.Gestures = do ",
"end": 104,
"score": 0.9999361038208008,
"start": 89,
"tag": "EMAIL",
"value": "javi@tapquo.com"
},
{
"context": "@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\nQuo.Gestures = do ($$ = Quo) ->",
"end": 117,
"score": 0.8586293458938599,
"start": 109,
"tag": "USERNAME",
"value": "@soyjavi"
}
] | source/quo.gestures.coffee | lguzzon/QuoJS | 558 | ###
Quo Gestures manager
@namespace Quo
@class Gestures
@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
###
"use strict"
Quo.Gestures = do ($$ = Quo) ->
_started = false
_handlers = {}
_fingers = null
_originalEvent = null
_disabled_tags = ["input", "select", "textarea"]
add = (gesture) ->
_handlers[gesture.name] = gesture.handler
_addDelegations gesture.events
trigger = (target, eventName, gestureData) ->
$$(target).trigger(eventName, gestureData, _originalEvent)
# Private methods
_start = (ev) ->
return ev.stopPropagation() if (ev.srcElement or ev.target).tagName.toLowerCase() in _disabled_tags
_started = true
_originalEvent = ev or event
_fingers = _getFingers(ev)
_handle "start", ev.target, _fingers
_move = (ev) ->
return unless _started
_originalEvent = ev or event
_fingers = _getFingers(ev)
_originalEvent.preventDefault() if _fingers.length > 1
_handle "move", ev.target, _fingers
_end = (ev) ->
return unless _started
_originalEvent = ev or event
_handle "end", ev.target, _fingers
_started = false
_cancel = (ev) ->
_started = false
_handle "cancel"
_addDelegations = (events) ->
events.forEach (event_name) ->
$$.fn[event_name] = (callback) ->
$$(document.body).delegate @selector, event_name, callback
@
_handle = (event, target, data) ->
for name, handler of _handlers when handler[event]
handler[event].call(handler, target, data)
_getFingers = (event) ->
({x: t.pageX, y: t.pageY} for t in event.touches or [event])
$$(document).ready ->
environment = $$ document.body
environment.bind "touchstart", _start
environment.bind "touchmove", _move
environment.bind "touchend", _end
environment.bind "touchcancel", _cancel
add : add
trigger : trigger
| 183431 | ###
Quo Gestures manager
@namespace Quo
@class Gestures
@author <NAME> <<EMAIL>> || @soyjavi
###
"use strict"
Quo.Gestures = do ($$ = Quo) ->
_started = false
_handlers = {}
_fingers = null
_originalEvent = null
_disabled_tags = ["input", "select", "textarea"]
add = (gesture) ->
_handlers[gesture.name] = gesture.handler
_addDelegations gesture.events
trigger = (target, eventName, gestureData) ->
$$(target).trigger(eventName, gestureData, _originalEvent)
# Private methods
_start = (ev) ->
return ev.stopPropagation() if (ev.srcElement or ev.target).tagName.toLowerCase() in _disabled_tags
_started = true
_originalEvent = ev or event
_fingers = _getFingers(ev)
_handle "start", ev.target, _fingers
_move = (ev) ->
return unless _started
_originalEvent = ev or event
_fingers = _getFingers(ev)
_originalEvent.preventDefault() if _fingers.length > 1
_handle "move", ev.target, _fingers
_end = (ev) ->
return unless _started
_originalEvent = ev or event
_handle "end", ev.target, _fingers
_started = false
_cancel = (ev) ->
_started = false
_handle "cancel"
_addDelegations = (events) ->
events.forEach (event_name) ->
$$.fn[event_name] = (callback) ->
$$(document.body).delegate @selector, event_name, callback
@
_handle = (event, target, data) ->
for name, handler of _handlers when handler[event]
handler[event].call(handler, target, data)
_getFingers = (event) ->
({x: t.pageX, y: t.pageY} for t in event.touches or [event])
$$(document).ready ->
environment = $$ document.body
environment.bind "touchstart", _start
environment.bind "touchmove", _move
environment.bind "touchend", _end
environment.bind "touchcancel", _cancel
add : add
trigger : trigger
| true | ###
Quo Gestures manager
@namespace Quo
@class Gestures
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi
###
"use strict"
Quo.Gestures = do ($$ = Quo) ->
_started = false
_handlers = {}
_fingers = null
_originalEvent = null
_disabled_tags = ["input", "select", "textarea"]
add = (gesture) ->
_handlers[gesture.name] = gesture.handler
_addDelegations gesture.events
trigger = (target, eventName, gestureData) ->
$$(target).trigger(eventName, gestureData, _originalEvent)
# Private methods
_start = (ev) ->
return ev.stopPropagation() if (ev.srcElement or ev.target).tagName.toLowerCase() in _disabled_tags
_started = true
_originalEvent = ev or event
_fingers = _getFingers(ev)
_handle "start", ev.target, _fingers
_move = (ev) ->
return unless _started
_originalEvent = ev or event
_fingers = _getFingers(ev)
_originalEvent.preventDefault() if _fingers.length > 1
_handle "move", ev.target, _fingers
_end = (ev) ->
return unless _started
_originalEvent = ev or event
_handle "end", ev.target, _fingers
_started = false
_cancel = (ev) ->
_started = false
_handle "cancel"
_addDelegations = (events) ->
events.forEach (event_name) ->
$$.fn[event_name] = (callback) ->
$$(document.body).delegate @selector, event_name, callback
@
_handle = (event, target, data) ->
for name, handler of _handlers when handler[event]
handler[event].call(handler, target, data)
_getFingers = (event) ->
({x: t.pageX, y: t.pageY} for t in event.touches or [event])
$$(document).ready ->
environment = $$ document.body
environment.bind "touchstart", _start
environment.bind "touchmove", _move
environment.bind "touchend", _end
environment.bind "touchcancel", _cancel
add : add
trigger : trigger
|
[
{
"context": "###\n@authors:\n- Nicolas Laplante https://plus.google.com/108189012221374960701\n- N",
"end": 32,
"score": 0.9998934864997864,
"start": 16,
"tag": "NAME",
"value": "Nicolas Laplante"
},
{
"context": "te https://plus.google.com/108189012221374960701\n- Nicholas McCready - https://twitter.com/nmccready\n- Carrie Kengle -",
"end": 98,
"score": 0.9998869895935059,
"start": 81,
"tag": "NAME",
"value": "Nicholas McCready"
},
{
"context": "4960701\n- Nicholas McCready - https://twitter.com/nmccready\n- Carrie Kengle - http://about.me/carrie\n###\n\n###",
"end": 130,
"score": 0.9996669888496399,
"start": 121,
"tag": "USERNAME",
"value": "nmccready"
},
{
"context": "icholas McCready - https://twitter.com/nmccready\n- Carrie Kengle - http://about.me/carrie\n###\n\n###\nPlaces Search B",
"end": 146,
"score": 0.9998952746391296,
"start": 133,
"tag": "NAME",
"value": "Carrie Kengle"
},
{
"context": "r.com/nmccready\n- Carrie Kengle - http://about.me/carrie\n###\n\n###\nPlaces Search Box directive\n\nThis direct",
"end": 171,
"score": 0.9939253926277161,
"start": 165,
"tag": "USERNAME",
"value": "carrie"
}
] | SafetyNet_Mobile/www/lib/angular-google-maps-master/src/coffee/directives/search-box.coffee | donh/pheonix | 1 | ###
@authors:
- Nicolas Laplante https://plus.google.com/108189012221374960701
- Nicholas McCready - https://twitter.com/nmccready
- Carrie Kengle - http://about.me/carrie
###
###
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
###
angular.module('uiGmapgoogle-maps')
.directive 'uiGmapSearchBox', ['uiGmapGoogleMapApi', 'uiGmapLogger',
'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile',
(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) ->
class SearchBox
require: 'ngModel'
constructor: ->
@$log = Logger
@restrict = 'EMA'
@require = '^' + 'uiGmapGoogleMap'
@priority = -1
@transclude = true
@template = '<span class=\'angular-google-map-search\' ng-transclude></span>'
@replace = true
@scope =
template: '=template' #required
events: '=events' #required
position: '=?position' #optional
options: '=?options' #optional
parentdiv: '=?parentdiv' #optional
ngModel: "=?" #optional
link: (scope, element, attrs, mapCtrl) =>
GoogleMapApi.then (maps) =>
$http.get(scope.template, { cache: $templateCache })
.success (template) =>
if angular.isUndefined scope.events
@$log.error 'searchBox: the events property is required'
return
mapCtrl.getScope().deferred.promise.then (map) =>
ctrlPosition = if angular.isDefined scope.position then scope.position.toUpperCase().replace /-/g, '_' else 'TOP_LEFT'
if not maps.ControlPosition[ctrlPosition]
@$log.error 'searchBox: invalid position property'
return
new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope))
new SearchBox()
]
| 127990 | ###
@authors:
- <NAME> https://plus.google.com/108189012221374960701
- <NAME> - https://twitter.com/nmccready
- <NAME> - http://about.me/carrie
###
###
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
###
angular.module('uiGmapgoogle-maps')
.directive 'uiGmapSearchBox', ['uiGmapGoogleMapApi', 'uiGmapLogger',
'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile',
(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) ->
class SearchBox
require: 'ngModel'
constructor: ->
@$log = Logger
@restrict = 'EMA'
@require = '^' + 'uiGmapGoogleMap'
@priority = -1
@transclude = true
@template = '<span class=\'angular-google-map-search\' ng-transclude></span>'
@replace = true
@scope =
template: '=template' #required
events: '=events' #required
position: '=?position' #optional
options: '=?options' #optional
parentdiv: '=?parentdiv' #optional
ngModel: "=?" #optional
link: (scope, element, attrs, mapCtrl) =>
GoogleMapApi.then (maps) =>
$http.get(scope.template, { cache: $templateCache })
.success (template) =>
if angular.isUndefined scope.events
@$log.error 'searchBox: the events property is required'
return
mapCtrl.getScope().deferred.promise.then (map) =>
ctrlPosition = if angular.isDefined scope.position then scope.position.toUpperCase().replace /-/g, '_' else 'TOP_LEFT'
if not maps.ControlPosition[ctrlPosition]
@$log.error 'searchBox: invalid position property'
return
new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope))
new SearchBox()
]
| true | ###
@authors:
- PI:NAME:<NAME>END_PI https://plus.google.com/108189012221374960701
- PI:NAME:<NAME>END_PI - https://twitter.com/nmccready
- PI:NAME:<NAME>END_PI - http://about.me/carrie
###
###
Places Search Box directive
This directive is used to create a Places Search Box.
This directive creates a new scope.
{attribute input required} HTMLInputElement
{attribute options optional} The options that can be set on a SearchBox object (google.maps.places.SearchBoxOptions object specification)
###
angular.module('uiGmapgoogle-maps')
.directive 'uiGmapSearchBox', ['uiGmapGoogleMapApi', 'uiGmapLogger',
'uiGmapSearchBoxParentModel', '$http', '$templateCache', '$compile',
(GoogleMapApi, Logger, SearchBoxParentModel, $http, $templateCache, $compile) ->
class SearchBox
require: 'ngModel'
constructor: ->
@$log = Logger
@restrict = 'EMA'
@require = '^' + 'uiGmapGoogleMap'
@priority = -1
@transclude = true
@template = '<span class=\'angular-google-map-search\' ng-transclude></span>'
@replace = true
@scope =
template: '=template' #required
events: '=events' #required
position: '=?position' #optional
options: '=?options' #optional
parentdiv: '=?parentdiv' #optional
ngModel: "=?" #optional
link: (scope, element, attrs, mapCtrl) =>
GoogleMapApi.then (maps) =>
$http.get(scope.template, { cache: $templateCache })
.success (template) =>
if angular.isUndefined scope.events
@$log.error 'searchBox: the events property is required'
return
mapCtrl.getScope().deferred.promise.then (map) =>
ctrlPosition = if angular.isDefined scope.position then scope.position.toUpperCase().replace /-/g, '_' else 'TOP_LEFT'
if not maps.ControlPosition[ctrlPosition]
@$log.error 'searchBox: invalid position property'
return
new SearchBoxParentModel(scope, element, attrs, map, ctrlPosition, $compile(template)(scope))
new SearchBox()
]
|
[
{
"context": "].relationships.push(rel)\n \n key = \"group-#{@groupCount++}\"\n\n group = @data.groups[key] = \n k",
"end": 7025,
"score": 0.932339072227478,
"start": 7002,
"tag": "KEY",
"value": "group-#{@groupCount++}\""
}
] | community/server/src/main/coffeescript/neo4j/webadmin/modules/databrowser/visualization/VisualDataModel.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
[],
() ->
class VisualDataModel
constructor : (@groupingThreshold=5) ->
@clear()
clear : () ->
@groupCount = 0
@visualGraph =
nodes : {}
edges : {}
@data =
relationships : {}
nodes : {}
groups : {}
getVisualGraph : () ->
# XXX
# Arbor.js borks if given a graph with no relationships to render.
# Add a "secret" hack node and relationship if there are no real
# relationships.
# (2011-04-07)
if _(@visualGraph.edges).keys().length == 0
for key, node of @visualGraph.nodes
@visualGraph.nodes["#{key}-SECRET-HACK-NODE"] = { hidden : true }
@visualGraph.edges[key] ?= {}
@visualGraph.edges[key]["#{key}-SECRET-HACK-NODE"] = { hidden : true }
@visualGraph
addNode : (node, relationships, relatedNodes) =>
if not @visualGraph.nodes[node.getSelf()]? or @visualGraph.nodes[node.getSelf()].type isnt "explored"
@ungroup([node])
@ungroup(relatedNodes)
@data.nodes[node.getSelf()] ?= { node : node, groups : {} }
@visualGraph.nodes[node.getSelf()] = { neoNode : node, type : "explored" }
# Add any related nodes to our local cache, if we don't already have them.
for relatedNode in relatedNodes
@data.nodes[relatedNode.getSelf()] ?= { node : relatedNode, groups : {} }
potentialGroups = {incoming:{},outgoing:{}}
for rel in relationships
if @data.relationships[rel.getSelf()]?
continue
@data.relationships[rel.getSelf()] = rel
otherUrl = rel.getOtherNodeUrl(node.getSelf())
dir = if rel.isStartNode(node.getSelf()) then "outgoing" else "incoming"
if not @visualGraph.nodes[otherUrl]?
potentialGroups[dir][rel.getType()] ?= { relationships:[] }
potentialGroups[dir][rel.getType()].relationships.push(rel)
else
@_addRelationship(rel.getStartNodeUrl(), rel.getEndNodeUrl(), rel)
for dir, groups of potentialGroups
for type, group of groups
if group.relationships.length >= @groupingThreshold
@_addGroup node, group.relationships, dir
else
for rel in group.relationships
@_addUnexploredNode node, rel
ungroup : (nodes) ->
for node in nodes
nodeUrl = node.getSelf()
if @data.nodes[nodeUrl]?
meta = @data.nodes[nodeUrl]
for key, groupMeta of meta.groups
group = groupMeta.group
group.nodeCount--
delete group.grouped[nodeUrl]
for rel in groupMeta.relationships
@_addUnexploredNode group.baseNode, rel
if group.nodeCount <= 0
@_removeGroup group
unexplore : (node) ->
nodeUrl = node.getSelf()
if @_isLastExploredNode node
return
if @visualGraph.nodes[nodeUrl]?
visualNode = @visualGraph.nodes[nodeUrl]
visualNode.type = "unexplored"
node.fixed = false
potentiallRemove = @_getUnexploredNodesRelatedTo nodeUrl
for relatedNodeUrl, relatedNodeMeta of potentiallRemove
if not @_hasExploredRelationships relatedNodeUrl, nodeUrl
@removeNode relatedNodeMeta.node
@_removeGroupsFor node
if not @_hasExploredRelationships nodeUrl
@removeNode node
removeNode : (node) ->
nodeUrl = node.getSelf()
delete @visualGraph.nodes[nodeUrl]
delete @data.nodes[nodeUrl]
@_removeRelationshipsFor(node)
_isLastExploredNode : (node) ->
nodeUrl = node.getSelf()
for url, visualNode of @visualGraph.nodes
if visualNode.type == "explored" and url != nodeUrl
return false
return true
_getUnexploredNodesRelatedTo : (nodeUrl) ->
found = []
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if fromUrl is nodeUrl
if @visualGraph.nodes[toUrl].type? and @visualGraph.nodes[toUrl].type is "unexplored"
found[toUrl] = @data.nodes[toUrl]
if toUrl is nodeUrl
if @visualGraph.nodes[fromUrl].type? and @visualGraph.nodes[fromUrl].type is "unexplored"
found[fromUrl] = @data.nodes[fromUrl]
return found
_hasExploredRelationships : (nodeUrl, excludeNodeUrl="") ->
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if fromUrl is nodeUrl
if not (toUrl is excludeNodeUrl) and @visualGraph.nodes[toUrl].type is "explored"
return true
if toUrl is nodeUrl
if not (fromUrl is excludeNodeUrl) and @visualGraph.nodes[fromUrl].type is "explored"
return true
return false
_addRelationship : (from, to, rel, relType=null) ->
@visualGraph.edges[from] ?= {}
@visualGraph.edges[from][to] ?= { length:.5, relationships : {}, directed:true, relType:relType }
if rel != false
@visualGraph.edges[from][to].relationships[rel.getSelf()] = rel
_addUnexploredNode : (baseNode, rel) ->
unexploredUrl = rel.getOtherNodeUrl(baseNode.getSelf())
@visualGraph.nodes[unexploredUrl] ?=
neoNode : @data.nodes[unexploredUrl].node
type : "unexplored"
@_addRelationship(rel.getStartNodeUrl(), rel.getEndNodeUrl(), rel)
_addGroup : (baseNode, relationships, direction) ->
baseNodeUrl = baseNode.getSelf()
nodeCount = 0
grouped = {}
for rel in relationships
nodeUrl = rel.getOtherNodeUrl(baseNodeUrl)
if not @data.nodes[nodeUrl]?
continue
nodeMeta = @data.nodes[nodeUrl]
if not grouped[nodeUrl]?
grouped[nodeUrl] = { node : nodeMeta.node, relationships : []}
nodeCount++
grouped[nodeUrl].relationships.push(rel)
key = "group-#{@groupCount++}"
group = @data.groups[key] =
key : key
baseNode : baseNode
grouped : grouped
nodeCount : nodeCount
@visualGraph.nodes[key] =
key : key
type : "group"
group : group
for url, meta of grouped
@data.nodes[url].groups[key] = { group : group, relationships : meta.relationships }
if direction is "outgoing"
@_addRelationship(baseNode.getSelf(), key, false, relationships[0].getType())
else
@_addRelationship(key, baseNode.getSelf(), false, relationships[0].getType())
_removeRelationshipsFor : (node) ->
nodeUrl = node.getSelf()
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if toUrl is nodeUrl or fromUrl is nodeUrl
for url, rel of @visualGraph.edges[fromUrl][toUrl].relationships
delete @data.relationships[rel.getSelf()]
if toUrl is nodeUrl
delete @visualGraph.edges[fromUrl][toUrl]
if @visualGraph.edges[nodeUrl]?
delete @visualGraph.edges[nodeUrl]
_removeRelationshipsInGroup : (group) ->
for url, grouped of group.grouped
node = @data.nodes[url]
if node.groups[group.key]?
delete node.groups[group.key]
for rel in grouped.relationships
delete @data.relationships[rel.getSelf()]
_removeGroup : (group) ->
delete @visualGraph.nodes[group.key]
delete @data.groups[group.key]
if @visualGraph.edges[group.key]?
delete @visualGraph.edges[group.key]
else
if @visualGraph.edges[group.baseNode.getSelf()]? and @visualGraph.edges[group.baseNode.getSelf()][group.key]?
delete @visualGraph.edges[group.baseNode.getSelf()][group.key]
_removeGroupsFor : (node) ->
nodeUrl = node.getSelf()
for key, group of @data.groups
if group.baseNode.getSelf() is nodeUrl
@_removeRelationshipsInGroup group
@_removeGroup group
)
| 115836 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
[],
() ->
class VisualDataModel
constructor : (@groupingThreshold=5) ->
@clear()
clear : () ->
@groupCount = 0
@visualGraph =
nodes : {}
edges : {}
@data =
relationships : {}
nodes : {}
groups : {}
getVisualGraph : () ->
# XXX
# Arbor.js borks if given a graph with no relationships to render.
# Add a "secret" hack node and relationship if there are no real
# relationships.
# (2011-04-07)
if _(@visualGraph.edges).keys().length == 0
for key, node of @visualGraph.nodes
@visualGraph.nodes["#{key}-SECRET-HACK-NODE"] = { hidden : true }
@visualGraph.edges[key] ?= {}
@visualGraph.edges[key]["#{key}-SECRET-HACK-NODE"] = { hidden : true }
@visualGraph
addNode : (node, relationships, relatedNodes) =>
if not @visualGraph.nodes[node.getSelf()]? or @visualGraph.nodes[node.getSelf()].type isnt "explored"
@ungroup([node])
@ungroup(relatedNodes)
@data.nodes[node.getSelf()] ?= { node : node, groups : {} }
@visualGraph.nodes[node.getSelf()] = { neoNode : node, type : "explored" }
# Add any related nodes to our local cache, if we don't already have them.
for relatedNode in relatedNodes
@data.nodes[relatedNode.getSelf()] ?= { node : relatedNode, groups : {} }
potentialGroups = {incoming:{},outgoing:{}}
for rel in relationships
if @data.relationships[rel.getSelf()]?
continue
@data.relationships[rel.getSelf()] = rel
otherUrl = rel.getOtherNodeUrl(node.getSelf())
dir = if rel.isStartNode(node.getSelf()) then "outgoing" else "incoming"
if not @visualGraph.nodes[otherUrl]?
potentialGroups[dir][rel.getType()] ?= { relationships:[] }
potentialGroups[dir][rel.getType()].relationships.push(rel)
else
@_addRelationship(rel.getStartNodeUrl(), rel.getEndNodeUrl(), rel)
for dir, groups of potentialGroups
for type, group of groups
if group.relationships.length >= @groupingThreshold
@_addGroup node, group.relationships, dir
else
for rel in group.relationships
@_addUnexploredNode node, rel
ungroup : (nodes) ->
for node in nodes
nodeUrl = node.getSelf()
if @data.nodes[nodeUrl]?
meta = @data.nodes[nodeUrl]
for key, groupMeta of meta.groups
group = groupMeta.group
group.nodeCount--
delete group.grouped[nodeUrl]
for rel in groupMeta.relationships
@_addUnexploredNode group.baseNode, rel
if group.nodeCount <= 0
@_removeGroup group
unexplore : (node) ->
nodeUrl = node.getSelf()
if @_isLastExploredNode node
return
if @visualGraph.nodes[nodeUrl]?
visualNode = @visualGraph.nodes[nodeUrl]
visualNode.type = "unexplored"
node.fixed = false
potentiallRemove = @_getUnexploredNodesRelatedTo nodeUrl
for relatedNodeUrl, relatedNodeMeta of potentiallRemove
if not @_hasExploredRelationships relatedNodeUrl, nodeUrl
@removeNode relatedNodeMeta.node
@_removeGroupsFor node
if not @_hasExploredRelationships nodeUrl
@removeNode node
removeNode : (node) ->
nodeUrl = node.getSelf()
delete @visualGraph.nodes[nodeUrl]
delete @data.nodes[nodeUrl]
@_removeRelationshipsFor(node)
_isLastExploredNode : (node) ->
nodeUrl = node.getSelf()
for url, visualNode of @visualGraph.nodes
if visualNode.type == "explored" and url != nodeUrl
return false
return true
_getUnexploredNodesRelatedTo : (nodeUrl) ->
found = []
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if fromUrl is nodeUrl
if @visualGraph.nodes[toUrl].type? and @visualGraph.nodes[toUrl].type is "unexplored"
found[toUrl] = @data.nodes[toUrl]
if toUrl is nodeUrl
if @visualGraph.nodes[fromUrl].type? and @visualGraph.nodes[fromUrl].type is "unexplored"
found[fromUrl] = @data.nodes[fromUrl]
return found
_hasExploredRelationships : (nodeUrl, excludeNodeUrl="") ->
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if fromUrl is nodeUrl
if not (toUrl is excludeNodeUrl) and @visualGraph.nodes[toUrl].type is "explored"
return true
if toUrl is nodeUrl
if not (fromUrl is excludeNodeUrl) and @visualGraph.nodes[fromUrl].type is "explored"
return true
return false
_addRelationship : (from, to, rel, relType=null) ->
@visualGraph.edges[from] ?= {}
@visualGraph.edges[from][to] ?= { length:.5, relationships : {}, directed:true, relType:relType }
if rel != false
@visualGraph.edges[from][to].relationships[rel.getSelf()] = rel
_addUnexploredNode : (baseNode, rel) ->
unexploredUrl = rel.getOtherNodeUrl(baseNode.getSelf())
@visualGraph.nodes[unexploredUrl] ?=
neoNode : @data.nodes[unexploredUrl].node
type : "unexplored"
@_addRelationship(rel.getStartNodeUrl(), rel.getEndNodeUrl(), rel)
_addGroup : (baseNode, relationships, direction) ->
baseNodeUrl = baseNode.getSelf()
nodeCount = 0
grouped = {}
for rel in relationships
nodeUrl = rel.getOtherNodeUrl(baseNodeUrl)
if not @data.nodes[nodeUrl]?
continue
nodeMeta = @data.nodes[nodeUrl]
if not grouped[nodeUrl]?
grouped[nodeUrl] = { node : nodeMeta.node, relationships : []}
nodeCount++
grouped[nodeUrl].relationships.push(rel)
key = "<KEY>
group = @data.groups[key] =
key : key
baseNode : baseNode
grouped : grouped
nodeCount : nodeCount
@visualGraph.nodes[key] =
key : key
type : "group"
group : group
for url, meta of grouped
@data.nodes[url].groups[key] = { group : group, relationships : meta.relationships }
if direction is "outgoing"
@_addRelationship(baseNode.getSelf(), key, false, relationships[0].getType())
else
@_addRelationship(key, baseNode.getSelf(), false, relationships[0].getType())
_removeRelationshipsFor : (node) ->
nodeUrl = node.getSelf()
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if toUrl is nodeUrl or fromUrl is nodeUrl
for url, rel of @visualGraph.edges[fromUrl][toUrl].relationships
delete @data.relationships[rel.getSelf()]
if toUrl is nodeUrl
delete @visualGraph.edges[fromUrl][toUrl]
if @visualGraph.edges[nodeUrl]?
delete @visualGraph.edges[nodeUrl]
_removeRelationshipsInGroup : (group) ->
for url, grouped of group.grouped
node = @data.nodes[url]
if node.groups[group.key]?
delete node.groups[group.key]
for rel in grouped.relationships
delete @data.relationships[rel.getSelf()]
_removeGroup : (group) ->
delete @visualGraph.nodes[group.key]
delete @data.groups[group.key]
if @visualGraph.edges[group.key]?
delete @visualGraph.edges[group.key]
else
if @visualGraph.edges[group.baseNode.getSelf()]? and @visualGraph.edges[group.baseNode.getSelf()][group.key]?
delete @visualGraph.edges[group.baseNode.getSelf()][group.key]
_removeGroupsFor : (node) ->
nodeUrl = node.getSelf()
for key, group of @data.groups
if group.baseNode.getSelf() is nodeUrl
@_removeRelationshipsInGroup group
@_removeGroup group
)
| true | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
[],
() ->
class VisualDataModel
constructor : (@groupingThreshold=5) ->
@clear()
clear : () ->
@groupCount = 0
@visualGraph =
nodes : {}
edges : {}
@data =
relationships : {}
nodes : {}
groups : {}
getVisualGraph : () ->
# XXX
# Arbor.js borks if given a graph with no relationships to render.
# Add a "secret" hack node and relationship if there are no real
# relationships.
# (2011-04-07)
if _(@visualGraph.edges).keys().length == 0
for key, node of @visualGraph.nodes
@visualGraph.nodes["#{key}-SECRET-HACK-NODE"] = { hidden : true }
@visualGraph.edges[key] ?= {}
@visualGraph.edges[key]["#{key}-SECRET-HACK-NODE"] = { hidden : true }
@visualGraph
addNode : (node, relationships, relatedNodes) =>
if not @visualGraph.nodes[node.getSelf()]? or @visualGraph.nodes[node.getSelf()].type isnt "explored"
@ungroup([node])
@ungroup(relatedNodes)
@data.nodes[node.getSelf()] ?= { node : node, groups : {} }
@visualGraph.nodes[node.getSelf()] = { neoNode : node, type : "explored" }
# Add any related nodes to our local cache, if we don't already have them.
for relatedNode in relatedNodes
@data.nodes[relatedNode.getSelf()] ?= { node : relatedNode, groups : {} }
potentialGroups = {incoming:{},outgoing:{}}
for rel in relationships
if @data.relationships[rel.getSelf()]?
continue
@data.relationships[rel.getSelf()] = rel
otherUrl = rel.getOtherNodeUrl(node.getSelf())
dir = if rel.isStartNode(node.getSelf()) then "outgoing" else "incoming"
if not @visualGraph.nodes[otherUrl]?
potentialGroups[dir][rel.getType()] ?= { relationships:[] }
potentialGroups[dir][rel.getType()].relationships.push(rel)
else
@_addRelationship(rel.getStartNodeUrl(), rel.getEndNodeUrl(), rel)
for dir, groups of potentialGroups
for type, group of groups
if group.relationships.length >= @groupingThreshold
@_addGroup node, group.relationships, dir
else
for rel in group.relationships
@_addUnexploredNode node, rel
ungroup : (nodes) ->
for node in nodes
nodeUrl = node.getSelf()
if @data.nodes[nodeUrl]?
meta = @data.nodes[nodeUrl]
for key, groupMeta of meta.groups
group = groupMeta.group
group.nodeCount--
delete group.grouped[nodeUrl]
for rel in groupMeta.relationships
@_addUnexploredNode group.baseNode, rel
if group.nodeCount <= 0
@_removeGroup group
unexplore : (node) ->
nodeUrl = node.getSelf()
if @_isLastExploredNode node
return
if @visualGraph.nodes[nodeUrl]?
visualNode = @visualGraph.nodes[nodeUrl]
visualNode.type = "unexplored"
node.fixed = false
potentiallRemove = @_getUnexploredNodesRelatedTo nodeUrl
for relatedNodeUrl, relatedNodeMeta of potentiallRemove
if not @_hasExploredRelationships relatedNodeUrl, nodeUrl
@removeNode relatedNodeMeta.node
@_removeGroupsFor node
if not @_hasExploredRelationships nodeUrl
@removeNode node
removeNode : (node) ->
nodeUrl = node.getSelf()
delete @visualGraph.nodes[nodeUrl]
delete @data.nodes[nodeUrl]
@_removeRelationshipsFor(node)
_isLastExploredNode : (node) ->
nodeUrl = node.getSelf()
for url, visualNode of @visualGraph.nodes
if visualNode.type == "explored" and url != nodeUrl
return false
return true
_getUnexploredNodesRelatedTo : (nodeUrl) ->
found = []
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if fromUrl is nodeUrl
if @visualGraph.nodes[toUrl].type? and @visualGraph.nodes[toUrl].type is "unexplored"
found[toUrl] = @data.nodes[toUrl]
if toUrl is nodeUrl
if @visualGraph.nodes[fromUrl].type? and @visualGraph.nodes[fromUrl].type is "unexplored"
found[fromUrl] = @data.nodes[fromUrl]
return found
_hasExploredRelationships : (nodeUrl, excludeNodeUrl="") ->
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if fromUrl is nodeUrl
if not (toUrl is excludeNodeUrl) and @visualGraph.nodes[toUrl].type is "explored"
return true
if toUrl is nodeUrl
if not (fromUrl is excludeNodeUrl) and @visualGraph.nodes[fromUrl].type is "explored"
return true
return false
_addRelationship : (from, to, rel, relType=null) ->
@visualGraph.edges[from] ?= {}
@visualGraph.edges[from][to] ?= { length:.5, relationships : {}, directed:true, relType:relType }
if rel != false
@visualGraph.edges[from][to].relationships[rel.getSelf()] = rel
_addUnexploredNode : (baseNode, rel) ->
unexploredUrl = rel.getOtherNodeUrl(baseNode.getSelf())
@visualGraph.nodes[unexploredUrl] ?=
neoNode : @data.nodes[unexploredUrl].node
type : "unexplored"
@_addRelationship(rel.getStartNodeUrl(), rel.getEndNodeUrl(), rel)
_addGroup : (baseNode, relationships, direction) ->
baseNodeUrl = baseNode.getSelf()
nodeCount = 0
grouped = {}
for rel in relationships
nodeUrl = rel.getOtherNodeUrl(baseNodeUrl)
if not @data.nodes[nodeUrl]?
continue
nodeMeta = @data.nodes[nodeUrl]
if not grouped[nodeUrl]?
grouped[nodeUrl] = { node : nodeMeta.node, relationships : []}
nodeCount++
grouped[nodeUrl].relationships.push(rel)
key = "PI:KEY:<KEY>END_PI
group = @data.groups[key] =
key : key
baseNode : baseNode
grouped : grouped
nodeCount : nodeCount
@visualGraph.nodes[key] =
key : key
type : "group"
group : group
for url, meta of grouped
@data.nodes[url].groups[key] = { group : group, relationships : meta.relationships }
if direction is "outgoing"
@_addRelationship(baseNode.getSelf(), key, false, relationships[0].getType())
else
@_addRelationship(key, baseNode.getSelf(), false, relationships[0].getType())
_removeRelationshipsFor : (node) ->
nodeUrl = node.getSelf()
for fromUrl, toMap of @visualGraph.edges
for toUrl, relMeta of toMap
if toUrl is nodeUrl or fromUrl is nodeUrl
for url, rel of @visualGraph.edges[fromUrl][toUrl].relationships
delete @data.relationships[rel.getSelf()]
if toUrl is nodeUrl
delete @visualGraph.edges[fromUrl][toUrl]
if @visualGraph.edges[nodeUrl]?
delete @visualGraph.edges[nodeUrl]
_removeRelationshipsInGroup : (group) ->
for url, grouped of group.grouped
node = @data.nodes[url]
if node.groups[group.key]?
delete node.groups[group.key]
for rel in grouped.relationships
delete @data.relationships[rel.getSelf()]
_removeGroup : (group) ->
delete @visualGraph.nodes[group.key]
delete @data.groups[group.key]
if @visualGraph.edges[group.key]?
delete @visualGraph.edges[group.key]
else
if @visualGraph.edges[group.baseNode.getSelf()]? and @visualGraph.edges[group.baseNode.getSelf()][group.key]?
delete @visualGraph.edges[group.baseNode.getSelf()][group.key]
_removeGroupsFor : (node) ->
nodeUrl = node.getSelf()
for key, group of @data.groups
if group.baseNode.getSelf() is nodeUrl
@_removeRelationshipsInGroup group
@_removeGroup group
)
|
[
{
"context": " = require './scope-name-provider'\n\nCONFIG_KEY = 'file-types'\n\nmodule.exports =\n config:\n $debug:\n ty",
"end": 106,
"score": 0.9880099892616272,
"start": 96,
"tag": "KEY",
"value": "file-types"
}
] | home/.atom/packages/file-types/lib/file-types.coffee | shadowbq/dot.atom | 0 | {basename} = require 'path'
ScopeNameProvider = require './scope-name-provider'
CONFIG_KEY = 'file-types'
module.exports =
config:
$debug:
type: 'boolean'
default: no
$caseSensitive:
type: 'boolean'
default: no
debug: no
snp: new ScopeNameProvider()
_off: []
activate: (state) ->
@_off.push atom.config.observe CONFIG_KEY, (newValue) =>
@loadConfig newValue
for editor in atom.workspace.getTextEditors()
@_tryToSetGrammar editor
@_off.push atom.workspace.observeTextEditors (editor) =>
# TODO: Does this cause a memory leak?
@_off.push editor.onDidChangePath =>
@_tryToSetGrammar editor
@_tryToSetGrammar editor
# Update all editors whenever a grammar registered with us gets loaded
updateEditorGrammars = (g) =>
for scopeName in @snp.getScopeNames() when g.scopeName is scopeName
for editor in atom.workspace.getTextEditors()
@_tryToSetGrammar editor
@_off.push atom.grammars.onDidAddGrammar updateEditorGrammars
@_off.push atom.grammars.onDidUpdateGrammar updateEditorGrammars
deactivate: ->
o?() for o in @_off
serialize: ->
loadConfig: (config = {}) ->
@debug = config.$debug is yes
@caseSensitive = config.$caseSensitive is yes
@snp = new ScopeNameProvider()
for fileType, scopeName of config
# Skip special settings
# (hopefully this won't conflict with any file types)
continue if /^\$/.test fileType
# If `fileType` contains a dot, starts with a caret, or ends with a dollar,
# we assume it is a regular expression matcher
if /(^\^)|(\.)|(\$$)/.test fileType
@snp.registerMatcher fileType, scopeName
else
# Otherwise, we assume it is an extension matcher
@snp.registerExtension fileType, scopeName
@_log @snp
_tryToSetGrammar: (editor) ->
filename = basename editor.getPath()
scopeName = @snp.getScopeName filename, caseSensitive: @caseSensitive
unless scopeName?
@_log "no custom scopeName for #{filename}...skipping"
return
g = atom.grammars.grammarForScopeName scopeName
unless g?
@_log "no grammar for #{scopeName}!?"
return
@_log "setting #{scopeName} as grammar for #{filename}"
editor.setGrammar g
_log: (argv...) ->
return unless @debug
argv.unshift '[file-types]'
console.debug.apply console, argv
| 134293 | {basename} = require 'path'
ScopeNameProvider = require './scope-name-provider'
CONFIG_KEY = '<KEY>'
module.exports =
config:
$debug:
type: 'boolean'
default: no
$caseSensitive:
type: 'boolean'
default: no
debug: no
snp: new ScopeNameProvider()
_off: []
activate: (state) ->
@_off.push atom.config.observe CONFIG_KEY, (newValue) =>
@loadConfig newValue
for editor in atom.workspace.getTextEditors()
@_tryToSetGrammar editor
@_off.push atom.workspace.observeTextEditors (editor) =>
# TODO: Does this cause a memory leak?
@_off.push editor.onDidChangePath =>
@_tryToSetGrammar editor
@_tryToSetGrammar editor
# Update all editors whenever a grammar registered with us gets loaded
updateEditorGrammars = (g) =>
for scopeName in @snp.getScopeNames() when g.scopeName is scopeName
for editor in atom.workspace.getTextEditors()
@_tryToSetGrammar editor
@_off.push atom.grammars.onDidAddGrammar updateEditorGrammars
@_off.push atom.grammars.onDidUpdateGrammar updateEditorGrammars
deactivate: ->
o?() for o in @_off
serialize: ->
loadConfig: (config = {}) ->
@debug = config.$debug is yes
@caseSensitive = config.$caseSensitive is yes
@snp = new ScopeNameProvider()
for fileType, scopeName of config
# Skip special settings
# (hopefully this won't conflict with any file types)
continue if /^\$/.test fileType
# If `fileType` contains a dot, starts with a caret, or ends with a dollar,
# we assume it is a regular expression matcher
if /(^\^)|(\.)|(\$$)/.test fileType
@snp.registerMatcher fileType, scopeName
else
# Otherwise, we assume it is an extension matcher
@snp.registerExtension fileType, scopeName
@_log @snp
_tryToSetGrammar: (editor) ->
filename = basename editor.getPath()
scopeName = @snp.getScopeName filename, caseSensitive: @caseSensitive
unless scopeName?
@_log "no custom scopeName for #{filename}...skipping"
return
g = atom.grammars.grammarForScopeName scopeName
unless g?
@_log "no grammar for #{scopeName}!?"
return
@_log "setting #{scopeName} as grammar for #{filename}"
editor.setGrammar g
_log: (argv...) ->
return unless @debug
argv.unshift '[file-types]'
console.debug.apply console, argv
| true | {basename} = require 'path'
ScopeNameProvider = require './scope-name-provider'
CONFIG_KEY = 'PI:KEY:<KEY>END_PI'
module.exports =
config:
$debug:
type: 'boolean'
default: no
$caseSensitive:
type: 'boolean'
default: no
debug: no
snp: new ScopeNameProvider()
_off: []
activate: (state) ->
@_off.push atom.config.observe CONFIG_KEY, (newValue) =>
@loadConfig newValue
for editor in atom.workspace.getTextEditors()
@_tryToSetGrammar editor
@_off.push atom.workspace.observeTextEditors (editor) =>
# TODO: Does this cause a memory leak?
@_off.push editor.onDidChangePath =>
@_tryToSetGrammar editor
@_tryToSetGrammar editor
# Update all editors whenever a grammar registered with us gets loaded
updateEditorGrammars = (g) =>
for scopeName in @snp.getScopeNames() when g.scopeName is scopeName
for editor in atom.workspace.getTextEditors()
@_tryToSetGrammar editor
@_off.push atom.grammars.onDidAddGrammar updateEditorGrammars
@_off.push atom.grammars.onDidUpdateGrammar updateEditorGrammars
deactivate: ->
o?() for o in @_off
serialize: ->
loadConfig: (config = {}) ->
@debug = config.$debug is yes
@caseSensitive = config.$caseSensitive is yes
@snp = new ScopeNameProvider()
for fileType, scopeName of config
# Skip special settings
# (hopefully this won't conflict with any file types)
continue if /^\$/.test fileType
# If `fileType` contains a dot, starts with a caret, or ends with a dollar,
# we assume it is a regular expression matcher
if /(^\^)|(\.)|(\$$)/.test fileType
@snp.registerMatcher fileType, scopeName
else
# Otherwise, we assume it is an extension matcher
@snp.registerExtension fileType, scopeName
@_log @snp
_tryToSetGrammar: (editor) ->
filename = basename editor.getPath()
scopeName = @snp.getScopeName filename, caseSensitive: @caseSensitive
unless scopeName?
@_log "no custom scopeName for #{filename}...skipping"
return
g = atom.grammars.grammarForScopeName scopeName
unless g?
@_log "no grammar for #{scopeName}!?"
return
@_log "setting #{scopeName} as grammar for #{filename}"
editor.setGrammar g
_log: (argv...) ->
return unless @debug
argv.unshift '[file-types]'
console.debug.apply console, argv
|
[
{
"context": "\trequest.setRequestHeader('X-Auth-Token', Accounts._storedLoginToken())\n\t\terror: (jqXHR, textStatus, errorThrown)",
"end": 3084,
"score": 0.553629994392395,
"start": 3073,
"tag": "KEY",
"value": "storedLogin"
}
] | creator/packages/steedos-object-database/client/subscribe.coffee | steedos/object-server | 10 | subs_objects = new SubsManager()
Creator._subApp = new ReactiveVar({});
lazyLoadAppsMenusId = null;
lazyLoadAppsMenus = ()->
if lazyLoadAppsMenusId
clearTimeout(lazyLoadAppsMenusId)
lazyLoadAppsMenusId = setTimeout ()->
Creator.loadAppsMenus();
lazyLoadAppsMenusId = null;
, 5000
lazyChangeClientObjectsId = null;
lazyChangeClientObjectsApiNames = [];
lazyChangeClientObjects = (objectApiName)->
if lazyChangeClientObjectsId
clearTimeout(lazyChangeClientObjectsId)
lazyChangeClientObjectsApiNames.push(objectApiName)
lazyChangeClientObjectsId = Meteor.setTimeout ()->
_getObjects lazyChangeClientObjectsApiNames, (result)->
if result && result.objects
_.each(result.objects, (objectSchema)->
if _.size(objectSchema.fields) > 0
delete Creator._recordSafeObjectCache[objectSchema.name]
try
oldObject = Creator.getObject(objectSchema.name);
if oldObject
objectSchema = _.extend objectSchema, { list_views: oldObject.list_views }
catch e
console.error(e);
Creator.Objects[objectSchema.name] = objectSchema
Creator.loadObjects objectSchema
Creator.deps.object.changed();
)
, 5000
_changeClientApps = (document)->
lazyLoadAppsMenus();
Creator.Apps[document.code] = document
Creator._subApp.set(Object.assign(document ,{ _id: document.code}))
if Session.get("app_id") == document._id
Creator.deps.app.changed();
_changeClientObjects = (document, oldDocument)->
if !Steedos.isSpaceAdmin() && !document.is_enable
return ;
if !Steedos.isSpaceAdmin() && document.in_development != '0'
return ;
SteedosUI.reloadObject document.name
lazyLoadAppsMenus();
# type = "added"
# if !_.isEmpty(_.findWhere(Creator.objectsByName, {_id: document._id}))
# type = "changed"
lazyChangeClientObjects(document.name)
try
if oldDocument && document && oldDocument.name != document.name
_removeClientObjects(oldDocument);
catch e
console.error(e);
_removeClientObjects = (document)->
_object = _.findWhere Creator.objectsByName, {_id: document._id}
Creator.removeObject(_object?.name)
# Creator.removeCollection(_object?.name)
if Session.get("object_name") == _object?.name
FlowRouter.go("/")
Creator.deps.object.changed();
_removeClientApps = (document)->
delete Creator.Apps[document.code]
Creator._subApp.set(Object.assign({}, document, {visible: false, _id: document.code}))
if Session.get("app_id") == document.code || Session.get("app_id") == document._id
Session.set("app_id", null)
FlowRouter.go("/")
#_loadObjectsPremissions = ()->
# Creator.bootstrap()
reloadObject = () ->
Setup.bootstrap(Steedos.getSpaceId());
Meteor.setTimeout ()->
Creator.deps.object.changed()
, 3000
_getObject = (objectId, callback)->
if !objectId || !_.isString(objectId)
return
spaceId = Session.get("spaceId")
$.ajax
type: "get"
url: Steedos.absoluteUrl "/api/bootstrap/#{spaceId}/#{objectId}"
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) ->
if _.isFunction(callback)
callback(result)
_getObjects = (objectApiNames, callback)->
objectApiNames = _.compact(_.uniq(objectApiNames))
if !objectApiNames || !_.isArray(objectApiNames) || _.isEmpty(objectApiNames)
return
spaceId = Session.get("spaceId")
$.ajax
type: "get"
url: Steedos.absoluteUrl "/api/bootstrap/#{spaceId}/#{objectApiNames.join(',')}"
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) ->
if _.isFunction(callback)
callback(result)
# Meteor.startup ()->
# Tracker.autorun (c)->
# spaceId = Session.get("spaceId")
# if spaceId
# # subs_objects.subscribe "creator_apps", spaceId
# subs_objects.subscribe "creator_objects", spaceId
# subs_objects.subscribe "creator_reload_object_logs", spaceId
Tracker.autorun (c) ->
if Creator.bootstrapLoaded.get()
# objects_observer_init = false
# Creator.getCollection("objects").find({is_deleted: {$ne: true}}).observe {
# # added: (newDocument)->
# # if objects_observer_init
# # _changeClientObjects newDocument
# changed: (newDocument, oldDocument)->
# if objects_observer_init
# if !Steedos.isSpaceAdmin() && (newDocument.is_enable == false || newDocument.in_development != '0')
# _removeClientObjects newDocument
# else
# _changeClientObjects newDocument, oldDocument
# # Meteor.setTimeout ()->
# # _changeClientObjects newDocument
# # , 5000
# removed: (oldDocument)->
# if objects_observer_init
# _removeClientObjects oldDocument
# }
# objects_observer_init = true
apps_observer_init = false
Creator.getCollection("apps").find({is_creator: true}).observe {
added: (newDocument)->
if apps_observer_init
_changeClientApps(newDocument)
changed: (newDocument, oldDocument)->
if apps_observer_init
_changeClientApps(newDocument)
removed: (oldDocument)->
if apps_observer_init
_removeClientApps(oldDocument)
}
apps_observer_init = true
# reload_objects_observer_init = false
# Creator.getCollection("_object_reload_logs").find({}).observe {
# added: (newDocument)->
# if reload_objects_observer_init
# _changeClientObjects({name: newDocument.object_name})
# }
# reload_objects_observer_init = true
# Meteor.startup ()->
# Tracker.autorun (c)->
# spaceId = Session.get("spaceId")
# if spaceId
# subs_objects.subscribe "publish_object_layouts", spaceId
# Tracker.autorun (c) ->
# if Creator.bootstrapLoaded.get()
# layouts_observer_init = false
# Creator.getCollection("object_layouts").find().observe {
# changed: (newDocument, oldDocument)->
# if layouts_observer_init
# _object = Creator.getObject(newDocument.object_name)
# if _object
# _changeClientObjects _object
# removed: (oldDocument)->
# if layouts_observer_init
# _object = Creator.getObject(oldDocument.object_name)
# if _object
# _changeClientObjects {_id: _object._id, name: oldDocument.object_name}
# }
# layouts_observer_init = true | 62658 | subs_objects = new SubsManager()
Creator._subApp = new ReactiveVar({});
lazyLoadAppsMenusId = null;
lazyLoadAppsMenus = ()->
if lazyLoadAppsMenusId
clearTimeout(lazyLoadAppsMenusId)
lazyLoadAppsMenusId = setTimeout ()->
Creator.loadAppsMenus();
lazyLoadAppsMenusId = null;
, 5000
lazyChangeClientObjectsId = null;
lazyChangeClientObjectsApiNames = [];
lazyChangeClientObjects = (objectApiName)->
if lazyChangeClientObjectsId
clearTimeout(lazyChangeClientObjectsId)
lazyChangeClientObjectsApiNames.push(objectApiName)
lazyChangeClientObjectsId = Meteor.setTimeout ()->
_getObjects lazyChangeClientObjectsApiNames, (result)->
if result && result.objects
_.each(result.objects, (objectSchema)->
if _.size(objectSchema.fields) > 0
delete Creator._recordSafeObjectCache[objectSchema.name]
try
oldObject = Creator.getObject(objectSchema.name);
if oldObject
objectSchema = _.extend objectSchema, { list_views: oldObject.list_views }
catch e
console.error(e);
Creator.Objects[objectSchema.name] = objectSchema
Creator.loadObjects objectSchema
Creator.deps.object.changed();
)
, 5000
_changeClientApps = (document)->
lazyLoadAppsMenus();
Creator.Apps[document.code] = document
Creator._subApp.set(Object.assign(document ,{ _id: document.code}))
if Session.get("app_id") == document._id
Creator.deps.app.changed();
_changeClientObjects = (document, oldDocument)->
if !Steedos.isSpaceAdmin() && !document.is_enable
return ;
if !Steedos.isSpaceAdmin() && document.in_development != '0'
return ;
SteedosUI.reloadObject document.name
lazyLoadAppsMenus();
# type = "added"
# if !_.isEmpty(_.findWhere(Creator.objectsByName, {_id: document._id}))
# type = "changed"
lazyChangeClientObjects(document.name)
try
if oldDocument && document && oldDocument.name != document.name
_removeClientObjects(oldDocument);
catch e
console.error(e);
_removeClientObjects = (document)->
_object = _.findWhere Creator.objectsByName, {_id: document._id}
Creator.removeObject(_object?.name)
# Creator.removeCollection(_object?.name)
if Session.get("object_name") == _object?.name
FlowRouter.go("/")
Creator.deps.object.changed();
_removeClientApps = (document)->
delete Creator.Apps[document.code]
Creator._subApp.set(Object.assign({}, document, {visible: false, _id: document.code}))
if Session.get("app_id") == document.code || Session.get("app_id") == document._id
Session.set("app_id", null)
FlowRouter.go("/")
#_loadObjectsPremissions = ()->
# Creator.bootstrap()
reloadObject = () ->
Setup.bootstrap(Steedos.getSpaceId());
Meteor.setTimeout ()->
Creator.deps.object.changed()
, 3000
_getObject = (objectId, callback)->
if !objectId || !_.isString(objectId)
return
spaceId = Session.get("spaceId")
$.ajax
type: "get"
url: Steedos.absoluteUrl "/api/bootstrap/#{spaceId}/#{objectId}"
dataType: "json"
beforeSend: (request) ->
request.setRequestHeader('X-User-Id', Meteor.userId())
request.setRequestHeader('X-Auth-Token', Accounts._<KEY>Token())
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) ->
if _.isFunction(callback)
callback(result)
_getObjects = (objectApiNames, callback)->
objectApiNames = _.compact(_.uniq(objectApiNames))
if !objectApiNames || !_.isArray(objectApiNames) || _.isEmpty(objectApiNames)
return
spaceId = Session.get("spaceId")
$.ajax
type: "get"
url: Steedos.absoluteUrl "/api/bootstrap/#{spaceId}/#{objectApiNames.join(',')}"
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) ->
if _.isFunction(callback)
callback(result)
# Meteor.startup ()->
# Tracker.autorun (c)->
# spaceId = Session.get("spaceId")
# if spaceId
# # subs_objects.subscribe "creator_apps", spaceId
# subs_objects.subscribe "creator_objects", spaceId
# subs_objects.subscribe "creator_reload_object_logs", spaceId
Tracker.autorun (c) ->
if Creator.bootstrapLoaded.get()
# objects_observer_init = false
# Creator.getCollection("objects").find({is_deleted: {$ne: true}}).observe {
# # added: (newDocument)->
# # if objects_observer_init
# # _changeClientObjects newDocument
# changed: (newDocument, oldDocument)->
# if objects_observer_init
# if !Steedos.isSpaceAdmin() && (newDocument.is_enable == false || newDocument.in_development != '0')
# _removeClientObjects newDocument
# else
# _changeClientObjects newDocument, oldDocument
# # Meteor.setTimeout ()->
# # _changeClientObjects newDocument
# # , 5000
# removed: (oldDocument)->
# if objects_observer_init
# _removeClientObjects oldDocument
# }
# objects_observer_init = true
apps_observer_init = false
Creator.getCollection("apps").find({is_creator: true}).observe {
added: (newDocument)->
if apps_observer_init
_changeClientApps(newDocument)
changed: (newDocument, oldDocument)->
if apps_observer_init
_changeClientApps(newDocument)
removed: (oldDocument)->
if apps_observer_init
_removeClientApps(oldDocument)
}
apps_observer_init = true
# reload_objects_observer_init = false
# Creator.getCollection("_object_reload_logs").find({}).observe {
# added: (newDocument)->
# if reload_objects_observer_init
# _changeClientObjects({name: newDocument.object_name})
# }
# reload_objects_observer_init = true
# Meteor.startup ()->
# Tracker.autorun (c)->
# spaceId = Session.get("spaceId")
# if spaceId
# subs_objects.subscribe "publish_object_layouts", spaceId
# Tracker.autorun (c) ->
# if Creator.bootstrapLoaded.get()
# layouts_observer_init = false
# Creator.getCollection("object_layouts").find().observe {
# changed: (newDocument, oldDocument)->
# if layouts_observer_init
# _object = Creator.getObject(newDocument.object_name)
# if _object
# _changeClientObjects _object
# removed: (oldDocument)->
# if layouts_observer_init
# _object = Creator.getObject(oldDocument.object_name)
# if _object
# _changeClientObjects {_id: _object._id, name: oldDocument.object_name}
# }
# layouts_observer_init = true | true | subs_objects = new SubsManager()
Creator._subApp = new ReactiveVar({});
lazyLoadAppsMenusId = null;
lazyLoadAppsMenus = ()->
if lazyLoadAppsMenusId
clearTimeout(lazyLoadAppsMenusId)
lazyLoadAppsMenusId = setTimeout ()->
Creator.loadAppsMenus();
lazyLoadAppsMenusId = null;
, 5000
lazyChangeClientObjectsId = null;
lazyChangeClientObjectsApiNames = [];
lazyChangeClientObjects = (objectApiName)->
if lazyChangeClientObjectsId
clearTimeout(lazyChangeClientObjectsId)
lazyChangeClientObjectsApiNames.push(objectApiName)
lazyChangeClientObjectsId = Meteor.setTimeout ()->
_getObjects lazyChangeClientObjectsApiNames, (result)->
if result && result.objects
_.each(result.objects, (objectSchema)->
if _.size(objectSchema.fields) > 0
delete Creator._recordSafeObjectCache[objectSchema.name]
try
oldObject = Creator.getObject(objectSchema.name);
if oldObject
objectSchema = _.extend objectSchema, { list_views: oldObject.list_views }
catch e
console.error(e);
Creator.Objects[objectSchema.name] = objectSchema
Creator.loadObjects objectSchema
Creator.deps.object.changed();
)
, 5000
_changeClientApps = (document)->
lazyLoadAppsMenus();
Creator.Apps[document.code] = document
Creator._subApp.set(Object.assign(document ,{ _id: document.code}))
if Session.get("app_id") == document._id
Creator.deps.app.changed();
_changeClientObjects = (document, oldDocument)->
if !Steedos.isSpaceAdmin() && !document.is_enable
return ;
if !Steedos.isSpaceAdmin() && document.in_development != '0'
return ;
SteedosUI.reloadObject document.name
lazyLoadAppsMenus();
# type = "added"
# if !_.isEmpty(_.findWhere(Creator.objectsByName, {_id: document._id}))
# type = "changed"
lazyChangeClientObjects(document.name)
try
if oldDocument && document && oldDocument.name != document.name
_removeClientObjects(oldDocument);
catch e
console.error(e);
_removeClientObjects = (document)->
_object = _.findWhere Creator.objectsByName, {_id: document._id}
Creator.removeObject(_object?.name)
# Creator.removeCollection(_object?.name)
if Session.get("object_name") == _object?.name
FlowRouter.go("/")
Creator.deps.object.changed();
_removeClientApps = (document)->
delete Creator.Apps[document.code]
Creator._subApp.set(Object.assign({}, document, {visible: false, _id: document.code}))
if Session.get("app_id") == document.code || Session.get("app_id") == document._id
Session.set("app_id", null)
FlowRouter.go("/")
#_loadObjectsPremissions = ()->
# Creator.bootstrap()
reloadObject = () ->
Setup.bootstrap(Steedos.getSpaceId());
Meteor.setTimeout ()->
Creator.deps.object.changed()
, 3000
_getObject = (objectId, callback)->
if !objectId || !_.isString(objectId)
return
spaceId = Session.get("spaceId")
$.ajax
type: "get"
url: Steedos.absoluteUrl "/api/bootstrap/#{spaceId}/#{objectId}"
dataType: "json"
beforeSend: (request) ->
request.setRequestHeader('X-User-Id', Meteor.userId())
request.setRequestHeader('X-Auth-Token', Accounts._PI:KEY:<KEY>END_PIToken())
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) ->
if _.isFunction(callback)
callback(result)
_getObjects = (objectApiNames, callback)->
objectApiNames = _.compact(_.uniq(objectApiNames))
if !objectApiNames || !_.isArray(objectApiNames) || _.isEmpty(objectApiNames)
return
spaceId = Session.get("spaceId")
$.ajax
type: "get"
url: Steedos.absoluteUrl "/api/bootstrap/#{spaceId}/#{objectApiNames.join(',')}"
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) ->
if _.isFunction(callback)
callback(result)
# Meteor.startup ()->
# Tracker.autorun (c)->
# spaceId = Session.get("spaceId")
# if spaceId
# # subs_objects.subscribe "creator_apps", spaceId
# subs_objects.subscribe "creator_objects", spaceId
# subs_objects.subscribe "creator_reload_object_logs", spaceId
Tracker.autorun (c) ->
if Creator.bootstrapLoaded.get()
# objects_observer_init = false
# Creator.getCollection("objects").find({is_deleted: {$ne: true}}).observe {
# # added: (newDocument)->
# # if objects_observer_init
# # _changeClientObjects newDocument
# changed: (newDocument, oldDocument)->
# if objects_observer_init
# if !Steedos.isSpaceAdmin() && (newDocument.is_enable == false || newDocument.in_development != '0')
# _removeClientObjects newDocument
# else
# _changeClientObjects newDocument, oldDocument
# # Meteor.setTimeout ()->
# # _changeClientObjects newDocument
# # , 5000
# removed: (oldDocument)->
# if objects_observer_init
# _removeClientObjects oldDocument
# }
# objects_observer_init = true
apps_observer_init = false
Creator.getCollection("apps").find({is_creator: true}).observe {
added: (newDocument)->
if apps_observer_init
_changeClientApps(newDocument)
changed: (newDocument, oldDocument)->
if apps_observer_init
_changeClientApps(newDocument)
removed: (oldDocument)->
if apps_observer_init
_removeClientApps(oldDocument)
}
apps_observer_init = true
# reload_objects_observer_init = false
# Creator.getCollection("_object_reload_logs").find({}).observe {
# added: (newDocument)->
# if reload_objects_observer_init
# _changeClientObjects({name: newDocument.object_name})
# }
# reload_objects_observer_init = true
# Meteor.startup ()->
# Tracker.autorun (c)->
# spaceId = Session.get("spaceId")
# if spaceId
# subs_objects.subscribe "publish_object_layouts", spaceId
# Tracker.autorun (c) ->
# if Creator.bootstrapLoaded.get()
# layouts_observer_init = false
# Creator.getCollection("object_layouts").find().observe {
# changed: (newDocument, oldDocument)->
# if layouts_observer_init
# _object = Creator.getObject(newDocument.object_name)
# if _object
# _changeClientObjects _object
# removed: (oldDocument)->
# if layouts_observer_init
# _object = Creator.getObject(oldDocument.object_name)
# if _object
# _changeClientObjects {_id: _object._id, name: oldDocument.object_name}
# }
# layouts_observer_init = true |
[
{
"context": " @fileoverview Rule to prefer ES6 to CJS\n# @author Jamund Ferguson\n###\n\n# import docsUrl from '../docsUrl'\n\nEXPORT_M",
"end": 72,
"score": 0.999858021736145,
"start": 57,
"tag": "NAME",
"value": "Jamund Ferguson"
}
] | src/rules/no-commonjs.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Rule to prefer ES6 to CJS
# @author Jamund Ferguson
###
# import docsUrl from '../docsUrl'
EXPORT_MESSAGE = 'Expected "export" or "export default"'
IMPORT_MESSAGE = 'Expected "import" instead of "require()"'
normalizeLegacyOptions = (options) ->
return allowPrimitiveModules: yes if (
options.indexOf('allow-primitive-modules') >= 0
)
options[0] or {}
allowPrimitive = (node, options) ->
return no unless options.allowPrimitiveModules
return no unless (
node.parent.type is 'AssignmentExpression' and node is node.parent.left
)
node.parent.right.type isnt 'ObjectExpression'
allowRequire = (node, options) -> options.allowRequire
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
schemaString = enum: ['allow-primitive-modules']
schemaObject =
type: 'object'
properties:
allowPrimitiveModules: type: 'boolean'
allowRequire: type: 'boolean'
additionalProperties: no
module.exports =
meta:
docs:
# url: docsUrl 'no-commonjs'
url: ''
schema:
anyOf: [
type: 'array'
items: [schemaString]
additionalItems: no
,
type: 'array'
items: [schemaObject]
additionalItems: no
]
create: (context) ->
options = normalizeLegacyOptions context.options
MemberExpression: (node) ->
# module.exports
if node.object.name is 'module' and node.property.name is 'exports'
return if allowPrimitive node, options
context.report {node, message: EXPORT_MESSAGE}
# exports.
if node.object.name is 'exports'
isInScope =
context
.getScope()
.variables.some (variable) -> variable.name is 'exports'
context.report {node, message: EXPORT_MESSAGE} unless isInScope
CallExpression: (call) ->
return unless context.getScope().type is 'module'
return unless call.parent.type in [
'ExpressionStatement'
'VariableDeclarator'
'AssignmentExpression'
]
return unless call.callee.type is 'Identifier'
return unless call.callee.name is 'require'
return unless call.arguments.length is 1
module = call.arguments[0]
return unless module.type is 'Literal'
return unless typeof module.value is 'string'
return if allowRequire call, options
# keeping it simple: all 1-string-arg `require` calls are reported
context.report
node: call.callee
message: IMPORT_MESSAGE
| 212023 | ###*
# @fileoverview Rule to prefer ES6 to CJS
# @author <NAME>
###
# import docsUrl from '../docsUrl'
EXPORT_MESSAGE = 'Expected "export" or "export default"'
IMPORT_MESSAGE = 'Expected "import" instead of "require()"'
normalizeLegacyOptions = (options) ->
return allowPrimitiveModules: yes if (
options.indexOf('allow-primitive-modules') >= 0
)
options[0] or {}
allowPrimitive = (node, options) ->
return no unless options.allowPrimitiveModules
return no unless (
node.parent.type is 'AssignmentExpression' and node is node.parent.left
)
node.parent.right.type isnt 'ObjectExpression'
allowRequire = (node, options) -> options.allowRequire
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
schemaString = enum: ['allow-primitive-modules']
schemaObject =
type: 'object'
properties:
allowPrimitiveModules: type: 'boolean'
allowRequire: type: 'boolean'
additionalProperties: no
module.exports =
meta:
docs:
# url: docsUrl 'no-commonjs'
url: ''
schema:
anyOf: [
type: 'array'
items: [schemaString]
additionalItems: no
,
type: 'array'
items: [schemaObject]
additionalItems: no
]
create: (context) ->
options = normalizeLegacyOptions context.options
MemberExpression: (node) ->
# module.exports
if node.object.name is 'module' and node.property.name is 'exports'
return if allowPrimitive node, options
context.report {node, message: EXPORT_MESSAGE}
# exports.
if node.object.name is 'exports'
isInScope =
context
.getScope()
.variables.some (variable) -> variable.name is 'exports'
context.report {node, message: EXPORT_MESSAGE} unless isInScope
CallExpression: (call) ->
return unless context.getScope().type is 'module'
return unless call.parent.type in [
'ExpressionStatement'
'VariableDeclarator'
'AssignmentExpression'
]
return unless call.callee.type is 'Identifier'
return unless call.callee.name is 'require'
return unless call.arguments.length is 1
module = call.arguments[0]
return unless module.type is 'Literal'
return unless typeof module.value is 'string'
return if allowRequire call, options
# keeping it simple: all 1-string-arg `require` calls are reported
context.report
node: call.callee
message: IMPORT_MESSAGE
| true | ###*
# @fileoverview Rule to prefer ES6 to CJS
# @author PI:NAME:<NAME>END_PI
###
# import docsUrl from '../docsUrl'
EXPORT_MESSAGE = 'Expected "export" or "export default"'
IMPORT_MESSAGE = 'Expected "import" instead of "require()"'
normalizeLegacyOptions = (options) ->
return allowPrimitiveModules: yes if (
options.indexOf('allow-primitive-modules') >= 0
)
options[0] or {}
allowPrimitive = (node, options) ->
return no unless options.allowPrimitiveModules
return no unless (
node.parent.type is 'AssignmentExpression' and node is node.parent.left
)
node.parent.right.type isnt 'ObjectExpression'
allowRequire = (node, options) -> options.allowRequire
#------------------------------------------------------------------------------
# Rule Definition
#------------------------------------------------------------------------------
schemaString = enum: ['allow-primitive-modules']
schemaObject =
type: 'object'
properties:
allowPrimitiveModules: type: 'boolean'
allowRequire: type: 'boolean'
additionalProperties: no
module.exports =
meta:
docs:
# url: docsUrl 'no-commonjs'
url: ''
schema:
anyOf: [
type: 'array'
items: [schemaString]
additionalItems: no
,
type: 'array'
items: [schemaObject]
additionalItems: no
]
create: (context) ->
options = normalizeLegacyOptions context.options
MemberExpression: (node) ->
# module.exports
if node.object.name is 'module' and node.property.name is 'exports'
return if allowPrimitive node, options
context.report {node, message: EXPORT_MESSAGE}
# exports.
if node.object.name is 'exports'
isInScope =
context
.getScope()
.variables.some (variable) -> variable.name is 'exports'
context.report {node, message: EXPORT_MESSAGE} unless isInScope
CallExpression: (call) ->
return unless context.getScope().type is 'module'
return unless call.parent.type in [
'ExpressionStatement'
'VariableDeclarator'
'AssignmentExpression'
]
return unless call.callee.type is 'Identifier'
return unless call.callee.name is 'require'
return unless call.arguments.length is 1
module = call.arguments[0]
return unless module.type is 'Literal'
return unless typeof module.value is 'string'
return if allowRequire call, options
# keeping it simple: all 1-string-arg `require` calls are reported
context.report
node: call.callee
message: IMPORT_MESSAGE
|
[
{
"context": " [{a:1, b:2, c:3}, {a:1, b:2, name: \"shokai\"}]\n done()\n\n ts.write {a:1, b:2, c:",
"end": 7249,
"score": 0.9624879956245422,
"start": 7243,
"tag": "USERNAME",
"value": "shokai"
},
{
"context": " ts.write {a:1}\n ts.write {a:1, b:2, name: \"shokai\"}\n\n it 'should not return Tuple if canceled', ",
"end": 7390,
"score": 0.8907143473625183,
"start": 7384,
"tag": "USERNAME",
"value": "shokai"
},
{
"context": ":3}, {expire: 1}\n ts.write new Tuple({name: \"shokai\"}), {expire: 3}\n ts.write {foo: \"bar\"}\n\n ",
"end": 8312,
"score": 0.6181234121322632,
"start": 8306,
"tag": "NAME",
"value": "shokai"
}
] | tests/test_tuplespace.coffee | Hykwtakumin/Pakaruland | 0 | process.env.NODE_ENV = 'test'
path = require 'path'
assert = require 'assert'
async = require 'async'
Linda = require(path.resolve())
TupleSpace = Linda.TupleSpace
Tuple = Linda.Tuple
describe 'instance of "TupleSpace"', ->
it 'should have property "name"', ->
assert.equal new TupleSpace("foo").name, 'foo'
it 'should have property "callbacks"', ->
ts = new TupleSpace()
assert.ok ts.hasOwnProperty('callbacks')
assert.ok ts.callbacks instanceof Array
it 'should have method "create_callback_id"', ->
assert.equal typeof new TupleSpace()['create_callback_id'], 'function'
it 'should have property "size"', ->
assert.ok new TupleSpace().hasOwnProperty('size')
describe 'property "size"', ->
it 'should return number of Tuples', ->
assert.equal new TupleSpace().size, 0
it 'should have method "write"', ->
assert.equal typeof new TupleSpace()['write'], 'function'
it 'should have method "cancel"', ->
assert.equal typeof new TupleSpace()['cancel'], 'function'
it 'should have method "check_expire"', ->
assert.equal typeof new TupleSpace()['check_expire'], 'function'
describe 'method "write"', ->
it 'should store HashTuples', ->
ts = new TupleSpace("foo")
assert.equal ts.size, 0
ts.write {a:1, b:2}
ts.write {a:1, b:3}
assert.equal ts.size, 2
it 'should not store if not valid Tuple', ->
ts = new TupleSpace("foo")
assert.equal ts.size, 0
ts.write "foobar"
ts.write [1,2]
ts.write null
assert.equal ts.size, 0
it 'should have method "read"', ->
assert.equal typeof new TupleSpace()['read'], 'function'
it 'should have method "take"', ->
assert.equal typeof new TupleSpace()['take'], 'function'
describe 'method "read" with callback', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.read {}, ->
assert.ok cid > 0
it 'should return matched Tuple', (done) ->
ts = new TupleSpace
ts.write {a:1, b:2, c:3}
ts.read {a:1, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
done()
it 'should wait if Tuple not found', (done) ->
ts = new TupleSpace
async.parallel [
(async_done) ->
ts.read {a:1, d:4}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3, d:4}
async_done(null, tuple)
(async_done) ->
ts.read {sensor: "light"}, (err, tuple) ->
assert.deepEqual tuple.data, {sensor: "light", value: 80}
async_done(null, tuple)
(async_done) ->
ts.read {}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
], (err, results) ->
done()
assert.equal ts.callbacks.length, 3
assert.equal ts.size, 0
ts.write {a:1, b:2, c:3}
ts.write {a:1, b:2, c:3, d:4}
ts.write {sensor: "light", value: 80}
assert.equal ts.callbacks.length, 0
assert.equal ts.size, 3
it 'should return matched Tuple if using queue mode', (done) ->
ts = new TupleSpace()
ts.write {foo: 'bar', n: 1}
ts.write {foo: 'bar', n: 2}
ts.write {foo: 'bar', n: 3}
ts.option({sort: 'queue'}).read {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: 'bar', n: 1}
assert.equal ts.size, 3
ts.read {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: 'bar', n: 3}
assert.equal ts.size, 3
done()
it 'should not return Tuple if canceled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.read {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.read {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
assert.equal ts.callbacks.length, 0
describe 'method "take" with callback', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.take {}, ->
assert.ok cid > 0
it 'should return matched Tuple and delete', (done) ->
ts = new TupleSpace
ts.write {a:1, b:2, c:3}
ts.take {a:1, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
assert.equal ts.size, 0
done()
it 'should return matched Tuple and delete if using queue mode', (done) ->
ts = new TupleSpace()
ts.write {n: 1, foo: 'bar'}
ts.write {n: 2, foo: 'bar'}
ts.write {n: 3, foo: 'bar'}
ts.option({sort: 'queue'}).take {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {n: 1, foo: 'bar'}
ts.take {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {n: 3, foo: 'bar'}
assert.equal ts.size, 1
done()
it 'should wait if Tuple not found', (done) ->
ts = new TupleSpace
async.parallel [
(async_done) ->
ts.take {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
(async_done) ->
ts.take {foo: "bar"}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: "bar"}
async_done(null, tuple)
(async_done) ->
ts.take {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:300}
async_done(null, tuple)
], (err, results) ->
assert.equal ts.callbacks.length, 0
done()
assert.equal ts.callbacks.length, 3
assert.equal ts.size, 0
ts.write {a:1, b:2, c:3}
ts.write {foo: "bar"}
ts.write {a:1, b:2, c:300}
assert.equal ts.callbacks.length, 0
assert.equal ts.size, 0
it 'should not return Tuple if cacneled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.take {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.take {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
assert.equal ts.callbacks.length, 0
describe 'method "watch"', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.watch {}, ->
assert.ok cid > 0
it 'should return Tuple when write(tuple)', (done) ->
ts = new TupleSpace
results = []
ts.watch {a:1, b:2}, (err, tuple) ->
results.push tuple.data
if results.length is 2
assert.deepEqual results,
[{a:1, b:2, c:3}, {a:1, b:2, name: "shokai"}]
done()
ts.write {a:1, b:2, c:3}
ts.write {foo: "bar"}
ts.write {a:1}
ts.write {a:1, b:2, name: "shokai"}
it 'should not return Tuple if canceled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.watch {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.watch {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
describe 'method "check_expire"', ->
it 'should delete expired tuples', (done) ->
@timeout(5000)
ts = new TupleSpace
ts.write {a:1, b:2}, {expire: 3}
ts.write {a:1, b:2, c:3}, {expire: 1}
ts.write new Tuple({name: "shokai"}), {expire: 3}
ts.write {foo: "bar"}
assert.equal ts.size, 4
async.parallel [
(async_done) ->
ts.read {a:1, b:2, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
(async_done) ->
setTimeout ->
ts.check_expire()
assert.equal ts.size, 3
ts.read {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, tuple)
, 2000
(async_done) ->
setTimeout ->
ts.check_expire()
assert.equal ts.size, 1
ts.read {}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: "bar"}
async_done(null, tuple)
, 4000
], (err, results) ->
done()
| 137663 | process.env.NODE_ENV = 'test'
path = require 'path'
assert = require 'assert'
async = require 'async'
Linda = require(path.resolve())
TupleSpace = Linda.TupleSpace
Tuple = Linda.Tuple
describe 'instance of "TupleSpace"', ->
it 'should have property "name"', ->
assert.equal new TupleSpace("foo").name, 'foo'
it 'should have property "callbacks"', ->
ts = new TupleSpace()
assert.ok ts.hasOwnProperty('callbacks')
assert.ok ts.callbacks instanceof Array
it 'should have method "create_callback_id"', ->
assert.equal typeof new TupleSpace()['create_callback_id'], 'function'
it 'should have property "size"', ->
assert.ok new TupleSpace().hasOwnProperty('size')
describe 'property "size"', ->
it 'should return number of Tuples', ->
assert.equal new TupleSpace().size, 0
it 'should have method "write"', ->
assert.equal typeof new TupleSpace()['write'], 'function'
it 'should have method "cancel"', ->
assert.equal typeof new TupleSpace()['cancel'], 'function'
it 'should have method "check_expire"', ->
assert.equal typeof new TupleSpace()['check_expire'], 'function'
describe 'method "write"', ->
it 'should store HashTuples', ->
ts = new TupleSpace("foo")
assert.equal ts.size, 0
ts.write {a:1, b:2}
ts.write {a:1, b:3}
assert.equal ts.size, 2
it 'should not store if not valid Tuple', ->
ts = new TupleSpace("foo")
assert.equal ts.size, 0
ts.write "foobar"
ts.write [1,2]
ts.write null
assert.equal ts.size, 0
it 'should have method "read"', ->
assert.equal typeof new TupleSpace()['read'], 'function'
it 'should have method "take"', ->
assert.equal typeof new TupleSpace()['take'], 'function'
describe 'method "read" with callback', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.read {}, ->
assert.ok cid > 0
it 'should return matched Tuple', (done) ->
ts = new TupleSpace
ts.write {a:1, b:2, c:3}
ts.read {a:1, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
done()
it 'should wait if Tuple not found', (done) ->
ts = new TupleSpace
async.parallel [
(async_done) ->
ts.read {a:1, d:4}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3, d:4}
async_done(null, tuple)
(async_done) ->
ts.read {sensor: "light"}, (err, tuple) ->
assert.deepEqual tuple.data, {sensor: "light", value: 80}
async_done(null, tuple)
(async_done) ->
ts.read {}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
], (err, results) ->
done()
assert.equal ts.callbacks.length, 3
assert.equal ts.size, 0
ts.write {a:1, b:2, c:3}
ts.write {a:1, b:2, c:3, d:4}
ts.write {sensor: "light", value: 80}
assert.equal ts.callbacks.length, 0
assert.equal ts.size, 3
it 'should return matched Tuple if using queue mode', (done) ->
ts = new TupleSpace()
ts.write {foo: 'bar', n: 1}
ts.write {foo: 'bar', n: 2}
ts.write {foo: 'bar', n: 3}
ts.option({sort: 'queue'}).read {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: 'bar', n: 1}
assert.equal ts.size, 3
ts.read {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: 'bar', n: 3}
assert.equal ts.size, 3
done()
it 'should not return Tuple if canceled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.read {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.read {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
assert.equal ts.callbacks.length, 0
describe 'method "take" with callback', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.take {}, ->
assert.ok cid > 0
it 'should return matched Tuple and delete', (done) ->
ts = new TupleSpace
ts.write {a:1, b:2, c:3}
ts.take {a:1, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
assert.equal ts.size, 0
done()
it 'should return matched Tuple and delete if using queue mode', (done) ->
ts = new TupleSpace()
ts.write {n: 1, foo: 'bar'}
ts.write {n: 2, foo: 'bar'}
ts.write {n: 3, foo: 'bar'}
ts.option({sort: 'queue'}).take {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {n: 1, foo: 'bar'}
ts.take {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {n: 3, foo: 'bar'}
assert.equal ts.size, 1
done()
it 'should wait if Tuple not found', (done) ->
ts = new TupleSpace
async.parallel [
(async_done) ->
ts.take {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
(async_done) ->
ts.take {foo: "bar"}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: "bar"}
async_done(null, tuple)
(async_done) ->
ts.take {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:300}
async_done(null, tuple)
], (err, results) ->
assert.equal ts.callbacks.length, 0
done()
assert.equal ts.callbacks.length, 3
assert.equal ts.size, 0
ts.write {a:1, b:2, c:3}
ts.write {foo: "bar"}
ts.write {a:1, b:2, c:300}
assert.equal ts.callbacks.length, 0
assert.equal ts.size, 0
it 'should not return Tuple if cacneled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.take {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.take {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
assert.equal ts.callbacks.length, 0
describe 'method "watch"', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.watch {}, ->
assert.ok cid > 0
it 'should return Tuple when write(tuple)', (done) ->
ts = new TupleSpace
results = []
ts.watch {a:1, b:2}, (err, tuple) ->
results.push tuple.data
if results.length is 2
assert.deepEqual results,
[{a:1, b:2, c:3}, {a:1, b:2, name: "shokai"}]
done()
ts.write {a:1, b:2, c:3}
ts.write {foo: "bar"}
ts.write {a:1}
ts.write {a:1, b:2, name: "shokai"}
it 'should not return Tuple if canceled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.watch {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.watch {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
describe 'method "check_expire"', ->
it 'should delete expired tuples', (done) ->
@timeout(5000)
ts = new TupleSpace
ts.write {a:1, b:2}, {expire: 3}
ts.write {a:1, b:2, c:3}, {expire: 1}
ts.write new Tuple({name: "<NAME>"}), {expire: 3}
ts.write {foo: "bar"}
assert.equal ts.size, 4
async.parallel [
(async_done) ->
ts.read {a:1, b:2, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
(async_done) ->
setTimeout ->
ts.check_expire()
assert.equal ts.size, 3
ts.read {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, tuple)
, 2000
(async_done) ->
setTimeout ->
ts.check_expire()
assert.equal ts.size, 1
ts.read {}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: "bar"}
async_done(null, tuple)
, 4000
], (err, results) ->
done()
| true | process.env.NODE_ENV = 'test'
path = require 'path'
assert = require 'assert'
async = require 'async'
Linda = require(path.resolve())
TupleSpace = Linda.TupleSpace
Tuple = Linda.Tuple
describe 'instance of "TupleSpace"', ->
it 'should have property "name"', ->
assert.equal new TupleSpace("foo").name, 'foo'
it 'should have property "callbacks"', ->
ts = new TupleSpace()
assert.ok ts.hasOwnProperty('callbacks')
assert.ok ts.callbacks instanceof Array
it 'should have method "create_callback_id"', ->
assert.equal typeof new TupleSpace()['create_callback_id'], 'function'
it 'should have property "size"', ->
assert.ok new TupleSpace().hasOwnProperty('size')
describe 'property "size"', ->
it 'should return number of Tuples', ->
assert.equal new TupleSpace().size, 0
it 'should have method "write"', ->
assert.equal typeof new TupleSpace()['write'], 'function'
it 'should have method "cancel"', ->
assert.equal typeof new TupleSpace()['cancel'], 'function'
it 'should have method "check_expire"', ->
assert.equal typeof new TupleSpace()['check_expire'], 'function'
describe 'method "write"', ->
it 'should store HashTuples', ->
ts = new TupleSpace("foo")
assert.equal ts.size, 0
ts.write {a:1, b:2}
ts.write {a:1, b:3}
assert.equal ts.size, 2
it 'should not store if not valid Tuple', ->
ts = new TupleSpace("foo")
assert.equal ts.size, 0
ts.write "foobar"
ts.write [1,2]
ts.write null
assert.equal ts.size, 0
it 'should have method "read"', ->
assert.equal typeof new TupleSpace()['read'], 'function'
it 'should have method "take"', ->
assert.equal typeof new TupleSpace()['take'], 'function'
describe 'method "read" with callback', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.read {}, ->
assert.ok cid > 0
it 'should return matched Tuple', (done) ->
ts = new TupleSpace
ts.write {a:1, b:2, c:3}
ts.read {a:1, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
done()
it 'should wait if Tuple not found', (done) ->
ts = new TupleSpace
async.parallel [
(async_done) ->
ts.read {a:1, d:4}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3, d:4}
async_done(null, tuple)
(async_done) ->
ts.read {sensor: "light"}, (err, tuple) ->
assert.deepEqual tuple.data, {sensor: "light", value: 80}
async_done(null, tuple)
(async_done) ->
ts.read {}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
], (err, results) ->
done()
assert.equal ts.callbacks.length, 3
assert.equal ts.size, 0
ts.write {a:1, b:2, c:3}
ts.write {a:1, b:2, c:3, d:4}
ts.write {sensor: "light", value: 80}
assert.equal ts.callbacks.length, 0
assert.equal ts.size, 3
it 'should return matched Tuple if using queue mode', (done) ->
ts = new TupleSpace()
ts.write {foo: 'bar', n: 1}
ts.write {foo: 'bar', n: 2}
ts.write {foo: 'bar', n: 3}
ts.option({sort: 'queue'}).read {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: 'bar', n: 1}
assert.equal ts.size, 3
ts.read {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: 'bar', n: 3}
assert.equal ts.size, 3
done()
it 'should not return Tuple if canceled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.read {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.read {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
assert.equal ts.callbacks.length, 0
describe 'method "take" with callback', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.take {}, ->
assert.ok cid > 0
it 'should return matched Tuple and delete', (done) ->
ts = new TupleSpace
ts.write {a:1, b:2, c:3}
ts.take {a:1, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
assert.equal ts.size, 0
done()
it 'should return matched Tuple and delete if using queue mode', (done) ->
ts = new TupleSpace()
ts.write {n: 1, foo: 'bar'}
ts.write {n: 2, foo: 'bar'}
ts.write {n: 3, foo: 'bar'}
ts.option({sort: 'queue'}).take {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {n: 1, foo: 'bar'}
ts.take {foo: 'bar'}, (err, tuple) ->
assert.deepEqual tuple.data, {n: 3, foo: 'bar'}
assert.equal ts.size, 1
done()
it 'should wait if Tuple not found', (done) ->
ts = new TupleSpace
async.parallel [
(async_done) ->
ts.take {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
(async_done) ->
ts.take {foo: "bar"}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: "bar"}
async_done(null, tuple)
(async_done) ->
ts.take {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:300}
async_done(null, tuple)
], (err, results) ->
assert.equal ts.callbacks.length, 0
done()
assert.equal ts.callbacks.length, 3
assert.equal ts.size, 0
ts.write {a:1, b:2, c:3}
ts.write {foo: "bar"}
ts.write {a:1, b:2, c:300}
assert.equal ts.callbacks.length, 0
assert.equal ts.size, 0
it 'should not return Tuple if cacneled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.take {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.take {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
assert.equal ts.callbacks.length, 0
describe 'method "watch"', ->
it 'should return cancel_id', ->
ts = new TupleSpace
cid = ts.watch {}, ->
assert.ok cid > 0
it 'should return Tuple when write(tuple)', (done) ->
ts = new TupleSpace
results = []
ts.watch {a:1, b:2}, (err, tuple) ->
results.push tuple.data
if results.length is 2
assert.deepEqual results,
[{a:1, b:2, c:3}, {a:1, b:2, name: "shokai"}]
done()
ts.write {a:1, b:2, c:3}
ts.write {foo: "bar"}
ts.write {a:1}
ts.write {a:1, b:2, name: "shokai"}
it 'should not return Tuple if canceled', (done) ->
ts = new TupleSpace
cid = null
async.parallel [
(async_done) ->
cid_ = ts.watch {a:1}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, cid_)
(async_done) ->
cid = ts.watch {}, (err, tuple) ->
assert.equal err, "cancel"
async_done(null, cid)
], (err, callback_ids) ->
assert.notEqual callback_ids[0], callback_ids[1]
done()
assert.equal ts.callbacks.length, 2
ts.cancel cid
assert.equal ts.callbacks.length, 1
ts.write {a:1, b:2}
describe 'method "check_expire"', ->
it 'should delete expired tuples', (done) ->
@timeout(5000)
ts = new TupleSpace
ts.write {a:1, b:2}, {expire: 3}
ts.write {a:1, b:2, c:3}, {expire: 1}
ts.write new Tuple({name: "PI:NAME:<NAME>END_PI"}), {expire: 3}
ts.write {foo: "bar"}
assert.equal ts.size, 4
async.parallel [
(async_done) ->
ts.read {a:1, b:2, c:3}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2, c:3}
async_done(null, tuple)
(async_done) ->
setTimeout ->
ts.check_expire()
assert.equal ts.size, 3
ts.read {a:1, b:2}, (err, tuple) ->
assert.deepEqual tuple.data, {a:1, b:2}
async_done(null, tuple)
, 2000
(async_done) ->
setTimeout ->
ts.check_expire()
assert.equal ts.size, 1
ts.read {}, (err, tuple) ->
assert.deepEqual tuple.data, {foo: "bar"}
async_done(null, tuple)
, 4000
], (err, results) ->
done()
|
[
{
"context": "Markdown snippets for Leanpub authors\n# Created by Maksim Surguy\n# Enjoy!\n\n'.source.gfm':\n 'lp-image':\n 'prefi",
"end": 66,
"score": 0.9998762011528015,
"start": 53,
"tag": "NAME",
"value": "Maksim Surguy"
}
] | home/.atom/packages/leanpub-snippets/snippets/leanpub.cson | shadowbq/dot.atom | 0 | # Markdown snippets for Leanpub authors
# Created by Maksim Surguy
# Enjoy!
'.source.gfm':
'lp-image':
'prefix' : 'lp-img'
'body': ''
'lp-code' :
'prefix' : 'lp-code'
'body': '{title="Listing $1", lang=${2:html}, linenos=off}\n~~~~~~~\n$3\n~~~~~~~'
'lp-aside':
'prefix' : 'lp-aside'
'body': 'A> ## $1\nA>\nA> $2'
'lp-info':
'prefix' : 'lp-info'
'body': 'I> ## $1\nI>\nI> $2'
'lp-error':
'prefix' : 'lp-error'
'body': 'E> ## $1\nE>\nE> $2'
'lp-question':
'prefix' : 'lp-question'
'body': 'Q> ## $1\nQ>\nQ> $2'
'lp-tip':
'prefix' : 'lp-tip'
'body': 'T> ## $1\nT>\nT> $2'
'lp-warning':
'prefix' : 'lp-warning'
'body': 'W> ## $1\nW>\nW> $2'
'lp-discussion':
'prefix' : 'lp-discussion'
'body': 'D> ## $1\nD>\nD> $2'
'lp-exercise':
'prefix' : 'lp-exercise'
'body': 'X> ## $1\nX>\nX> $2' | 140183 | # Markdown snippets for Leanpub authors
# Created by <NAME>
# Enjoy!
'.source.gfm':
'lp-image':
'prefix' : 'lp-img'
'body': ''
'lp-code' :
'prefix' : 'lp-code'
'body': '{title="Listing $1", lang=${2:html}, linenos=off}\n~~~~~~~\n$3\n~~~~~~~'
'lp-aside':
'prefix' : 'lp-aside'
'body': 'A> ## $1\nA>\nA> $2'
'lp-info':
'prefix' : 'lp-info'
'body': 'I> ## $1\nI>\nI> $2'
'lp-error':
'prefix' : 'lp-error'
'body': 'E> ## $1\nE>\nE> $2'
'lp-question':
'prefix' : 'lp-question'
'body': 'Q> ## $1\nQ>\nQ> $2'
'lp-tip':
'prefix' : 'lp-tip'
'body': 'T> ## $1\nT>\nT> $2'
'lp-warning':
'prefix' : 'lp-warning'
'body': 'W> ## $1\nW>\nW> $2'
'lp-discussion':
'prefix' : 'lp-discussion'
'body': 'D> ## $1\nD>\nD> $2'
'lp-exercise':
'prefix' : 'lp-exercise'
'body': 'X> ## $1\nX>\nX> $2' | true | # Markdown snippets for Leanpub authors
# Created by PI:NAME:<NAME>END_PI
# Enjoy!
'.source.gfm':
'lp-image':
'prefix' : 'lp-img'
'body': ''
'lp-code' :
'prefix' : 'lp-code'
'body': '{title="Listing $1", lang=${2:html}, linenos=off}\n~~~~~~~\n$3\n~~~~~~~'
'lp-aside':
'prefix' : 'lp-aside'
'body': 'A> ## $1\nA>\nA> $2'
'lp-info':
'prefix' : 'lp-info'
'body': 'I> ## $1\nI>\nI> $2'
'lp-error':
'prefix' : 'lp-error'
'body': 'E> ## $1\nE>\nE> $2'
'lp-question':
'prefix' : 'lp-question'
'body': 'Q> ## $1\nQ>\nQ> $2'
'lp-tip':
'prefix' : 'lp-tip'
'body': 'T> ## $1\nT>\nT> $2'
'lp-warning':
'prefix' : 'lp-warning'
'body': 'W> ## $1\nW>\nW> $2'
'lp-discussion':
'prefix' : 'lp-discussion'
'body': 'D> ## $1\nD>\nD> $2'
'lp-exercise':
'prefix' : 'lp-exercise'
'body': 'X> ## $1\nX>\nX> $2' |
[
{
"context": ", resource: {\n resourceType: 'Users', name: 'foo'\n })\n readed = crud.fhir_read_resource(plv8",
"end": 726,
"score": 0.9867081046104431,
"start": 723,
"tag": "NAME",
"value": "foo"
},
{
"context": "\n toUpdate = copy(readed)\n toUpdate.name = 'bar'\n\n crud.fhir_update_resource(plv8, resource: t",
"end": 871,
"score": 0.9769460558891296,
"start": 868,
"tag": "NAME",
"value": "bar"
}
] | test/fhir/history_spec.coffee | micabe/fhirbase | 0 | plv8 = require('../../plpl/src/plv8')
crud = require('../../src/fhir/crud')
history = require('../../src/fhir/history')
schema = require('../../src/core/schema')
assert = require('assert')
copy = (x)-> JSON.parse(JSON.stringify(x))
describe 'CORE: History spec', ->
before ->
schema.fhir_create_storage(plv8, resourceType: 'Users')
schema.fhir_create_storage(plv8, resourceType: 'Patient')
beforeEach ->
plv8.execute("SET plv8.start_proc = 'plv8_init'")
schema.fhir_truncate_storage(plv8, resourceType: 'Users')
schema.fhir_truncate_storage(plv8, resourceType: 'Patient')
it 'resource history', ->
created = crud.fhir_create_resource(plv8, resource: {
resourceType: 'Users', name: 'foo'
})
readed = crud.fhir_read_resource(plv8, {id: created.id, resourceType: 'Users'})
toUpdate = copy(readed)
toUpdate.name = 'bar'
crud.fhir_update_resource(plv8, resource: toUpdate)
deleted = crud.fhir_delete_resource(plv8, {
id: readed.id, resourceType: 'Users'
})
hx = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(hx.total, 3)
assert.equal(hx.entry.length, 3)
assert.deepEqual(
hx.entry.map((entry) -> entry.request.method),
['DELETE', 'PUT', 'POST']
)
it 'resource history with _count', ->
created = crud.fhir_create_resource(plv8, resource: {resourceType: 'Users'})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
crud.fhir_update_resource(plv8, resource: copy(readed))
fullHistory = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(fullHistory.total, 2)
assert.equal(fullHistory.entry.length, 2)
limitedHistory = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_count=1'
})
assert.equal(limitedHistory.total, 1)
assert.equal(limitedHistory.entry.length, 1)
it 'instance history with _since', ->
for id in ['id1', 'id2']
crud.fhir_create_resource(plv8, allowId: true, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'First']}]})
crud.fhir_update_resource(plv8, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'Second']}]})
crud.fhir_update_resource(plv8, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'Third']}]})
count = plv8.execute("select count(*) from patient")
assert.equal(count[0].count, 2)
sinceHistory = history.fhir_resource_history(plv8, {
id: 'id1',
resourceType: 'Patient',
queryString: '_since=2015-07-15'
})
assert.equal(sinceHistory.total, 3)
assert.equal(sinceHistory.entry.length, 3)
for e in sinceHistory.entry
assert(e.resource.id, 'id1')
it 'resource history _since and _before', ->
created = crud.fhir_create_resource(plv8, resource: {resourceType: 'Users'})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
crud.fhir_update_resource(plv8, resource: copy(readed))
plv8.execute(
"UPDATE users_history
SET valid_from = '01-Jan-1970'::timestamp with time zone
WHERE id = '#{readed.id}'"
)
crud.fhir_update_resource(plv8, resource: copy(readed))
fullHistory = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(fullHistory.total, 3)
assert.equal(fullHistory.entry.length, 3)
historySince = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_since=2016-01-01'
})
assert.equal(historySince.total, 1)
assert.equal(historySince.entry.length, 1)
historyBefore = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_before=2016-01-01'
})
assert.equal(historyBefore.total, 2)
assert.equal(historyBefore.entry.length, 2)
it 'parse_history_params', ->
[res, errors] = history.parse_history_params('_since=2010&_count=10')
assert.deepEqual(res, {_since: '2010-01-01', _count: 10})
it 'resource type history', ->
schema.fhir_truncate_storage(plv8, resourceType: 'Users')
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u1'})
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u2'})
created = crud.fhir_create_resource(plv8, resource: {
resourceType: 'Users', name: 'foo'
})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
toUpdate = copy(readed)
toUpdate.name = 'bar'
crud.fhir_update_resource(plv8, resource: toUpdate)
deleted = crud.fhir_delete_resource(plv8, {
id: readed.id, resourceType: 'Users'
})
hx = history.fhir_resource_type_history(plv8, resourceType: 'Users')
assert.equal(hx.total, 5)
assert.deepEqual(
hx.entry.map((entry) -> entry.request.method),
['DELETE', 'PUT', 'POST', 'POST', 'POST']
)
hx = history.fhir_resource_type_history(
plv8,
resourceType: 'Users',
queryString: '_count=2'
)
assert.equal(hx.total, 2)
it 'resource type history with _since and _before', ->
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u1'})
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u2'})
plv8.execute(
"UPDATE users_history
SET valid_from = '01-Jan-1970'::timestamp with time zone"
)
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u3'})
fullHistory = history.fhir_resource_type_history(plv8, {
resourceType: 'Users'
})
assert.equal(fullHistory.total, 3)
assert.equal(fullHistory.entry.length, 3)
historySince = history.fhir_resource_type_history(plv8, {
resourceType: 'Users',
queryString: '_since=2016-01-01'
})
assert.equal(historySince.total, 1)
assert.equal(historySince.entry.length, 1)
historyBefore = history.fhir_resource_type_history(plv8, {
resourceType: 'Users',
queryString: '_before=2016-01-01'
})
assert.equal(historyBefore.total, 2)
assert.equal(historyBefore.entry.length, 2)
| 109051 | plv8 = require('../../plpl/src/plv8')
crud = require('../../src/fhir/crud')
history = require('../../src/fhir/history')
schema = require('../../src/core/schema')
assert = require('assert')
copy = (x)-> JSON.parse(JSON.stringify(x))
describe 'CORE: History spec', ->
before ->
schema.fhir_create_storage(plv8, resourceType: 'Users')
schema.fhir_create_storage(plv8, resourceType: 'Patient')
beforeEach ->
plv8.execute("SET plv8.start_proc = 'plv8_init'")
schema.fhir_truncate_storage(plv8, resourceType: 'Users')
schema.fhir_truncate_storage(plv8, resourceType: 'Patient')
it 'resource history', ->
created = crud.fhir_create_resource(plv8, resource: {
resourceType: 'Users', name: '<NAME>'
})
readed = crud.fhir_read_resource(plv8, {id: created.id, resourceType: 'Users'})
toUpdate = copy(readed)
toUpdate.name = '<NAME>'
crud.fhir_update_resource(plv8, resource: toUpdate)
deleted = crud.fhir_delete_resource(plv8, {
id: readed.id, resourceType: 'Users'
})
hx = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(hx.total, 3)
assert.equal(hx.entry.length, 3)
assert.deepEqual(
hx.entry.map((entry) -> entry.request.method),
['DELETE', 'PUT', 'POST']
)
it 'resource history with _count', ->
created = crud.fhir_create_resource(plv8, resource: {resourceType: 'Users'})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
crud.fhir_update_resource(plv8, resource: copy(readed))
fullHistory = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(fullHistory.total, 2)
assert.equal(fullHistory.entry.length, 2)
limitedHistory = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_count=1'
})
assert.equal(limitedHistory.total, 1)
assert.equal(limitedHistory.entry.length, 1)
it 'instance history with _since', ->
for id in ['id1', 'id2']
crud.fhir_create_resource(plv8, allowId: true, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'First']}]})
crud.fhir_update_resource(plv8, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'Second']}]})
crud.fhir_update_resource(plv8, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'Third']}]})
count = plv8.execute("select count(*) from patient")
assert.equal(count[0].count, 2)
sinceHistory = history.fhir_resource_history(plv8, {
id: 'id1',
resourceType: 'Patient',
queryString: '_since=2015-07-15'
})
assert.equal(sinceHistory.total, 3)
assert.equal(sinceHistory.entry.length, 3)
for e in sinceHistory.entry
assert(e.resource.id, 'id1')
it 'resource history _since and _before', ->
created = crud.fhir_create_resource(plv8, resource: {resourceType: 'Users'})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
crud.fhir_update_resource(plv8, resource: copy(readed))
plv8.execute(
"UPDATE users_history
SET valid_from = '01-Jan-1970'::timestamp with time zone
WHERE id = '#{readed.id}'"
)
crud.fhir_update_resource(plv8, resource: copy(readed))
fullHistory = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(fullHistory.total, 3)
assert.equal(fullHistory.entry.length, 3)
historySince = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_since=2016-01-01'
})
assert.equal(historySince.total, 1)
assert.equal(historySince.entry.length, 1)
historyBefore = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_before=2016-01-01'
})
assert.equal(historyBefore.total, 2)
assert.equal(historyBefore.entry.length, 2)
it 'parse_history_params', ->
[res, errors] = history.parse_history_params('_since=2010&_count=10')
assert.deepEqual(res, {_since: '2010-01-01', _count: 10})
it 'resource type history', ->
schema.fhir_truncate_storage(plv8, resourceType: 'Users')
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u1'})
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u2'})
created = crud.fhir_create_resource(plv8, resource: {
resourceType: 'Users', name: 'foo'
})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
toUpdate = copy(readed)
toUpdate.name = 'bar'
crud.fhir_update_resource(plv8, resource: toUpdate)
deleted = crud.fhir_delete_resource(plv8, {
id: readed.id, resourceType: 'Users'
})
hx = history.fhir_resource_type_history(plv8, resourceType: 'Users')
assert.equal(hx.total, 5)
assert.deepEqual(
hx.entry.map((entry) -> entry.request.method),
['DELETE', 'PUT', 'POST', 'POST', 'POST']
)
hx = history.fhir_resource_type_history(
plv8,
resourceType: 'Users',
queryString: '_count=2'
)
assert.equal(hx.total, 2)
it 'resource type history with _since and _before', ->
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u1'})
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u2'})
plv8.execute(
"UPDATE users_history
SET valid_from = '01-Jan-1970'::timestamp with time zone"
)
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u3'})
fullHistory = history.fhir_resource_type_history(plv8, {
resourceType: 'Users'
})
assert.equal(fullHistory.total, 3)
assert.equal(fullHistory.entry.length, 3)
historySince = history.fhir_resource_type_history(plv8, {
resourceType: 'Users',
queryString: '_since=2016-01-01'
})
assert.equal(historySince.total, 1)
assert.equal(historySince.entry.length, 1)
historyBefore = history.fhir_resource_type_history(plv8, {
resourceType: 'Users',
queryString: '_before=2016-01-01'
})
assert.equal(historyBefore.total, 2)
assert.equal(historyBefore.entry.length, 2)
| true | plv8 = require('../../plpl/src/plv8')
crud = require('../../src/fhir/crud')
history = require('../../src/fhir/history')
schema = require('../../src/core/schema')
assert = require('assert')
copy = (x)-> JSON.parse(JSON.stringify(x))
describe 'CORE: History spec', ->
before ->
schema.fhir_create_storage(plv8, resourceType: 'Users')
schema.fhir_create_storage(plv8, resourceType: 'Patient')
beforeEach ->
plv8.execute("SET plv8.start_proc = 'plv8_init'")
schema.fhir_truncate_storage(plv8, resourceType: 'Users')
schema.fhir_truncate_storage(plv8, resourceType: 'Patient')
it 'resource history', ->
created = crud.fhir_create_resource(plv8, resource: {
resourceType: 'Users', name: 'PI:NAME:<NAME>END_PI'
})
readed = crud.fhir_read_resource(plv8, {id: created.id, resourceType: 'Users'})
toUpdate = copy(readed)
toUpdate.name = 'PI:NAME:<NAME>END_PI'
crud.fhir_update_resource(plv8, resource: toUpdate)
deleted = crud.fhir_delete_resource(plv8, {
id: readed.id, resourceType: 'Users'
})
hx = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(hx.total, 3)
assert.equal(hx.entry.length, 3)
assert.deepEqual(
hx.entry.map((entry) -> entry.request.method),
['DELETE', 'PUT', 'POST']
)
it 'resource history with _count', ->
created = crud.fhir_create_resource(plv8, resource: {resourceType: 'Users'})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
crud.fhir_update_resource(plv8, resource: copy(readed))
fullHistory = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(fullHistory.total, 2)
assert.equal(fullHistory.entry.length, 2)
limitedHistory = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_count=1'
})
assert.equal(limitedHistory.total, 1)
assert.equal(limitedHistory.entry.length, 1)
it 'instance history with _since', ->
for id in ['id1', 'id2']
crud.fhir_create_resource(plv8, allowId: true, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'First']}]})
crud.fhir_update_resource(plv8, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'Second']}]})
crud.fhir_update_resource(plv8, resource: {
resourceType: 'Patient',
id: id,
name: [{family: [id + 'Third']}]})
count = plv8.execute("select count(*) from patient")
assert.equal(count[0].count, 2)
sinceHistory = history.fhir_resource_history(plv8, {
id: 'id1',
resourceType: 'Patient',
queryString: '_since=2015-07-15'
})
assert.equal(sinceHistory.total, 3)
assert.equal(sinceHistory.entry.length, 3)
for e in sinceHistory.entry
assert(e.resource.id, 'id1')
it 'resource history _since and _before', ->
created = crud.fhir_create_resource(plv8, resource: {resourceType: 'Users'})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
crud.fhir_update_resource(plv8, resource: copy(readed))
plv8.execute(
"UPDATE users_history
SET valid_from = '01-Jan-1970'::timestamp with time zone
WHERE id = '#{readed.id}'"
)
crud.fhir_update_resource(plv8, resource: copy(readed))
fullHistory = history.fhir_resource_history(plv8, {
id: readed.id, resourceType: 'Users'
})
assert.equal(fullHistory.total, 3)
assert.equal(fullHistory.entry.length, 3)
historySince = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_since=2016-01-01'
})
assert.equal(historySince.total, 1)
assert.equal(historySince.entry.length, 1)
historyBefore = history.fhir_resource_history(plv8, {
id: readed.id,
resourceType: 'Users',
queryString: '_before=2016-01-01'
})
assert.equal(historyBefore.total, 2)
assert.equal(historyBefore.entry.length, 2)
it 'parse_history_params', ->
[res, errors] = history.parse_history_params('_since=2010&_count=10')
assert.deepEqual(res, {_since: '2010-01-01', _count: 10})
it 'resource type history', ->
schema.fhir_truncate_storage(plv8, resourceType: 'Users')
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u1'})
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u2'})
created = crud.fhir_create_resource(plv8, resource: {
resourceType: 'Users', name: 'foo'
})
readed = crud.fhir_read_resource(plv8, {
id: created.id, resourceType: 'Users'
})
toUpdate = copy(readed)
toUpdate.name = 'bar'
crud.fhir_update_resource(plv8, resource: toUpdate)
deleted = crud.fhir_delete_resource(plv8, {
id: readed.id, resourceType: 'Users'
})
hx = history.fhir_resource_type_history(plv8, resourceType: 'Users')
assert.equal(hx.total, 5)
assert.deepEqual(
hx.entry.map((entry) -> entry.request.method),
['DELETE', 'PUT', 'POST', 'POST', 'POST']
)
hx = history.fhir_resource_type_history(
plv8,
resourceType: 'Users',
queryString: '_count=2'
)
assert.equal(hx.total, 2)
it 'resource type history with _since and _before', ->
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u1'})
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u2'})
plv8.execute(
"UPDATE users_history
SET valid_from = '01-Jan-1970'::timestamp with time zone"
)
crud.fhir_create_resource(plv8, resource: {resourceType: 'Users', name: 'u3'})
fullHistory = history.fhir_resource_type_history(plv8, {
resourceType: 'Users'
})
assert.equal(fullHistory.total, 3)
assert.equal(fullHistory.entry.length, 3)
historySince = history.fhir_resource_type_history(plv8, {
resourceType: 'Users',
queryString: '_since=2016-01-01'
})
assert.equal(historySince.total, 1)
assert.equal(historySince.entry.length, 1)
historyBefore = history.fhir_resource_type_history(plv8, {
resourceType: 'Users',
queryString: '_before=2016-01-01'
})
assert.equal(historyBefore.total, 2)
assert.equal(historyBefore.entry.length, 2)
|
[
{
"context": "export default\n name: 'Venus'\n type: 'planet'\n radius: 6051.8\n mass: 48.685",
"end": 29,
"score": 0.9991111159324646,
"start": 24,
"tag": "NAME",
"value": "Venus"
}
] | src/data/bodies/venus.coffee | skepticalimagination/solaris-model | 5 | export default
name: 'Venus'
type: 'planet'
radius: 6051.8
mass: 48.685e23
tilt: 177.3
elements:
format: 'jpl-1800-2050'
base: {a: 0.72333566, e: 0.00677672, i: 3.39467605, L: 181.97909950, lp: 131.60246718, node: 76.67984255}
cy: {a: 0.00000390, e: -0.00004107, i: -0.00078890, L: 58517.81538729, lp: 0.00268329, node: -0.27769418}
| 14572 | export default
name: '<NAME>'
type: 'planet'
radius: 6051.8
mass: 48.685e23
tilt: 177.3
elements:
format: 'jpl-1800-2050'
base: {a: 0.72333566, e: 0.00677672, i: 3.39467605, L: 181.97909950, lp: 131.60246718, node: 76.67984255}
cy: {a: 0.00000390, e: -0.00004107, i: -0.00078890, L: 58517.81538729, lp: 0.00268329, node: -0.27769418}
| true | export default
name: 'PI:NAME:<NAME>END_PI'
type: 'planet'
radius: 6051.8
mass: 48.685e23
tilt: 177.3
elements:
format: 'jpl-1800-2050'
base: {a: 0.72333566, e: 0.00677672, i: 3.39467605, L: 181.97909950, lp: 131.60246718, node: 76.67984255}
cy: {a: 0.00000390, e: -0.00004107, i: -0.00078890, L: 58517.81538729, lp: 0.00268329, node: -0.27769418}
|
[
{
"context": " node: @req.node\n nodeUser: nodeUser\n actor: @req.actor\n unl",
"end": 13756,
"score": 0.8831756114959717,
"start": 13748,
"tag": "USERNAME",
"value": "nodeUser"
},
{
"context": "For /user/.../subscriptions\n #\n # <item id=\"koski@buddycloud.com\">\n # <query xmlns=\"http://jabber.org/protoc",
"end": 21883,
"score": 0.9998747706413269,
"start": 21863,
"tag": "EMAIL",
"value": "koski@buddycloud.com"
},
{
"context": " node: @req.node\n user: @req.user\n affiliation: @affiliation",
"end": 35547,
"score": 0.810100793838501,
"start": 35547,
"tag": "USERNAME",
"value": ""
},
{
"context": " node: @req.node\n user: @req.user\n affiliation: @affiliation\n ",
"end": 35557,
"score": 0.9041866064071655,
"start": 35553,
"tag": "USERNAME",
"value": "user"
},
{
"context": " node: @req.node\n user: user\n subscription: 'pending'\n ",
"end": 47026,
"score": 0.8508977890014648,
"start": 47022,
"tag": "NAME",
"value": "user"
},
{
"context": " node: @req.node\n user: user\n affiliation: 'outcast'\n ",
"end": 47247,
"score": 0.8279341459274292,
"start": 47243,
"tag": "NAME",
"value": "user"
}
] | src/local/operations.coffee | surevine/buddycloud-server | 0 | logger = require('../logger').makeLogger 'local/operations'
{inspect} = require('util')
{getNodeUser, getNodeType} = require('../util')
async = require('async')
uuid = require('node-uuid')
errors = require('../errors')
NS = require('../xmpp/ns')
{normalizeItem} = require('../normalize')
{Element} = require('node-xmpp')
runTransaction = null
exports.setModel = (model) ->
runTransaction = model.transaction
exports.checkCreateNode = null
defaultConfiguration = (user) ->
posts:
title: "#{user} Channel Posts"
description: "A buddycloud channel"
channelType: "personal"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "publisher"
status:
title: "#{user} Status Updates"
description: "M000D"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/previous':
title: "#{user} Previous Location"
description: "Where #{user} has been before"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/current':
title: "#{user} Current Location"
description: "Where #{user} is at now"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/next':
title: "#{user} Next Location"
description: "Where #{user} intends to go"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
subscriptions:
title: "#{user} Subscriptions"
description: "Browse my interests"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
# user is "topic@domain" string
defaultTopicConfiguration = (user) =>
posts:
title: "#{user} Topic Channel"
description: "All about #{user.split('@')?[0]}"
channelType: "topic"
accessModel: "open"
publishModel: "subscribers"
defaultAffiliation: "member"
NODE_OWNER_TYPE_REGEXP = /^\/user\/([^\/]+)\/?(.*)/
AFFILIATIONS = [
'outcast', 'none', 'member',
'publisher', 'moderator', 'owner'
]
isAffiliationAtLeast = (affiliation1, affiliation2) ->
i1 = AFFILIATIONS.indexOf(affiliation1)
i2 = AFFILIATIONS.indexOf(affiliation2)
if i2 < 0
false
else
i1 >= i2
canModerate = (affiliation) ->
affiliation is 'owner' or affiliation is 'moderator'
###
# Base Operations
###
##
# Is created with options from the request
#
# Implementations set result
class Operation
constructor: (@router, @req) ->
if @req.node? and
(m = @req.node.match(NODE_OWNER_TYPE_REGEXP)) and
m[2] is 'subscriptions'
# Affords for specialized items handling in RetrieveItems and Publish
@subscriptionsNodeOwner = m[1]
run: (cb) ->
cb new errorsFeature.NotImplemented("Operation defined but not yet implemented")
class ModelOperation extends Operation
run: (cb) ->
runTransaction (err, t) =>
if err
return cb err
opName = @req.operation or @constructor?.name or "?"
@transaction t, (err, results) ->
if err
logger.warn "Transaction #{opName} rollback: #{err}"
t.rollback ->
cb err
else
t.commit ->
logger.debug "Transaction #{opName} committed"
cb null, results
# Must be implemented by subclass
transaction: (t, cb) ->
cb null
class PrivilegedOperation extends ModelOperation
transaction: (t, cb) ->
async.waterfall [ (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
@checkAccessModel t, cb2
, (cb2) =>
@checkRequiredAffiliation t, cb2
], (err) =>
if err
return cb err
@privilegedTransaction t, cb
fetchActorAffiliation: (t, cb) ->
unless @req.node
return cb()
if @req.actor.indexOf('@') >= 0
t.getAffiliation @req.node, @req.actor, (err, affiliation) =>
if err
return cb err
@actorAffiliation = affiliation or 'none'
else
# actor no user? check if listener!
t.getListenerAffiliations @req.node, @req.actor, (err, affiliations) =>
if err
return cb err
@actorAffiliation = 'none'
for affiliation in affiliations
if affiliation isnt @actorAffiliation and
isAffiliationAtLeast affiliation, @actorAffiliation
@actorAffiliation = affiliation
if canModerate @actorAffiliation
# Moderators get to see everything
@filterSubscription = @filterSubscriptionModerator
@filterAffiliation = @filterAffiliationModerator
cb()
fetchNodeConfig: (t, cb) ->
unless @req.node
return cb()
t.getConfig @req.node, (err, config) =>
if err
return cb err
@nodeConfig = config
cb()
checkAccessModel: (t, cb) ->
# Deny any outcast
if @actorAffiliation is 'outcast'
return cb new errors.Forbidden("Outcast")
# Set default according to node config
unless @requiredAffiliation
if @nodeConfig.accessModel is 'open'
# Open nodes allow anyone
@requiredAffiliation = 'none'
else
# For all other access models, actor has to be member
@requiredAffiliation = 'member'
cb()
checkRequiredAffiliation: (t, cb) ->
if @requiredAffiliation?.constructor is Function
requiredAffiliation = @requiredAffiliation()
else
requiredAffiliation = @requiredAffiliation
if not requiredAffiliation? or
isAffiliationAtLeast @actorAffiliation, requiredAffiliation
cb()
else
cb new errors.Forbidden("Requires affiliation #{requiredAffiliation} (you are #{@actorAffiliation})")
# Used by Publish operation
checkPublishModel: (t, cb) ->
pass = false
switch @nodeConfig.publishModel
when 'open'
pass = true
when 'members'
pass = isAffiliationAtLeast @actorAffiliation, 'member'
when 'publishers'
pass = isAffiliationAtLeast @actorAffiliation, 'publisher'
else
# Owners can always post
pass = (@actorAffiliation is 'owner')
if pass
cb()
else if @nodeConfig.publishModel is 'subscribers'
# Special handling because subscription state must be
# fetched
t.getSubscription @req.node, @req.actor, (err, subscription) ->
if !err and subscription is 'subscribed'
cb()
else
cb err or new errors.Forbidden("Only subscribers may publish")
else
cb new errors.Forbidden("Only #{@nodeConfig.publishModel} may publish")
filterSubscription: (subscription) =>
subscription.jid is @actor or
subscription.subscription is 'subscribed'
filterAffiliation: (affiliation) ->
affiliation.affiliation isnt 'outcast'
filterSubscriptionModerator: (subscription) ->
yes
filterAffiliationModerator: (affiliation) ->
yes
###
# Discrete Operations
###
class BrowseInfo extends Operation
run: (cb) ->
cb null,
features: [
NS.DISCO_INFO, NS.DISCO_ITEMS,
NS.REGISTER,
NS.PUBSUB, NS.PUBSUB_OWNER
]
identities: [{
category: "pubsub"
type: "service"
name: "XEP-0060 service"
}, {
category: "pubsub"
type: "channels"
name: "Channels service"
}, {
category: "pubsub"
type: "inbox"
name: "Channels inbox service"
}]
class BrowseNodeInfo extends PrivilegedOperation
##
# See access control notice of RetrieveNodeConfiguration
transaction: (t, cb) ->
t.getConfig @req.node, (err, config) =>
cb err,
node: @req.node
features: [
NS.DISCO_INFO, NS.DISCO_ITEMS,
NS.REGISTER,
NS.PUBSUB, NS.PUBSUB_OWNER
]
identities: [{
category: "pubsub"
type: "leaf"
name: "XEP-0060 node"
}, {
category: "pubsub"
type: "channel"
name: "buddycloud channel"
}]
config: config
class BrowseNodes extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
@fetchNodes t, (err, results) =>
if err
return cb err
results = rsm.cropResults(results, 'node')
results.forEach (item) =>
item.jid = @req.me
cb null, results
fetchNodes: (t, cb) ->
t.listNodes cb
class BrowseTopFollowedNodes extends BrowseNodes
fetchNodes: (t, cb) ->
max = @req.rsm.max or 10
t.getTopFollowedNodes max, null, null, cb
class BrowseTopPublishedNodes extends BrowseNodes
fetchNodes: (t, cb) ->
max = @req.rsm.max or 10
t.getTopPublishedNodes max, null, null, cb
class BrowseNodeItems extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
if @subscriptionsNodeOwner?
t.getSubscriptions @subscriptionsNodeOwner, (err, subscriptions) =>
if err
return cb err
# Group for item ids by followee:
subscriptionsByFollowee = {}
for subscription in subscriptions
if (m = subscription.node.match(NODE_OWNER_TYPE_REGEXP))
followee = m[1]
subscriptionsByFollowee[followee] = true
# Prepare RSM suitable result set
results = []
for own followee, present of subscriptionsByFollowee
results.push
name: followee
jid: @req.me
node: @req.node
# Sort for a stable traversal with multiple RSM'ed queries
results.sort (result1, result2) ->
if result1.name < result2.name
-1
else if result1.name > result2.name
1
else
0
# Apply RSM
results = @req.rsm.cropResults results, 'name'
cb null, results
else
t.getItemIds @req.node, (err, ids) =>
if err
return cb err
# Apply RSM
ids = @req.rsm.cropResults ids
results = ids.map (id) =>
{ name: id, jid: @req.me, node: @req.node }
results.node = @req.node
results.rsm = @req.rsm
cb null, results
class Register extends ModelOperation
run: (cb) ->
# check if this component is authoritative for the requesting
# user's domain
@router.authorizeFor @req.me, @req.actor, (err, valid) =>
if err
return cb err
if valid
# asynchronous super:
ModelOperation::run.call @, cb
else
cb new errors.NotAllowed("This is not the authoritative buddycloud-server for your domain")
transaction: (t, cb) ->
user = @req.actor
jobs = []
for own nodeType, config of defaultConfiguration(user)
# rescope loop variables:
do (nodeType, config) =>
jobs.push (cb2) =>
node = "/user/#{user}/#{nodeType}"
config.creationDate = new Date().toISOString()
@createNodeWithConfig t, node, config, cb2
async.series jobs, (err) ->
cb err
createNodeWithConfig: (t, node, config, cb) ->
user = @req.actor
created = no
async.waterfall [(cb2) ->
logger.info "creating #{node}"
t.createNode node, cb2
, (created_, cb2) ->
created = created_
t.setAffiliation node, user, 'owner', cb2
, (cb2) =>
t.setSubscription node, user, @req.sender, 'subscribed', cb2
, (cb2) ->
# if already present, don't overwrite config
if created
t.setConfig node, config, cb2
else
cb2 null
], cb
class CreateNode extends ModelOperation
transaction: (t, cb) ->
nodeUser = getNodeUser @req.node
unless nodeUser
return cb new errors.BadRequest("Malformed node")
if nodeUser.split("@")[0].length < 1
return cb new errors.BadRequest("Malformed node name")
isTopic = nodeUser isnt @req.actor
nodePrefix = "/user/#{nodeUser}/"
try
opts =
node: @req.node
nodeUser: nodeUser
actor: @req.actor
unless exports.checkCreateNode?(opts)
return cb new errors.NotAllowed("Node creation not allowed")
catch e
return cb e
async.waterfall [(cb2) =>
t.getOwnersByNodePrefix nodePrefix, cb2
, (owners, cb2) =>
if owners.length < 1 or owners.indexOf(@req.actor) >= 0
# Either there are no owners yet, or the user is
# already one of them.
t.createNode @req.node, cb2
else
cb2 new errors.NotAllowed("Nodes with prefix #{nodePrefix} are already owned by #{owners.join(', ')}")
, (created, cb2) =>
if created
# Worked, proceed
cb2 null
else
# Already exists
cb2 new errors.Conflict("Node #{@req.node} already exists")
, (cb2) =>
config = @req.config or {}
config.creationDate = new Date().toISOString()
# Pick config defaults
if isTopic
defaults = defaultTopicConfiguration nodeUser
else
defaults = defaultConfiguration nodeUser
defaults = defaults[getNodeType @req.node]
if defaults
# Mix into config
for own key, value of defaults
unless config
config = {}
# Don't overwrite existing
unless config[key]?
config[key] = value
# Set
t.setConfig @req.node, config, cb2
, (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, 'subscribed', cb2
, (cb2) =>
t.setAffiliation @req.node, @req.actor, 'owner', cb2
], cb
class Publish extends PrivilegedOperation
# checks affiliation with @checkPublishModel below
privilegedTransaction: (t, cb) ->
if @subscriptionsNode?
return cb new errors.NotAllowed("The subscriptions node is automagically populated")
async.waterfall [ (cb2) =>
@checkPublishModel t, cb2
, (cb2) =>
async.series @req.items.map((item) =>
(cb3) =>
async.waterfall [(cb4) =>
unless item.id?
item.id = uuid()
cb4 null, null
else
t.getItem @req.node, item.id, (err, item) ->
if err and err.constructor is errors.NotFound
cb4 null, null
else
cb4 err, item
, (oldItem, cb4) =>
normalizeItem @req, oldItem, item, cb4
, (newItem, cb4) =>
t.writeItem @req.node, newItem.id, newItem.el, (err) ->
cb4 err, newItem.id
], cb3
), cb2
], cb
notification: ->
[{
type: 'items'
node: @req.node
items: @req.items
}]
class Subscribe extends PrivilegedOperation
##
# Overwrites PrivilegedOperation#transaction() to use a different
# permissions checking model, but still uses its methods.
transaction: (t, cb) ->
async.waterfall [ (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
if @nodeConfig.accessModel is 'authorize'
@subscription = 'pending'
# Immediately return:
return cb2()
@subscription = 'subscribed'
defaultAffiliation = @nodeConfig.defaultAffiliation or 'none'
unless isAffiliationAtLeast @actorAffiliation, defaultAffiliation
# Less than current affiliation? Bump up to defaultAffiliation
@affiliation = @nodeConfig.defaultAffiliation or 'member'
@checkAccessModel t, cb2
], (err) =>
if err
return cb err
@privilegedTransaction t, cb
privilegedTransaction: (t, cb) ->
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, @subscription, cb2
, (cb2) =>
if @affiliation
t.setAffiliation @req.node, @req.actor, @affiliation, cb2
else
cb2()
], (err) =>
cb err,
user: @req.actor
subscription: @subscription
notification: ->
ns = [{
type: 'subscription'
node: @req.node
user: @req.actor
subscription: @subscription
}]
if @affiliation
ns.push
type: 'affiliation'
node: @req.node
user: @req.actor
affiliation: @affiliation
ns
moderatorNotification: ->
if @subscription is 'pending'
type: 'authorizationPrompt'
node: @req.node
user: @req.actor
##
# Not privileged as anybody should be able to unsubscribe him/herself
class Unsubscribe extends PrivilegedOperation
transaction: (t, cb) ->
if @req.node.indexOf("/user/#{@req.actor}/") == 0
return cb new errors.Forbidden("You may not unsubscribe from your own nodes")
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, 'none', cb2
, (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
# only decrease if <= defaultAffiliation
if isAffiliationAtLeast(@nodeConfig.defaultAffiliation, @actorAffiliation) and
@actorAffiliation isnt 'outcast'
@actorAffiliation = 'none'
t.setAffiliation @req.node, @req.actor, 'none', cb2
else
cb2()
], cb
notification: ->
[{
type: 'subscription'
node: @req.node
user: @req.actor
subscription: 'none'
}, {
type: 'affiliation'
node: @req.node
user: @req.actor
affiliation: @actorAffiliation
}]
class RetrieveItems extends PrivilegedOperation
run: (cb) ->
if @subscriptionsNodeOwner?
# Special case: only handle virtually when local server is
# authoritative
@router.authorizeFor @req.me, @subscriptionsNodeOwner, (err, valid) =>
if err
return cb err
if valid
# Patch in virtual items
@privilegedTransaction = @retrieveSubscriptionsItems
# asynchronous super:
PrivilegedOperation::run.call @, cb
else
super
privilegedTransaction: (t, cb) ->
node = @req.node
rsm = @req.rsm
if @req.itemIds?
fetchItemIds = (cb2) =>
cb2 null, @req.itemIds
else
fetchItemIds = (cb2) ->
t.getItemIds node, cb2
fetchItemIds (err, ids) ->
# Apply RSM
ids = rsm.cropResults ids
# Fetching actual items
async.series ids.map((id) ->
(cb2) ->
t.getItem node, id, (err, el) ->
if err
return cb2 err
cb2 null,
id: id
el: el
), (err, results) ->
if err
cb err
else
# Annotate results array
results.node = node
results.rsm = rsm
cb null, results
##
# For /user/.../subscriptions
#
# <item id="koski@buddycloud.com">
# <query xmlns="http://jabber.org/protocol/disco#items" xmlns:pubsub="http://jabber.org/protocol/pubsub" xmlns:atom="http://www.w3.org/2005/Atom">
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/posts"
# pubsub:affiliation="publisher">
# <atom:updated>2010-12-26T17:30:00Z</atom:updated>
# </item>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/future"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/current"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/previous"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/mood"
# pubsub:affiliation="member"/>
# </query>
# </item>
retrieveSubscriptionsItems: (t, cb) ->
async.waterfall [ (cb2) =>
t.getSubscriptions @subscriptionsNodeOwner, cb2
, (subscriptions, cb2) =>
# No pending subscriptions:
subscriptions = subscriptions.filter (subscription) ->
subscription.subscription is 'subscribed'
# Group for item ids by followee:
subscriptionsByFollowee = {}
for subscription in subscriptions
if (m = subscription.node.match(NODE_OWNER_TYPE_REGEXP))
followee = m[1]
unless subscriptionsByFollowee[followee]?
subscriptionsByFollowee[followee] = []
subscriptionsByFollowee[followee].push subscription
# Prepare RSM suitable result set
results = []
for own followee, followeeSubscriptions of subscriptionsByFollowee
results.push
id: followee
subscriptions: followeeSubscriptions
# Sort for a stable traversal with multiple RSM'ed queries
results.sort (result1, result2) ->
if result1.id < result2.id
-1
else if result1.id > result2.id
1
else
0
# Apply RSM
results = @req.rsm.cropResults results, 'id'
# get affiliations per node
async.forEachSeries results, (result, cb3) =>
async.forEach result.subscriptions, (subscription, cb4) =>
t.getAffiliation subscription.node, @subscriptionsNodeOwner, (err, affiliation) ->
subscription.affiliation ?= affiliation
cb4 err
, cb3
, (err) ->
cb2 err, results
, (results, cb2) =>
# Transform to specified items format
for item in results
item.el = new Element('query',
xmlns: NS.DISCO_ITEMS
'xmlns:pubsub': NS.PUBSUB
)
for subscription in item.subscriptions
itemAttrs =
jid: @subscriptionsNodeOwner
node: subscription.node
itemAttrs['pubsub:subscription'] ?= subscription.subscription
itemAttrs['pubsub:affiliation'] ?= subscription.affiliation
item.el.c('item', itemAttrs)
delete item.subscriptions
results.rsm = @req.rsm
results.node = @req.node
cb2 null, results
], cb
class RetractItems extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
async.waterfall [ (cb2) =>
if isAffiliationAtLeast @actorAffiliation, 'moderator'
# Owners and moderators may remove any post
cb2()
else
# Anyone may remove only their own posts
@checkItemsAuthor t, cb2
, (cb2) =>
async.forEach @req.items, (id, cb3) =>
t.deleteItem @req.node, id, cb3
, cb2
, (cb2) =>
if @req.notify
@notification = ->
[{
type: 'items'
node: @req.node
retract: @req.items
}]
cb2()
], cb
checkItemsAuthor: (t, cb) ->
async.forEachSeries @req.items, (id, cb2) =>
t.getItem @req.node, id, (err, el) =>
if err?.constructor is errors.NotFound
# Ignore non-existant item
return cb2()
else if err
return cb2(err)
# Check for post authorship
author = el?.is('entry') and
el.getChild('author')?.getChild('uri')?.getText()
if author is "acct:#{@req.actor}"
# Authenticated!
cb2()
else
cb2 new errors.NotAllowed("You may not retract other people's posts")
, cb
class RetrieveUserSubscriptions extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
t.getSubscriptions @req.actor, (err, subscriptions) ->
if err
return cb err
subscriptions = rsm.cropResults subscriptions, 'node'
cb null, subscriptions
class RetrieveUserAffiliations extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
t.getAffiliations @req.actor, (err, affiliations) ->
if err
return cb err
affiliations = rsm.cropResults affiliations, 'node'
cb null, affiliations
class RetrieveNodeSubscriptions extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
rsm = @req.rsm
t.getSubscribers @req.node, (err, subscriptions) =>
if err
return cb err
subscriptions = subscriptions.filter @filterSubscription
subscriptions = rsm.cropResults subscriptions, 'user'
cb null, subscriptions
class RetrieveNodeAffiliations extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
rsm = @req.rsm
t.getAffiliated @req.node, (err, affiliations) =>
if err
return cb err
affiliations = affiliations.filter @filterAffiliation
affiliations = rsm.cropResults affiliations, 'user'
cb null, affiliations
class RetrieveNodeConfiguration extends PrivilegedOperation
##
# Allowed for anyone. We do not have hidden channels yet.
#
# * Even closed channels should be browsable so that subscription
# can be requested at all
# * outcast shall not receive too much punishment (or glorification)
transaction: (t, cb) ->
t.getConfig @req.node, (err, config) ->
# wrap into { config: ...} result
cb err, { config }
class ManageNodeSubscriptions extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
defaultAffiliation = null
async.waterfall [(cb2) =>
t.getConfig @req.node, (error, config) =>
defaultAffiliation = config.defaultAffiliation or 'member'
cb2(error)
, (cb2) =>
async.forEach @req.subscriptions
, ({user, subscription}, cb3) =>
async.waterfall [(cb4) =>
if @req.node.indexOf("/user/#{user}/") == 0 and
subscription isnt 'subscribed'
cb4 new errors.Forbidden("You may not unsubscribe the owner")
else
t.setSubscription @req.node, user, null, subscription, cb4
, (cb4) =>
t.getAffiliation @req.node, user, cb4
, (affiliation, cb4) =>
if affiliation is 'none'
t.setAffiliation @req.node, user, defaultAffiliation, cb4
else
cb4()
], cb3
, cb2
], cb
notification: ->
@req.subscriptions.map ({user, subscription}) =>
{
type: 'subscription'
node: @req.node
user
subscription
}
class ManageNodeAffiliations extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
@newModerators = []
async.series @req.affiliations.map(({user, affiliation}) =>
(cb2) =>
async.waterfall [ (cb3) =>
t.getAffiliation @req.node, user, cb3
, (oldAffiliation, cb3) =>
if oldAffiliation is affiliation
# No change
cb3()
else
if oldAffiliation isnt 'owner' and
affiliation is 'owner' and
@actorAffiliation isnt 'owner'
# Non-owner tries to elect a new owner!
cb3 new errors.Forbidden("You may not elect a new owner")
else
async.series [ (cb4) =>
if not canModerate(oldAffiliation) and
canModerate(affiliation)
t.getSubscriptionListener @req.node, user, (err, listener) =>
if (not err) and listener
@newModerators.push { user, listener, node: @req.node }
cb4 err
else
cb4()
, (cb4) =>
if @req.node.indexOf("/user/#{user}/") == 0 and
affiliation isnt 'owner'
cb4 new errors.Forbidden("You may not demote the owner")
else
t.setAffiliation @req.node, user, affiliation, cb4
], (err) ->
cb3 err
], cb2
), cb
notification: ->
affiliations = @req.affiliations.map ({user, affiliation}) =>
{
type: 'affiliation'
node: @req.node
user
affiliation
}
ALLOWED_ACCESS_MODELS = ['open', 'whitelist', 'authorize']
ALLOWED_PUBLISH_MODELS = ['open', 'subscribers', 'publishers']
class ManageNodeConfiguration extends PrivilegedOperation
requiredAffiliation: 'owner'
run: (cb) ->
# Validate some config
if @req.config.accessModel? and
ALLOWED_ACCESS_MODELS.indexOf(@req.config.accessModel) < 0
cb new errors.BadRequest("Invalid access model")
else if @req.config.publishModel? and
ALLOWED_PUBLISH_MODELS.indexOf(@req.config.publishModel) < 0
cb new errors.BadRequest("Invalid publish model")
else if @req.config.creationDate?
cb new errors.BadRequest("Cannot set creation date")
else
# All is well, actually run
super(cb)
privilegedTransaction: (t, cb) ->
t.setConfig @req.node, @req.config, cb
notification: ->
[{
type: 'config'
node: @req.node
config: @req.config
}]
##
# Removes all subscriptions of the actor, call back with all remote
# subscriptions that the backends must then unsubscribe for.
#
# Two uses:
#
# * Rm subscriptions of an anonymous (temporary) user
# * TODO: Completely clear out a user account
class RemoveUser extends ModelOperation
transaction: (t, cb) ->
t.getUserRemoteSubscriptions @req.actor, (err, subscriptions) =>
if err
return cb(err)
t.clearUserSubscriptions @req.actor, (err) =>
cb err, subscriptions
class AuthorizeSubscriber extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
if @req.allow
@subscription = 'subscribed'
unless isAffiliationAtLeast @actorAffiliation, @nodeConfig.defaultAffiliation
# Less than current affiliation? Bump up to defaultAffiliation
@affiliation = @nodeConfig.defaultAffiliation or 'member'
else
@subscription = 'none'
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.user, @req.sender, @subscription, cb2
, (cb2) =>
if @affiliation
t.setAffiliation @req.node, @req.user, @affiliation, cb2
else
cb2()
], (err) ->
cb err
notification: ->
ns = [{
type: 'subscription'
node: @req.node
user: @req.user
subscription: @subscription
}]
if @affiliation
ns.push
type: 'affiliation'
node: @req.node
user: @req.user
affiliation: @affiliation
ns
##
# MAM replay
# and authorization form query
#
# The RSM handling here respects only a <max/> value.
#
# Doesn't care about about subscriptions nodes.
class ReplayArchive extends ModelOperation
transaction: (t, cb) ->
max = @req.rsm?.max or 50
sent = 0
async.waterfall [ (cb2) =>
t.walkListenerArchive @req.sender, @req.start, @req.end, max, (results) =>
if sent < max
results.sort (a, b) ->
if a.updated < b.updated
-1
else if a.updated > b.updated
1
else
0
results = results.slice(0, max - sent)
@sendNotification results
sent += results.length
, cb2
, (cb2) =>
sent = 0
t.walkModeratorAuthorizationRequests @req.sender, (req) =>
if sent < max
req.type = 'authorizationPrompt'
@sendNotification req
sent++
, cb2
], cb
sendNotification: (results) ->
notification = Object.create(results)
notification.listener = @req.fullSender
notification.replay = true
@router.notify notification
class PushInbox extends ModelOperation
transaction: (t, cb) ->
notification = []
newNodes = []
newModerators = []
unsubscribedNodes = {}
async.waterfall [(cb2) =>
logger.debug "pushUpdates: #{inspect @req}"
async.filter @req, (update, cb3) =>
if update.type is 'subscription' and update.listener?
# Was successful remote subscription attempt
t.createNode update.node, (err, created) =>
if created
newNodes.push update.node
cb3 not err
else
# Just an update, to be cached locally?
t.nodeExists update.node, (err, exists) ->
cb3 not err and exists
, (updates) ->
cb2 null, updates
, (updates, cb2) =>
logger.debug "pushFilteredUpdates: #{inspect updates}"
async.forEach updates, (update, cb3) ->
switch update.type
when 'items'
notification.push update
{node, items} = update
async.forEach items, (item, cb4) ->
{id, el} = item
t.writeItem node, id, el, cb4
, cb3
when 'subscription'
notification.push update
{node, user, listener, subscription} = update
if subscription isnt 'subscribed'
unsubscribedNodes[node] = yes
t.setSubscription node, user, listener, subscription, cb3
when 'affiliation'
notification.push update
{node, user, affiliation} = update
t.getAffiliation node, user, (err, oldAffiliation) ->
if err
return cb3 err
async.series [ (cb4) =>
if not canModerate(oldAffiliation) and
canModerate(affiliation)
t.getSubscriptionListener node, user, (err, listener) ->
if (not err) and listener
newModerators.push { user, listener, node }
cb4 err
else
cb4()
, (cb4) =>
t.setAffiliation node, user, affiliation, cb4
], (err) ->
cb3 err
when 'config'
notification.push update
{node, config} = update
t.setConfig node, config, cb3
else
cb3 new errors.InternalServerError("Bogus push update type: #{update.type}")
, cb2
, (cb2) =>
# Memorize updates for notifications, same format:
@notification = -> notification
if newNodes.length > 0
@newNodes = newNodes
if newModerators.length > 0
@newModerators = newModerators
cb2()
, (cb2) =>
# no local subscriptions left to remote node? delete it.
checks = []
for own node, _ of unsubscribedNodes
checks.push (cb3) ->
t.getNodeListeners node, (err, listeners) ->
if err
return cb3 err
unless listeners? and listeners.length > 0
t.purgeNode node, cb3
async.parallel checks, cb2
], cb
class Notify extends ModelOperation
transaction: (t, cb) ->
async.waterfall [(cb2) =>
async.forEach @req, (update, cb3) =>
# First, we complete subscriptions node items
m = update.node.match(NODE_OWNER_TYPE_REGEXP)
# Fill in missing subscriptions node items
if update.type is 'items' and m?[2] is 'subscriptions'
subscriber = m[1]
t.getSubscriptions subscriber, (err, subscriptions) =>
if err
return cb3 err
async.map update.items, ({id, el}, cb4) =>
if el
# Content already exists, perhaps
# relaying a notification from another
# service
return cb4 null, { id, el }
userSubscriptions = subscriptions.filter (subscription) ->
subscription.node.indexOf("/user/#{id}/") is 0
affiliations = {}
async.forEach userSubscriptions, (subscription, cb5) =>
t.getAffiliation subscriber, subscription.node, (err, affiliation) =>
affiliations[subscription.node] = affiliation
cb5(err)
, (err) =>
el = new Element('query',
xmlns: NS.DISCO_ITEMS
'xmlns:pubsub': NS.PUBSUB
)
for subscription in userSubscriptions
itemAttrs =
jid: subscriber
node: subscription.node
itemAttrs['pubsub:subscription'] ?= subscription.subscription
itemAttrs['pubsub:affiliation'] ?= affiliations[subscription.node]
el.c('item', itemAttrs)
cb4 null, { id, el }
, (err, items) =>
if err
return cb3(err)
update.items = items
cb3()
else
cb3()
, cb2
, (cb2) =>
# Then, retrieve all listeners
# (assuming all updates pertain one single node)
# TODO: walk in batches
logger.debug "notifyNotification: #{inspect @req}"
t.getNodeListeners @req.node, cb2
, (listeners, cb2) =>
# Always notify all users pertained by a subscription
# notification, even if just unsubscribed.
for update in @req
if update.type is 'subscription' and
listeners.indexOf(update.user) < 0
listeners.push update.user
cb2 null, listeners
, (listeners, cb2) =>
moderatorListeners = []
otherListeners = []
async.forEach listeners, (listener, cb3) =>
t.getAffiliation @req.node, listener, (err, affiliation) ->
if err
return cb3 err
if canModerate affiliation
moderatorListeners.push listener
else
otherListeners.push listener
cb3()
, (err) =>
cb2 err, moderatorListeners, otherListeners
, (moderatorListeners, otherListeners, cb2) =>
# Send out through backends
if moderatorListeners.length > 0
for listener in moderatorListeners
notification = Object.create(@req)
notification.listener = listener
@router.notify notification
if otherListeners.length > 0
req = @req.filter (update) =>
switch update.type
when 'subscription'
PrivilegedOperation::filterSubscription update
when 'affiliation'
PrivilegedOperation::filterAffiliation update
else
yes
# Any left after filtering? Don't send empty
# notification when somebody got banned.
if req.length > 0
for listener in otherListeners
notification = Object.create(req)
notification.node = @req.node
notification.listener = listener
@router.notify notification
cb2()
], cb
class ModeratorNotify extends ModelOperation
transaction: (t, cb) ->
# TODO: walk in batches
logger.debug "moderatorNotifyNotification: #{inspect(@req)}"
t.getNodeModeratorListeners @req.node, (err, listeners) =>
if err
return cb err
for listener in listeners
notification = Object.create(@req)
notification.listener = listener
@router.notify notification
cb()
class NewModeratorNotify extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
async.parallel [ (cb2) =>
t.getPending @req.node, cb2
, (cb2) =>
t.getOutcast @req.node, cb2
], (err, [pendingUsers, bannedUsers]) =>
if err
return cb err
notification = []
notification.node = @req.node
notification.listener = @req.listener
for user in pendingUsers
notification.push
type: 'subscription'
node: @req.node
user: user
subscription: 'pending'
for user in bannedUsers
notification.push
type: 'affiliation'
node: @req.node
user: user
affiliation: 'outcast'
@router.notify notification
cb()
OPERATIONS =
'browse-info': BrowseInfo
'browse-node-info': BrowseNodeInfo
'browse-nodes': BrowseNodes
'browse-top-followed-nodes': BrowseTopFollowedNodes
'browse-top-published-nodes': BrowseTopPublishedNodes
'browse-node-items': BrowseNodeItems
'register-user': Register
'create-node': CreateNode
'publish-node-items': Publish
'subscribe-node': Subscribe
'unsubscribe-node': Unsubscribe
'retrieve-node-items': RetrieveItems
'retract-node-items': RetractItems
'retrieve-user-subscriptions': RetrieveUserSubscriptions
'retrieve-user-affiliations': RetrieveUserAffiliations
'retrieve-node-subscriptions': RetrieveNodeSubscriptions
'retrieve-node-affiliations': RetrieveNodeAffiliations
'retrieve-node-configuration': RetrieveNodeConfiguration
'manage-node-subscriptions': ManageNodeSubscriptions
'manage-node-affiliations': ManageNodeAffiliations
'manage-node-configuration': ManageNodeConfiguration
'remove-user': RemoveUser
'confirm-subscriber-authorization': AuthorizeSubscriber
'replay-archive': ReplayArchive
'push-inbox': PushInbox
exports.run = (router, request, cb) ->
opName = request.operation
unless opName
# No operation specified, reply immediately
return cb?()
opClass = OPERATIONS[opName]
unless opClass
logger.warn "Unimplemented operation #{opName}: #{inspect request}"
return cb?(new errors.FeatureNotImplemented("Unimplemented operation #{opName}"))
logger.debug "operations.run: #{inspect request}"
op = new opClass(router, request)
op.run (error, result) ->
if error
logger.warn "Operation #{opName} failed: #{error.stack or error}"
cb? error
else
# Successfully done
logger.debug "Operation #{opName} ran: #{inspect result}"
async.series [(cb2) ->
# Run notifications
if (notification = op.notification?())
# Extend by subscriptions node notifications
notification = notification.concat generateSubscriptionsNotifications(notification)
# Call Notify operation grouped by node
# (looks up subscribers by node)
blocks = []
for own node, notifications of groupByNode(notification)
notifications.node = node
do (notifications) ->
blocks.push (cb3) ->
new Notify(router, notifications).run (err) ->
if err
logger.error("Error running notifications: #{err.stack or err.message or err}")
cb3()
async.series blocks, cb2
else
cb2()
, (cb2) ->
if (notification = op.moderatorNotification?())
new ModeratorNotify(router, notification).run (err) ->
if err
logger.error("Error running notifications: #{err.stack or err.message or err}")
cb2()
else
cb2()
, (cb2) ->
if (op.newModerators and op.newModerators.length > 0)
blocks = []
for {user, node, listener} in op.newModerators
req =
operation: 'new-moderator-notification'
node: node
actor: user
listener: listener
do (req) ->
blocks.push (cb3) ->
new NewModeratorNotify(router, req).run (err) ->
if err
logger.error("Error running new moderator notification: #{err.stack or err.message or err}")
cb3()
async.series blocks, cb2
else
cb2()
, (cb2) ->
# May need to sync new nodes
if op.newNodes?
async.forEach op.newNodes, (node, cb3) ->
router.syncNode node, cb3
, cb2
else
cb2()
], ->
# Ignore any sync result
try
cb? null, result
catch e
logger.error e.stack or e
groupByNode = (updates) ->
result = {}
for update in updates
unless result.hasOwnProperty(update.node)
result[update.node] = []
result[update.node].push update
result
generateSubscriptionsNotifications = (updates) ->
itemIdsSeen = {}
updates.filter((update) ->
(update.type is 'subscription' and
update.subscription is 'subscribed') or
update.type is 'affiliation'
).map((update) ->
followee = update.node.match(NODE_OWNER_TYPE_REGEXP)?[1]
type: 'items'
node: "/user/#{update.user}/subscriptions"
items: [{ id: followee }]
# Actual item payload will be completed by Notify transaction
).filter((update) ->
itemId = update.items[0].id
if itemIdsSeen[itemId]?
no
else
itemIdsSeen[itemId] = yes
yes
)
| 158593 | logger = require('../logger').makeLogger 'local/operations'
{inspect} = require('util')
{getNodeUser, getNodeType} = require('../util')
async = require('async')
uuid = require('node-uuid')
errors = require('../errors')
NS = require('../xmpp/ns')
{normalizeItem} = require('../normalize')
{Element} = require('node-xmpp')
runTransaction = null
exports.setModel = (model) ->
runTransaction = model.transaction
exports.checkCreateNode = null
defaultConfiguration = (user) ->
posts:
title: "#{user} Channel Posts"
description: "A buddycloud channel"
channelType: "personal"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "publisher"
status:
title: "#{user} Status Updates"
description: "M000D"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/previous':
title: "#{user} Previous Location"
description: "Where #{user} has been before"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/current':
title: "#{user} Current Location"
description: "Where #{user} is at now"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/next':
title: "#{user} Next Location"
description: "Where #{user} intends to go"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
subscriptions:
title: "#{user} Subscriptions"
description: "Browse my interests"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
# user is "topic@domain" string
defaultTopicConfiguration = (user) =>
posts:
title: "#{user} Topic Channel"
description: "All about #{user.split('@')?[0]}"
channelType: "topic"
accessModel: "open"
publishModel: "subscribers"
defaultAffiliation: "member"
NODE_OWNER_TYPE_REGEXP = /^\/user\/([^\/]+)\/?(.*)/
AFFILIATIONS = [
'outcast', 'none', 'member',
'publisher', 'moderator', 'owner'
]
isAffiliationAtLeast = (affiliation1, affiliation2) ->
i1 = AFFILIATIONS.indexOf(affiliation1)
i2 = AFFILIATIONS.indexOf(affiliation2)
if i2 < 0
false
else
i1 >= i2
canModerate = (affiliation) ->
affiliation is 'owner' or affiliation is 'moderator'
###
# Base Operations
###
##
# Is created with options from the request
#
# Implementations set result
class Operation
constructor: (@router, @req) ->
if @req.node? and
(m = @req.node.match(NODE_OWNER_TYPE_REGEXP)) and
m[2] is 'subscriptions'
# Affords for specialized items handling in RetrieveItems and Publish
@subscriptionsNodeOwner = m[1]
run: (cb) ->
cb new errorsFeature.NotImplemented("Operation defined but not yet implemented")
class ModelOperation extends Operation
run: (cb) ->
runTransaction (err, t) =>
if err
return cb err
opName = @req.operation or @constructor?.name or "?"
@transaction t, (err, results) ->
if err
logger.warn "Transaction #{opName} rollback: #{err}"
t.rollback ->
cb err
else
t.commit ->
logger.debug "Transaction #{opName} committed"
cb null, results
# Must be implemented by subclass
transaction: (t, cb) ->
cb null
class PrivilegedOperation extends ModelOperation
transaction: (t, cb) ->
async.waterfall [ (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
@checkAccessModel t, cb2
, (cb2) =>
@checkRequiredAffiliation t, cb2
], (err) =>
if err
return cb err
@privilegedTransaction t, cb
fetchActorAffiliation: (t, cb) ->
unless @req.node
return cb()
if @req.actor.indexOf('@') >= 0
t.getAffiliation @req.node, @req.actor, (err, affiliation) =>
if err
return cb err
@actorAffiliation = affiliation or 'none'
else
# actor no user? check if listener!
t.getListenerAffiliations @req.node, @req.actor, (err, affiliations) =>
if err
return cb err
@actorAffiliation = 'none'
for affiliation in affiliations
if affiliation isnt @actorAffiliation and
isAffiliationAtLeast affiliation, @actorAffiliation
@actorAffiliation = affiliation
if canModerate @actorAffiliation
# Moderators get to see everything
@filterSubscription = @filterSubscriptionModerator
@filterAffiliation = @filterAffiliationModerator
cb()
fetchNodeConfig: (t, cb) ->
unless @req.node
return cb()
t.getConfig @req.node, (err, config) =>
if err
return cb err
@nodeConfig = config
cb()
checkAccessModel: (t, cb) ->
# Deny any outcast
if @actorAffiliation is 'outcast'
return cb new errors.Forbidden("Outcast")
# Set default according to node config
unless @requiredAffiliation
if @nodeConfig.accessModel is 'open'
# Open nodes allow anyone
@requiredAffiliation = 'none'
else
# For all other access models, actor has to be member
@requiredAffiliation = 'member'
cb()
checkRequiredAffiliation: (t, cb) ->
if @requiredAffiliation?.constructor is Function
requiredAffiliation = @requiredAffiliation()
else
requiredAffiliation = @requiredAffiliation
if not requiredAffiliation? or
isAffiliationAtLeast @actorAffiliation, requiredAffiliation
cb()
else
cb new errors.Forbidden("Requires affiliation #{requiredAffiliation} (you are #{@actorAffiliation})")
# Used by Publish operation
checkPublishModel: (t, cb) ->
pass = false
switch @nodeConfig.publishModel
when 'open'
pass = true
when 'members'
pass = isAffiliationAtLeast @actorAffiliation, 'member'
when 'publishers'
pass = isAffiliationAtLeast @actorAffiliation, 'publisher'
else
# Owners can always post
pass = (@actorAffiliation is 'owner')
if pass
cb()
else if @nodeConfig.publishModel is 'subscribers'
# Special handling because subscription state must be
# fetched
t.getSubscription @req.node, @req.actor, (err, subscription) ->
if !err and subscription is 'subscribed'
cb()
else
cb err or new errors.Forbidden("Only subscribers may publish")
else
cb new errors.Forbidden("Only #{@nodeConfig.publishModel} may publish")
filterSubscription: (subscription) =>
subscription.jid is @actor or
subscription.subscription is 'subscribed'
filterAffiliation: (affiliation) ->
affiliation.affiliation isnt 'outcast'
filterSubscriptionModerator: (subscription) ->
yes
filterAffiliationModerator: (affiliation) ->
yes
###
# Discrete Operations
###
class BrowseInfo extends Operation
run: (cb) ->
cb null,
features: [
NS.DISCO_INFO, NS.DISCO_ITEMS,
NS.REGISTER,
NS.PUBSUB, NS.PUBSUB_OWNER
]
identities: [{
category: "pubsub"
type: "service"
name: "XEP-0060 service"
}, {
category: "pubsub"
type: "channels"
name: "Channels service"
}, {
category: "pubsub"
type: "inbox"
name: "Channels inbox service"
}]
class BrowseNodeInfo extends PrivilegedOperation
##
# See access control notice of RetrieveNodeConfiguration
transaction: (t, cb) ->
t.getConfig @req.node, (err, config) =>
cb err,
node: @req.node
features: [
NS.DISCO_INFO, NS.DISCO_ITEMS,
NS.REGISTER,
NS.PUBSUB, NS.PUBSUB_OWNER
]
identities: [{
category: "pubsub"
type: "leaf"
name: "XEP-0060 node"
}, {
category: "pubsub"
type: "channel"
name: "buddycloud channel"
}]
config: config
class BrowseNodes extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
@fetchNodes t, (err, results) =>
if err
return cb err
results = rsm.cropResults(results, 'node')
results.forEach (item) =>
item.jid = @req.me
cb null, results
fetchNodes: (t, cb) ->
t.listNodes cb
class BrowseTopFollowedNodes extends BrowseNodes
fetchNodes: (t, cb) ->
max = @req.rsm.max or 10
t.getTopFollowedNodes max, null, null, cb
class BrowseTopPublishedNodes extends BrowseNodes
fetchNodes: (t, cb) ->
max = @req.rsm.max or 10
t.getTopPublishedNodes max, null, null, cb
class BrowseNodeItems extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
if @subscriptionsNodeOwner?
t.getSubscriptions @subscriptionsNodeOwner, (err, subscriptions) =>
if err
return cb err
# Group for item ids by followee:
subscriptionsByFollowee = {}
for subscription in subscriptions
if (m = subscription.node.match(NODE_OWNER_TYPE_REGEXP))
followee = m[1]
subscriptionsByFollowee[followee] = true
# Prepare RSM suitable result set
results = []
for own followee, present of subscriptionsByFollowee
results.push
name: followee
jid: @req.me
node: @req.node
# Sort for a stable traversal with multiple RSM'ed queries
results.sort (result1, result2) ->
if result1.name < result2.name
-1
else if result1.name > result2.name
1
else
0
# Apply RSM
results = @req.rsm.cropResults results, 'name'
cb null, results
else
t.getItemIds @req.node, (err, ids) =>
if err
return cb err
# Apply RSM
ids = @req.rsm.cropResults ids
results = ids.map (id) =>
{ name: id, jid: @req.me, node: @req.node }
results.node = @req.node
results.rsm = @req.rsm
cb null, results
class Register extends ModelOperation
run: (cb) ->
# check if this component is authoritative for the requesting
# user's domain
@router.authorizeFor @req.me, @req.actor, (err, valid) =>
if err
return cb err
if valid
# asynchronous super:
ModelOperation::run.call @, cb
else
cb new errors.NotAllowed("This is not the authoritative buddycloud-server for your domain")
transaction: (t, cb) ->
user = @req.actor
jobs = []
for own nodeType, config of defaultConfiguration(user)
# rescope loop variables:
do (nodeType, config) =>
jobs.push (cb2) =>
node = "/user/#{user}/#{nodeType}"
config.creationDate = new Date().toISOString()
@createNodeWithConfig t, node, config, cb2
async.series jobs, (err) ->
cb err
createNodeWithConfig: (t, node, config, cb) ->
user = @req.actor
created = no
async.waterfall [(cb2) ->
logger.info "creating #{node}"
t.createNode node, cb2
, (created_, cb2) ->
created = created_
t.setAffiliation node, user, 'owner', cb2
, (cb2) =>
t.setSubscription node, user, @req.sender, 'subscribed', cb2
, (cb2) ->
# if already present, don't overwrite config
if created
t.setConfig node, config, cb2
else
cb2 null
], cb
class CreateNode extends ModelOperation
transaction: (t, cb) ->
nodeUser = getNodeUser @req.node
unless nodeUser
return cb new errors.BadRequest("Malformed node")
if nodeUser.split("@")[0].length < 1
return cb new errors.BadRequest("Malformed node name")
isTopic = nodeUser isnt @req.actor
nodePrefix = "/user/#{nodeUser}/"
try
opts =
node: @req.node
nodeUser: nodeUser
actor: @req.actor
unless exports.checkCreateNode?(opts)
return cb new errors.NotAllowed("Node creation not allowed")
catch e
return cb e
async.waterfall [(cb2) =>
t.getOwnersByNodePrefix nodePrefix, cb2
, (owners, cb2) =>
if owners.length < 1 or owners.indexOf(@req.actor) >= 0
# Either there are no owners yet, or the user is
# already one of them.
t.createNode @req.node, cb2
else
cb2 new errors.NotAllowed("Nodes with prefix #{nodePrefix} are already owned by #{owners.join(', ')}")
, (created, cb2) =>
if created
# Worked, proceed
cb2 null
else
# Already exists
cb2 new errors.Conflict("Node #{@req.node} already exists")
, (cb2) =>
config = @req.config or {}
config.creationDate = new Date().toISOString()
# Pick config defaults
if isTopic
defaults = defaultTopicConfiguration nodeUser
else
defaults = defaultConfiguration nodeUser
defaults = defaults[getNodeType @req.node]
if defaults
# Mix into config
for own key, value of defaults
unless config
config = {}
# Don't overwrite existing
unless config[key]?
config[key] = value
# Set
t.setConfig @req.node, config, cb2
, (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, 'subscribed', cb2
, (cb2) =>
t.setAffiliation @req.node, @req.actor, 'owner', cb2
], cb
class Publish extends PrivilegedOperation
# checks affiliation with @checkPublishModel below
privilegedTransaction: (t, cb) ->
if @subscriptionsNode?
return cb new errors.NotAllowed("The subscriptions node is automagically populated")
async.waterfall [ (cb2) =>
@checkPublishModel t, cb2
, (cb2) =>
async.series @req.items.map((item) =>
(cb3) =>
async.waterfall [(cb4) =>
unless item.id?
item.id = uuid()
cb4 null, null
else
t.getItem @req.node, item.id, (err, item) ->
if err and err.constructor is errors.NotFound
cb4 null, null
else
cb4 err, item
, (oldItem, cb4) =>
normalizeItem @req, oldItem, item, cb4
, (newItem, cb4) =>
t.writeItem @req.node, newItem.id, newItem.el, (err) ->
cb4 err, newItem.id
], cb3
), cb2
], cb
notification: ->
[{
type: 'items'
node: @req.node
items: @req.items
}]
class Subscribe extends PrivilegedOperation
##
# Overwrites PrivilegedOperation#transaction() to use a different
# permissions checking model, but still uses its methods.
transaction: (t, cb) ->
async.waterfall [ (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
if @nodeConfig.accessModel is 'authorize'
@subscription = 'pending'
# Immediately return:
return cb2()
@subscription = 'subscribed'
defaultAffiliation = @nodeConfig.defaultAffiliation or 'none'
unless isAffiliationAtLeast @actorAffiliation, defaultAffiliation
# Less than current affiliation? Bump up to defaultAffiliation
@affiliation = @nodeConfig.defaultAffiliation or 'member'
@checkAccessModel t, cb2
], (err) =>
if err
return cb err
@privilegedTransaction t, cb
privilegedTransaction: (t, cb) ->
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, @subscription, cb2
, (cb2) =>
if @affiliation
t.setAffiliation @req.node, @req.actor, @affiliation, cb2
else
cb2()
], (err) =>
cb err,
user: @req.actor
subscription: @subscription
notification: ->
ns = [{
type: 'subscription'
node: @req.node
user: @req.actor
subscription: @subscription
}]
if @affiliation
ns.push
type: 'affiliation'
node: @req.node
user: @req.actor
affiliation: @affiliation
ns
moderatorNotification: ->
if @subscription is 'pending'
type: 'authorizationPrompt'
node: @req.node
user: @req.actor
##
# Not privileged as anybody should be able to unsubscribe him/herself
class Unsubscribe extends PrivilegedOperation
transaction: (t, cb) ->
if @req.node.indexOf("/user/#{@req.actor}/") == 0
return cb new errors.Forbidden("You may not unsubscribe from your own nodes")
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, 'none', cb2
, (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
# only decrease if <= defaultAffiliation
if isAffiliationAtLeast(@nodeConfig.defaultAffiliation, @actorAffiliation) and
@actorAffiliation isnt 'outcast'
@actorAffiliation = 'none'
t.setAffiliation @req.node, @req.actor, 'none', cb2
else
cb2()
], cb
notification: ->
[{
type: 'subscription'
node: @req.node
user: @req.actor
subscription: 'none'
}, {
type: 'affiliation'
node: @req.node
user: @req.actor
affiliation: @actorAffiliation
}]
class RetrieveItems extends PrivilegedOperation
run: (cb) ->
if @subscriptionsNodeOwner?
# Special case: only handle virtually when local server is
# authoritative
@router.authorizeFor @req.me, @subscriptionsNodeOwner, (err, valid) =>
if err
return cb err
if valid
# Patch in virtual items
@privilegedTransaction = @retrieveSubscriptionsItems
# asynchronous super:
PrivilegedOperation::run.call @, cb
else
super
privilegedTransaction: (t, cb) ->
node = @req.node
rsm = @req.rsm
if @req.itemIds?
fetchItemIds = (cb2) =>
cb2 null, @req.itemIds
else
fetchItemIds = (cb2) ->
t.getItemIds node, cb2
fetchItemIds (err, ids) ->
# Apply RSM
ids = rsm.cropResults ids
# Fetching actual items
async.series ids.map((id) ->
(cb2) ->
t.getItem node, id, (err, el) ->
if err
return cb2 err
cb2 null,
id: id
el: el
), (err, results) ->
if err
cb err
else
# Annotate results array
results.node = node
results.rsm = rsm
cb null, results
##
# For /user/.../subscriptions
#
# <item id="<EMAIL>">
# <query xmlns="http://jabber.org/protocol/disco#items" xmlns:pubsub="http://jabber.org/protocol/pubsub" xmlns:atom="http://www.w3.org/2005/Atom">
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/posts"
# pubsub:affiliation="publisher">
# <atom:updated>2010-12-26T17:30:00Z</atom:updated>
# </item>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/future"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/current"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/previous"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/mood"
# pubsub:affiliation="member"/>
# </query>
# </item>
retrieveSubscriptionsItems: (t, cb) ->
async.waterfall [ (cb2) =>
t.getSubscriptions @subscriptionsNodeOwner, cb2
, (subscriptions, cb2) =>
# No pending subscriptions:
subscriptions = subscriptions.filter (subscription) ->
subscription.subscription is 'subscribed'
# Group for item ids by followee:
subscriptionsByFollowee = {}
for subscription in subscriptions
if (m = subscription.node.match(NODE_OWNER_TYPE_REGEXP))
followee = m[1]
unless subscriptionsByFollowee[followee]?
subscriptionsByFollowee[followee] = []
subscriptionsByFollowee[followee].push subscription
# Prepare RSM suitable result set
results = []
for own followee, followeeSubscriptions of subscriptionsByFollowee
results.push
id: followee
subscriptions: followeeSubscriptions
# Sort for a stable traversal with multiple RSM'ed queries
results.sort (result1, result2) ->
if result1.id < result2.id
-1
else if result1.id > result2.id
1
else
0
# Apply RSM
results = @req.rsm.cropResults results, 'id'
# get affiliations per node
async.forEachSeries results, (result, cb3) =>
async.forEach result.subscriptions, (subscription, cb4) =>
t.getAffiliation subscription.node, @subscriptionsNodeOwner, (err, affiliation) ->
subscription.affiliation ?= affiliation
cb4 err
, cb3
, (err) ->
cb2 err, results
, (results, cb2) =>
# Transform to specified items format
for item in results
item.el = new Element('query',
xmlns: NS.DISCO_ITEMS
'xmlns:pubsub': NS.PUBSUB
)
for subscription in item.subscriptions
itemAttrs =
jid: @subscriptionsNodeOwner
node: subscription.node
itemAttrs['pubsub:subscription'] ?= subscription.subscription
itemAttrs['pubsub:affiliation'] ?= subscription.affiliation
item.el.c('item', itemAttrs)
delete item.subscriptions
results.rsm = @req.rsm
results.node = @req.node
cb2 null, results
], cb
class RetractItems extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
async.waterfall [ (cb2) =>
if isAffiliationAtLeast @actorAffiliation, 'moderator'
# Owners and moderators may remove any post
cb2()
else
# Anyone may remove only their own posts
@checkItemsAuthor t, cb2
, (cb2) =>
async.forEach @req.items, (id, cb3) =>
t.deleteItem @req.node, id, cb3
, cb2
, (cb2) =>
if @req.notify
@notification = ->
[{
type: 'items'
node: @req.node
retract: @req.items
}]
cb2()
], cb
checkItemsAuthor: (t, cb) ->
async.forEachSeries @req.items, (id, cb2) =>
t.getItem @req.node, id, (err, el) =>
if err?.constructor is errors.NotFound
# Ignore non-existant item
return cb2()
else if err
return cb2(err)
# Check for post authorship
author = el?.is('entry') and
el.getChild('author')?.getChild('uri')?.getText()
if author is "acct:#{@req.actor}"
# Authenticated!
cb2()
else
cb2 new errors.NotAllowed("You may not retract other people's posts")
, cb
class RetrieveUserSubscriptions extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
t.getSubscriptions @req.actor, (err, subscriptions) ->
if err
return cb err
subscriptions = rsm.cropResults subscriptions, 'node'
cb null, subscriptions
class RetrieveUserAffiliations extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
t.getAffiliations @req.actor, (err, affiliations) ->
if err
return cb err
affiliations = rsm.cropResults affiliations, 'node'
cb null, affiliations
class RetrieveNodeSubscriptions extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
rsm = @req.rsm
t.getSubscribers @req.node, (err, subscriptions) =>
if err
return cb err
subscriptions = subscriptions.filter @filterSubscription
subscriptions = rsm.cropResults subscriptions, 'user'
cb null, subscriptions
class RetrieveNodeAffiliations extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
rsm = @req.rsm
t.getAffiliated @req.node, (err, affiliations) =>
if err
return cb err
affiliations = affiliations.filter @filterAffiliation
affiliations = rsm.cropResults affiliations, 'user'
cb null, affiliations
class RetrieveNodeConfiguration extends PrivilegedOperation
##
# Allowed for anyone. We do not have hidden channels yet.
#
# * Even closed channels should be browsable so that subscription
# can be requested at all
# * outcast shall not receive too much punishment (or glorification)
transaction: (t, cb) ->
t.getConfig @req.node, (err, config) ->
# wrap into { config: ...} result
cb err, { config }
class ManageNodeSubscriptions extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
defaultAffiliation = null
async.waterfall [(cb2) =>
t.getConfig @req.node, (error, config) =>
defaultAffiliation = config.defaultAffiliation or 'member'
cb2(error)
, (cb2) =>
async.forEach @req.subscriptions
, ({user, subscription}, cb3) =>
async.waterfall [(cb4) =>
if @req.node.indexOf("/user/#{user}/") == 0 and
subscription isnt 'subscribed'
cb4 new errors.Forbidden("You may not unsubscribe the owner")
else
t.setSubscription @req.node, user, null, subscription, cb4
, (cb4) =>
t.getAffiliation @req.node, user, cb4
, (affiliation, cb4) =>
if affiliation is 'none'
t.setAffiliation @req.node, user, defaultAffiliation, cb4
else
cb4()
], cb3
, cb2
], cb
notification: ->
@req.subscriptions.map ({user, subscription}) =>
{
type: 'subscription'
node: @req.node
user
subscription
}
class ManageNodeAffiliations extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
@newModerators = []
async.series @req.affiliations.map(({user, affiliation}) =>
(cb2) =>
async.waterfall [ (cb3) =>
t.getAffiliation @req.node, user, cb3
, (oldAffiliation, cb3) =>
if oldAffiliation is affiliation
# No change
cb3()
else
if oldAffiliation isnt 'owner' and
affiliation is 'owner' and
@actorAffiliation isnt 'owner'
# Non-owner tries to elect a new owner!
cb3 new errors.Forbidden("You may not elect a new owner")
else
async.series [ (cb4) =>
if not canModerate(oldAffiliation) and
canModerate(affiliation)
t.getSubscriptionListener @req.node, user, (err, listener) =>
if (not err) and listener
@newModerators.push { user, listener, node: @req.node }
cb4 err
else
cb4()
, (cb4) =>
if @req.node.indexOf("/user/#{user}/") == 0 and
affiliation isnt 'owner'
cb4 new errors.Forbidden("You may not demote the owner")
else
t.setAffiliation @req.node, user, affiliation, cb4
], (err) ->
cb3 err
], cb2
), cb
notification: ->
affiliations = @req.affiliations.map ({user, affiliation}) =>
{
type: 'affiliation'
node: @req.node
user
affiliation
}
ALLOWED_ACCESS_MODELS = ['open', 'whitelist', 'authorize']
ALLOWED_PUBLISH_MODELS = ['open', 'subscribers', 'publishers']
class ManageNodeConfiguration extends PrivilegedOperation
requiredAffiliation: 'owner'
run: (cb) ->
# Validate some config
if @req.config.accessModel? and
ALLOWED_ACCESS_MODELS.indexOf(@req.config.accessModel) < 0
cb new errors.BadRequest("Invalid access model")
else if @req.config.publishModel? and
ALLOWED_PUBLISH_MODELS.indexOf(@req.config.publishModel) < 0
cb new errors.BadRequest("Invalid publish model")
else if @req.config.creationDate?
cb new errors.BadRequest("Cannot set creation date")
else
# All is well, actually run
super(cb)
privilegedTransaction: (t, cb) ->
t.setConfig @req.node, @req.config, cb
notification: ->
[{
type: 'config'
node: @req.node
config: @req.config
}]
##
# Removes all subscriptions of the actor, call back with all remote
# subscriptions that the backends must then unsubscribe for.
#
# Two uses:
#
# * Rm subscriptions of an anonymous (temporary) user
# * TODO: Completely clear out a user account
class RemoveUser extends ModelOperation
transaction: (t, cb) ->
t.getUserRemoteSubscriptions @req.actor, (err, subscriptions) =>
if err
return cb(err)
t.clearUserSubscriptions @req.actor, (err) =>
cb err, subscriptions
class AuthorizeSubscriber extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
if @req.allow
@subscription = 'subscribed'
unless isAffiliationAtLeast @actorAffiliation, @nodeConfig.defaultAffiliation
# Less than current affiliation? Bump up to defaultAffiliation
@affiliation = @nodeConfig.defaultAffiliation or 'member'
else
@subscription = 'none'
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.user, @req.sender, @subscription, cb2
, (cb2) =>
if @affiliation
t.setAffiliation @req.node, @req.user, @affiliation, cb2
else
cb2()
], (err) ->
cb err
notification: ->
ns = [{
type: 'subscription'
node: @req.node
user: @req.user
subscription: @subscription
}]
if @affiliation
ns.push
type: 'affiliation'
node: @req.node
user: @req.user
affiliation: @affiliation
ns
##
# MAM replay
# and authorization form query
#
# The RSM handling here respects only a <max/> value.
#
# Doesn't care about about subscriptions nodes.
class ReplayArchive extends ModelOperation
transaction: (t, cb) ->
max = @req.rsm?.max or 50
sent = 0
async.waterfall [ (cb2) =>
t.walkListenerArchive @req.sender, @req.start, @req.end, max, (results) =>
if sent < max
results.sort (a, b) ->
if a.updated < b.updated
-1
else if a.updated > b.updated
1
else
0
results = results.slice(0, max - sent)
@sendNotification results
sent += results.length
, cb2
, (cb2) =>
sent = 0
t.walkModeratorAuthorizationRequests @req.sender, (req) =>
if sent < max
req.type = 'authorizationPrompt'
@sendNotification req
sent++
, cb2
], cb
sendNotification: (results) ->
notification = Object.create(results)
notification.listener = @req.fullSender
notification.replay = true
@router.notify notification
class PushInbox extends ModelOperation
transaction: (t, cb) ->
notification = []
newNodes = []
newModerators = []
unsubscribedNodes = {}
async.waterfall [(cb2) =>
logger.debug "pushUpdates: #{inspect @req}"
async.filter @req, (update, cb3) =>
if update.type is 'subscription' and update.listener?
# Was successful remote subscription attempt
t.createNode update.node, (err, created) =>
if created
newNodes.push update.node
cb3 not err
else
# Just an update, to be cached locally?
t.nodeExists update.node, (err, exists) ->
cb3 not err and exists
, (updates) ->
cb2 null, updates
, (updates, cb2) =>
logger.debug "pushFilteredUpdates: #{inspect updates}"
async.forEach updates, (update, cb3) ->
switch update.type
when 'items'
notification.push update
{node, items} = update
async.forEach items, (item, cb4) ->
{id, el} = item
t.writeItem node, id, el, cb4
, cb3
when 'subscription'
notification.push update
{node, user, listener, subscription} = update
if subscription isnt 'subscribed'
unsubscribedNodes[node] = yes
t.setSubscription node, user, listener, subscription, cb3
when 'affiliation'
notification.push update
{node, user, affiliation} = update
t.getAffiliation node, user, (err, oldAffiliation) ->
if err
return cb3 err
async.series [ (cb4) =>
if not canModerate(oldAffiliation) and
canModerate(affiliation)
t.getSubscriptionListener node, user, (err, listener) ->
if (not err) and listener
newModerators.push { user, listener, node }
cb4 err
else
cb4()
, (cb4) =>
t.setAffiliation node, user, affiliation, cb4
], (err) ->
cb3 err
when 'config'
notification.push update
{node, config} = update
t.setConfig node, config, cb3
else
cb3 new errors.InternalServerError("Bogus push update type: #{update.type}")
, cb2
, (cb2) =>
# Memorize updates for notifications, same format:
@notification = -> notification
if newNodes.length > 0
@newNodes = newNodes
if newModerators.length > 0
@newModerators = newModerators
cb2()
, (cb2) =>
# no local subscriptions left to remote node? delete it.
checks = []
for own node, _ of unsubscribedNodes
checks.push (cb3) ->
t.getNodeListeners node, (err, listeners) ->
if err
return cb3 err
unless listeners? and listeners.length > 0
t.purgeNode node, cb3
async.parallel checks, cb2
], cb
class Notify extends ModelOperation
transaction: (t, cb) ->
async.waterfall [(cb2) =>
async.forEach @req, (update, cb3) =>
# First, we complete subscriptions node items
m = update.node.match(NODE_OWNER_TYPE_REGEXP)
# Fill in missing subscriptions node items
if update.type is 'items' and m?[2] is 'subscriptions'
subscriber = m[1]
t.getSubscriptions subscriber, (err, subscriptions) =>
if err
return cb3 err
async.map update.items, ({id, el}, cb4) =>
if el
# Content already exists, perhaps
# relaying a notification from another
# service
return cb4 null, { id, el }
userSubscriptions = subscriptions.filter (subscription) ->
subscription.node.indexOf("/user/#{id}/") is 0
affiliations = {}
async.forEach userSubscriptions, (subscription, cb5) =>
t.getAffiliation subscriber, subscription.node, (err, affiliation) =>
affiliations[subscription.node] = affiliation
cb5(err)
, (err) =>
el = new Element('query',
xmlns: NS.DISCO_ITEMS
'xmlns:pubsub': NS.PUBSUB
)
for subscription in userSubscriptions
itemAttrs =
jid: subscriber
node: subscription.node
itemAttrs['pubsub:subscription'] ?= subscription.subscription
itemAttrs['pubsub:affiliation'] ?= affiliations[subscription.node]
el.c('item', itemAttrs)
cb4 null, { id, el }
, (err, items) =>
if err
return cb3(err)
update.items = items
cb3()
else
cb3()
, cb2
, (cb2) =>
# Then, retrieve all listeners
# (assuming all updates pertain one single node)
# TODO: walk in batches
logger.debug "notifyNotification: #{inspect @req}"
t.getNodeListeners @req.node, cb2
, (listeners, cb2) =>
# Always notify all users pertained by a subscription
# notification, even if just unsubscribed.
for update in @req
if update.type is 'subscription' and
listeners.indexOf(update.user) < 0
listeners.push update.user
cb2 null, listeners
, (listeners, cb2) =>
moderatorListeners = []
otherListeners = []
async.forEach listeners, (listener, cb3) =>
t.getAffiliation @req.node, listener, (err, affiliation) ->
if err
return cb3 err
if canModerate affiliation
moderatorListeners.push listener
else
otherListeners.push listener
cb3()
, (err) =>
cb2 err, moderatorListeners, otherListeners
, (moderatorListeners, otherListeners, cb2) =>
# Send out through backends
if moderatorListeners.length > 0
for listener in moderatorListeners
notification = Object.create(@req)
notification.listener = listener
@router.notify notification
if otherListeners.length > 0
req = @req.filter (update) =>
switch update.type
when 'subscription'
PrivilegedOperation::filterSubscription update
when 'affiliation'
PrivilegedOperation::filterAffiliation update
else
yes
# Any left after filtering? Don't send empty
# notification when somebody got banned.
if req.length > 0
for listener in otherListeners
notification = Object.create(req)
notification.node = @req.node
notification.listener = listener
@router.notify notification
cb2()
], cb
class ModeratorNotify extends ModelOperation
transaction: (t, cb) ->
# TODO: walk in batches
logger.debug "moderatorNotifyNotification: #{inspect(@req)}"
t.getNodeModeratorListeners @req.node, (err, listeners) =>
if err
return cb err
for listener in listeners
notification = Object.create(@req)
notification.listener = listener
@router.notify notification
cb()
class NewModeratorNotify extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
async.parallel [ (cb2) =>
t.getPending @req.node, cb2
, (cb2) =>
t.getOutcast @req.node, cb2
], (err, [pendingUsers, bannedUsers]) =>
if err
return cb err
notification = []
notification.node = @req.node
notification.listener = @req.listener
for user in pendingUsers
notification.push
type: 'subscription'
node: @req.node
user: <NAME>
subscription: 'pending'
for user in bannedUsers
notification.push
type: 'affiliation'
node: @req.node
user: <NAME>
affiliation: 'outcast'
@router.notify notification
cb()
OPERATIONS =
'browse-info': BrowseInfo
'browse-node-info': BrowseNodeInfo
'browse-nodes': BrowseNodes
'browse-top-followed-nodes': BrowseTopFollowedNodes
'browse-top-published-nodes': BrowseTopPublishedNodes
'browse-node-items': BrowseNodeItems
'register-user': Register
'create-node': CreateNode
'publish-node-items': Publish
'subscribe-node': Subscribe
'unsubscribe-node': Unsubscribe
'retrieve-node-items': RetrieveItems
'retract-node-items': RetractItems
'retrieve-user-subscriptions': RetrieveUserSubscriptions
'retrieve-user-affiliations': RetrieveUserAffiliations
'retrieve-node-subscriptions': RetrieveNodeSubscriptions
'retrieve-node-affiliations': RetrieveNodeAffiliations
'retrieve-node-configuration': RetrieveNodeConfiguration
'manage-node-subscriptions': ManageNodeSubscriptions
'manage-node-affiliations': ManageNodeAffiliations
'manage-node-configuration': ManageNodeConfiguration
'remove-user': RemoveUser
'confirm-subscriber-authorization': AuthorizeSubscriber
'replay-archive': ReplayArchive
'push-inbox': PushInbox
exports.run = (router, request, cb) ->
opName = request.operation
unless opName
# No operation specified, reply immediately
return cb?()
opClass = OPERATIONS[opName]
unless opClass
logger.warn "Unimplemented operation #{opName}: #{inspect request}"
return cb?(new errors.FeatureNotImplemented("Unimplemented operation #{opName}"))
logger.debug "operations.run: #{inspect request}"
op = new opClass(router, request)
op.run (error, result) ->
if error
logger.warn "Operation #{opName} failed: #{error.stack or error}"
cb? error
else
# Successfully done
logger.debug "Operation #{opName} ran: #{inspect result}"
async.series [(cb2) ->
# Run notifications
if (notification = op.notification?())
# Extend by subscriptions node notifications
notification = notification.concat generateSubscriptionsNotifications(notification)
# Call Notify operation grouped by node
# (looks up subscribers by node)
blocks = []
for own node, notifications of groupByNode(notification)
notifications.node = node
do (notifications) ->
blocks.push (cb3) ->
new Notify(router, notifications).run (err) ->
if err
logger.error("Error running notifications: #{err.stack or err.message or err}")
cb3()
async.series blocks, cb2
else
cb2()
, (cb2) ->
if (notification = op.moderatorNotification?())
new ModeratorNotify(router, notification).run (err) ->
if err
logger.error("Error running notifications: #{err.stack or err.message or err}")
cb2()
else
cb2()
, (cb2) ->
if (op.newModerators and op.newModerators.length > 0)
blocks = []
for {user, node, listener} in op.newModerators
req =
operation: 'new-moderator-notification'
node: node
actor: user
listener: listener
do (req) ->
blocks.push (cb3) ->
new NewModeratorNotify(router, req).run (err) ->
if err
logger.error("Error running new moderator notification: #{err.stack or err.message or err}")
cb3()
async.series blocks, cb2
else
cb2()
, (cb2) ->
# May need to sync new nodes
if op.newNodes?
async.forEach op.newNodes, (node, cb3) ->
router.syncNode node, cb3
, cb2
else
cb2()
], ->
# Ignore any sync result
try
cb? null, result
catch e
logger.error e.stack or e
groupByNode = (updates) ->
result = {}
for update in updates
unless result.hasOwnProperty(update.node)
result[update.node] = []
result[update.node].push update
result
generateSubscriptionsNotifications = (updates) ->
itemIdsSeen = {}
updates.filter((update) ->
(update.type is 'subscription' and
update.subscription is 'subscribed') or
update.type is 'affiliation'
).map((update) ->
followee = update.node.match(NODE_OWNER_TYPE_REGEXP)?[1]
type: 'items'
node: "/user/#{update.user}/subscriptions"
items: [{ id: followee }]
# Actual item payload will be completed by Notify transaction
).filter((update) ->
itemId = update.items[0].id
if itemIdsSeen[itemId]?
no
else
itemIdsSeen[itemId] = yes
yes
)
| true | logger = require('../logger').makeLogger 'local/operations'
{inspect} = require('util')
{getNodeUser, getNodeType} = require('../util')
async = require('async')
uuid = require('node-uuid')
errors = require('../errors')
NS = require('../xmpp/ns')
{normalizeItem} = require('../normalize')
{Element} = require('node-xmpp')
runTransaction = null
exports.setModel = (model) ->
runTransaction = model.transaction
exports.checkCreateNode = null
defaultConfiguration = (user) ->
posts:
title: "#{user} Channel Posts"
description: "A buddycloud channel"
channelType: "personal"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "publisher"
status:
title: "#{user} Status Updates"
description: "M000D"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/previous':
title: "#{user} Previous Location"
description: "Where #{user} has been before"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/current':
title: "#{user} Current Location"
description: "Where #{user} is at now"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
'geo/next':
title: "#{user} Next Location"
description: "Where #{user} intends to go"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
subscriptions:
title: "#{user} Subscriptions"
description: "Browse my interests"
accessModel: "authorize"
publishModel: "publishers"
defaultAffiliation: "member"
# user is "topic@domain" string
defaultTopicConfiguration = (user) =>
posts:
title: "#{user} Topic Channel"
description: "All about #{user.split('@')?[0]}"
channelType: "topic"
accessModel: "open"
publishModel: "subscribers"
defaultAffiliation: "member"
NODE_OWNER_TYPE_REGEXP = /^\/user\/([^\/]+)\/?(.*)/
AFFILIATIONS = [
'outcast', 'none', 'member',
'publisher', 'moderator', 'owner'
]
isAffiliationAtLeast = (affiliation1, affiliation2) ->
i1 = AFFILIATIONS.indexOf(affiliation1)
i2 = AFFILIATIONS.indexOf(affiliation2)
if i2 < 0
false
else
i1 >= i2
canModerate = (affiliation) ->
affiliation is 'owner' or affiliation is 'moderator'
###
# Base Operations
###
##
# Is created with options from the request
#
# Implementations set result
class Operation
constructor: (@router, @req) ->
if @req.node? and
(m = @req.node.match(NODE_OWNER_TYPE_REGEXP)) and
m[2] is 'subscriptions'
# Affords for specialized items handling in RetrieveItems and Publish
@subscriptionsNodeOwner = m[1]
run: (cb) ->
cb new errorsFeature.NotImplemented("Operation defined but not yet implemented")
class ModelOperation extends Operation
run: (cb) ->
runTransaction (err, t) =>
if err
return cb err
opName = @req.operation or @constructor?.name or "?"
@transaction t, (err, results) ->
if err
logger.warn "Transaction #{opName} rollback: #{err}"
t.rollback ->
cb err
else
t.commit ->
logger.debug "Transaction #{opName} committed"
cb null, results
# Must be implemented by subclass
transaction: (t, cb) ->
cb null
class PrivilegedOperation extends ModelOperation
transaction: (t, cb) ->
async.waterfall [ (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
@checkAccessModel t, cb2
, (cb2) =>
@checkRequiredAffiliation t, cb2
], (err) =>
if err
return cb err
@privilegedTransaction t, cb
fetchActorAffiliation: (t, cb) ->
unless @req.node
return cb()
if @req.actor.indexOf('@') >= 0
t.getAffiliation @req.node, @req.actor, (err, affiliation) =>
if err
return cb err
@actorAffiliation = affiliation or 'none'
else
# actor no user? check if listener!
t.getListenerAffiliations @req.node, @req.actor, (err, affiliations) =>
if err
return cb err
@actorAffiliation = 'none'
for affiliation in affiliations
if affiliation isnt @actorAffiliation and
isAffiliationAtLeast affiliation, @actorAffiliation
@actorAffiliation = affiliation
if canModerate @actorAffiliation
# Moderators get to see everything
@filterSubscription = @filterSubscriptionModerator
@filterAffiliation = @filterAffiliationModerator
cb()
fetchNodeConfig: (t, cb) ->
unless @req.node
return cb()
t.getConfig @req.node, (err, config) =>
if err
return cb err
@nodeConfig = config
cb()
checkAccessModel: (t, cb) ->
# Deny any outcast
if @actorAffiliation is 'outcast'
return cb new errors.Forbidden("Outcast")
# Set default according to node config
unless @requiredAffiliation
if @nodeConfig.accessModel is 'open'
# Open nodes allow anyone
@requiredAffiliation = 'none'
else
# For all other access models, actor has to be member
@requiredAffiliation = 'member'
cb()
checkRequiredAffiliation: (t, cb) ->
if @requiredAffiliation?.constructor is Function
requiredAffiliation = @requiredAffiliation()
else
requiredAffiliation = @requiredAffiliation
if not requiredAffiliation? or
isAffiliationAtLeast @actorAffiliation, requiredAffiliation
cb()
else
cb new errors.Forbidden("Requires affiliation #{requiredAffiliation} (you are #{@actorAffiliation})")
# Used by Publish operation
checkPublishModel: (t, cb) ->
pass = false
switch @nodeConfig.publishModel
when 'open'
pass = true
when 'members'
pass = isAffiliationAtLeast @actorAffiliation, 'member'
when 'publishers'
pass = isAffiliationAtLeast @actorAffiliation, 'publisher'
else
# Owners can always post
pass = (@actorAffiliation is 'owner')
if pass
cb()
else if @nodeConfig.publishModel is 'subscribers'
# Special handling because subscription state must be
# fetched
t.getSubscription @req.node, @req.actor, (err, subscription) ->
if !err and subscription is 'subscribed'
cb()
else
cb err or new errors.Forbidden("Only subscribers may publish")
else
cb new errors.Forbidden("Only #{@nodeConfig.publishModel} may publish")
filterSubscription: (subscription) =>
subscription.jid is @actor or
subscription.subscription is 'subscribed'
filterAffiliation: (affiliation) ->
affiliation.affiliation isnt 'outcast'
filterSubscriptionModerator: (subscription) ->
yes
filterAffiliationModerator: (affiliation) ->
yes
###
# Discrete Operations
###
class BrowseInfo extends Operation
run: (cb) ->
cb null,
features: [
NS.DISCO_INFO, NS.DISCO_ITEMS,
NS.REGISTER,
NS.PUBSUB, NS.PUBSUB_OWNER
]
identities: [{
category: "pubsub"
type: "service"
name: "XEP-0060 service"
}, {
category: "pubsub"
type: "channels"
name: "Channels service"
}, {
category: "pubsub"
type: "inbox"
name: "Channels inbox service"
}]
class BrowseNodeInfo extends PrivilegedOperation
##
# See access control notice of RetrieveNodeConfiguration
transaction: (t, cb) ->
t.getConfig @req.node, (err, config) =>
cb err,
node: @req.node
features: [
NS.DISCO_INFO, NS.DISCO_ITEMS,
NS.REGISTER,
NS.PUBSUB, NS.PUBSUB_OWNER
]
identities: [{
category: "pubsub"
type: "leaf"
name: "XEP-0060 node"
}, {
category: "pubsub"
type: "channel"
name: "buddycloud channel"
}]
config: config
class BrowseNodes extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
@fetchNodes t, (err, results) =>
if err
return cb err
results = rsm.cropResults(results, 'node')
results.forEach (item) =>
item.jid = @req.me
cb null, results
fetchNodes: (t, cb) ->
t.listNodes cb
class BrowseTopFollowedNodes extends BrowseNodes
fetchNodes: (t, cb) ->
max = @req.rsm.max or 10
t.getTopFollowedNodes max, null, null, cb
class BrowseTopPublishedNodes extends BrowseNodes
fetchNodes: (t, cb) ->
max = @req.rsm.max or 10
t.getTopPublishedNodes max, null, null, cb
class BrowseNodeItems extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
if @subscriptionsNodeOwner?
t.getSubscriptions @subscriptionsNodeOwner, (err, subscriptions) =>
if err
return cb err
# Group for item ids by followee:
subscriptionsByFollowee = {}
for subscription in subscriptions
if (m = subscription.node.match(NODE_OWNER_TYPE_REGEXP))
followee = m[1]
subscriptionsByFollowee[followee] = true
# Prepare RSM suitable result set
results = []
for own followee, present of subscriptionsByFollowee
results.push
name: followee
jid: @req.me
node: @req.node
# Sort for a stable traversal with multiple RSM'ed queries
results.sort (result1, result2) ->
if result1.name < result2.name
-1
else if result1.name > result2.name
1
else
0
# Apply RSM
results = @req.rsm.cropResults results, 'name'
cb null, results
else
t.getItemIds @req.node, (err, ids) =>
if err
return cb err
# Apply RSM
ids = @req.rsm.cropResults ids
results = ids.map (id) =>
{ name: id, jid: @req.me, node: @req.node }
results.node = @req.node
results.rsm = @req.rsm
cb null, results
class Register extends ModelOperation
run: (cb) ->
# check if this component is authoritative for the requesting
# user's domain
@router.authorizeFor @req.me, @req.actor, (err, valid) =>
if err
return cb err
if valid
# asynchronous super:
ModelOperation::run.call @, cb
else
cb new errors.NotAllowed("This is not the authoritative buddycloud-server for your domain")
transaction: (t, cb) ->
user = @req.actor
jobs = []
for own nodeType, config of defaultConfiguration(user)
# rescope loop variables:
do (nodeType, config) =>
jobs.push (cb2) =>
node = "/user/#{user}/#{nodeType}"
config.creationDate = new Date().toISOString()
@createNodeWithConfig t, node, config, cb2
async.series jobs, (err) ->
cb err
createNodeWithConfig: (t, node, config, cb) ->
user = @req.actor
created = no
async.waterfall [(cb2) ->
logger.info "creating #{node}"
t.createNode node, cb2
, (created_, cb2) ->
created = created_
t.setAffiliation node, user, 'owner', cb2
, (cb2) =>
t.setSubscription node, user, @req.sender, 'subscribed', cb2
, (cb2) ->
# if already present, don't overwrite config
if created
t.setConfig node, config, cb2
else
cb2 null
], cb
class CreateNode extends ModelOperation
transaction: (t, cb) ->
nodeUser = getNodeUser @req.node
unless nodeUser
return cb new errors.BadRequest("Malformed node")
if nodeUser.split("@")[0].length < 1
return cb new errors.BadRequest("Malformed node name")
isTopic = nodeUser isnt @req.actor
nodePrefix = "/user/#{nodeUser}/"
try
opts =
node: @req.node
nodeUser: nodeUser
actor: @req.actor
unless exports.checkCreateNode?(opts)
return cb new errors.NotAllowed("Node creation not allowed")
catch e
return cb e
async.waterfall [(cb2) =>
t.getOwnersByNodePrefix nodePrefix, cb2
, (owners, cb2) =>
if owners.length < 1 or owners.indexOf(@req.actor) >= 0
# Either there are no owners yet, or the user is
# already one of them.
t.createNode @req.node, cb2
else
cb2 new errors.NotAllowed("Nodes with prefix #{nodePrefix} are already owned by #{owners.join(', ')}")
, (created, cb2) =>
if created
# Worked, proceed
cb2 null
else
# Already exists
cb2 new errors.Conflict("Node #{@req.node} already exists")
, (cb2) =>
config = @req.config or {}
config.creationDate = new Date().toISOString()
# Pick config defaults
if isTopic
defaults = defaultTopicConfiguration nodeUser
else
defaults = defaultConfiguration nodeUser
defaults = defaults[getNodeType @req.node]
if defaults
# Mix into config
for own key, value of defaults
unless config
config = {}
# Don't overwrite existing
unless config[key]?
config[key] = value
# Set
t.setConfig @req.node, config, cb2
, (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, 'subscribed', cb2
, (cb2) =>
t.setAffiliation @req.node, @req.actor, 'owner', cb2
], cb
class Publish extends PrivilegedOperation
# checks affiliation with @checkPublishModel below
privilegedTransaction: (t, cb) ->
if @subscriptionsNode?
return cb new errors.NotAllowed("The subscriptions node is automagically populated")
async.waterfall [ (cb2) =>
@checkPublishModel t, cb2
, (cb2) =>
async.series @req.items.map((item) =>
(cb3) =>
async.waterfall [(cb4) =>
unless item.id?
item.id = uuid()
cb4 null, null
else
t.getItem @req.node, item.id, (err, item) ->
if err and err.constructor is errors.NotFound
cb4 null, null
else
cb4 err, item
, (oldItem, cb4) =>
normalizeItem @req, oldItem, item, cb4
, (newItem, cb4) =>
t.writeItem @req.node, newItem.id, newItem.el, (err) ->
cb4 err, newItem.id
], cb3
), cb2
], cb
notification: ->
[{
type: 'items'
node: @req.node
items: @req.items
}]
class Subscribe extends PrivilegedOperation
##
# Overwrites PrivilegedOperation#transaction() to use a different
# permissions checking model, but still uses its methods.
transaction: (t, cb) ->
async.waterfall [ (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
if @nodeConfig.accessModel is 'authorize'
@subscription = 'pending'
# Immediately return:
return cb2()
@subscription = 'subscribed'
defaultAffiliation = @nodeConfig.defaultAffiliation or 'none'
unless isAffiliationAtLeast @actorAffiliation, defaultAffiliation
# Less than current affiliation? Bump up to defaultAffiliation
@affiliation = @nodeConfig.defaultAffiliation or 'member'
@checkAccessModel t, cb2
], (err) =>
if err
return cb err
@privilegedTransaction t, cb
privilegedTransaction: (t, cb) ->
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, @subscription, cb2
, (cb2) =>
if @affiliation
t.setAffiliation @req.node, @req.actor, @affiliation, cb2
else
cb2()
], (err) =>
cb err,
user: @req.actor
subscription: @subscription
notification: ->
ns = [{
type: 'subscription'
node: @req.node
user: @req.actor
subscription: @subscription
}]
if @affiliation
ns.push
type: 'affiliation'
node: @req.node
user: @req.actor
affiliation: @affiliation
ns
moderatorNotification: ->
if @subscription is 'pending'
type: 'authorizationPrompt'
node: @req.node
user: @req.actor
##
# Not privileged as anybody should be able to unsubscribe him/herself
class Unsubscribe extends PrivilegedOperation
transaction: (t, cb) ->
if @req.node.indexOf("/user/#{@req.actor}/") == 0
return cb new errors.Forbidden("You may not unsubscribe from your own nodes")
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.actor, @req.sender, 'none', cb2
, (cb2) =>
@fetchActorAffiliation t, cb2
, (cb2) =>
@fetchNodeConfig t, cb2
, (cb2) =>
# only decrease if <= defaultAffiliation
if isAffiliationAtLeast(@nodeConfig.defaultAffiliation, @actorAffiliation) and
@actorAffiliation isnt 'outcast'
@actorAffiliation = 'none'
t.setAffiliation @req.node, @req.actor, 'none', cb2
else
cb2()
], cb
notification: ->
[{
type: 'subscription'
node: @req.node
user: @req.actor
subscription: 'none'
}, {
type: 'affiliation'
node: @req.node
user: @req.actor
affiliation: @actorAffiliation
}]
class RetrieveItems extends PrivilegedOperation
run: (cb) ->
if @subscriptionsNodeOwner?
# Special case: only handle virtually when local server is
# authoritative
@router.authorizeFor @req.me, @subscriptionsNodeOwner, (err, valid) =>
if err
return cb err
if valid
# Patch in virtual items
@privilegedTransaction = @retrieveSubscriptionsItems
# asynchronous super:
PrivilegedOperation::run.call @, cb
else
super
privilegedTransaction: (t, cb) ->
node = @req.node
rsm = @req.rsm
if @req.itemIds?
fetchItemIds = (cb2) =>
cb2 null, @req.itemIds
else
fetchItemIds = (cb2) ->
t.getItemIds node, cb2
fetchItemIds (err, ids) ->
# Apply RSM
ids = rsm.cropResults ids
# Fetching actual items
async.series ids.map((id) ->
(cb2) ->
t.getItem node, id, (err, el) ->
if err
return cb2 err
cb2 null,
id: id
el: el
), (err, results) ->
if err
cb err
else
# Annotate results array
results.node = node
results.rsm = rsm
cb null, results
##
# For /user/.../subscriptions
#
# <item id="PI:EMAIL:<EMAIL>END_PI">
# <query xmlns="http://jabber.org/protocol/disco#items" xmlns:pubsub="http://jabber.org/protocol/pubsub" xmlns:atom="http://www.w3.org/2005/Atom">
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/posts"
# pubsub:affiliation="publisher">
# <atom:updated>2010-12-26T17:30:00Z</atom:updated>
# </item>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/future"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/current"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/geo/previous"/>
# <item jid="sandbox.buddycloud.com"
# node="/user/koski@buddycloud.com/mood"
# pubsub:affiliation="member"/>
# </query>
# </item>
retrieveSubscriptionsItems: (t, cb) ->
async.waterfall [ (cb2) =>
t.getSubscriptions @subscriptionsNodeOwner, cb2
, (subscriptions, cb2) =>
# No pending subscriptions:
subscriptions = subscriptions.filter (subscription) ->
subscription.subscription is 'subscribed'
# Group for item ids by followee:
subscriptionsByFollowee = {}
for subscription in subscriptions
if (m = subscription.node.match(NODE_OWNER_TYPE_REGEXP))
followee = m[1]
unless subscriptionsByFollowee[followee]?
subscriptionsByFollowee[followee] = []
subscriptionsByFollowee[followee].push subscription
# Prepare RSM suitable result set
results = []
for own followee, followeeSubscriptions of subscriptionsByFollowee
results.push
id: followee
subscriptions: followeeSubscriptions
# Sort for a stable traversal with multiple RSM'ed queries
results.sort (result1, result2) ->
if result1.id < result2.id
-1
else if result1.id > result2.id
1
else
0
# Apply RSM
results = @req.rsm.cropResults results, 'id'
# get affiliations per node
async.forEachSeries results, (result, cb3) =>
async.forEach result.subscriptions, (subscription, cb4) =>
t.getAffiliation subscription.node, @subscriptionsNodeOwner, (err, affiliation) ->
subscription.affiliation ?= affiliation
cb4 err
, cb3
, (err) ->
cb2 err, results
, (results, cb2) =>
# Transform to specified items format
for item in results
item.el = new Element('query',
xmlns: NS.DISCO_ITEMS
'xmlns:pubsub': NS.PUBSUB
)
for subscription in item.subscriptions
itemAttrs =
jid: @subscriptionsNodeOwner
node: subscription.node
itemAttrs['pubsub:subscription'] ?= subscription.subscription
itemAttrs['pubsub:affiliation'] ?= subscription.affiliation
item.el.c('item', itemAttrs)
delete item.subscriptions
results.rsm = @req.rsm
results.node = @req.node
cb2 null, results
], cb
class RetractItems extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
async.waterfall [ (cb2) =>
if isAffiliationAtLeast @actorAffiliation, 'moderator'
# Owners and moderators may remove any post
cb2()
else
# Anyone may remove only their own posts
@checkItemsAuthor t, cb2
, (cb2) =>
async.forEach @req.items, (id, cb3) =>
t.deleteItem @req.node, id, cb3
, cb2
, (cb2) =>
if @req.notify
@notification = ->
[{
type: 'items'
node: @req.node
retract: @req.items
}]
cb2()
], cb
checkItemsAuthor: (t, cb) ->
async.forEachSeries @req.items, (id, cb2) =>
t.getItem @req.node, id, (err, el) =>
if err?.constructor is errors.NotFound
# Ignore non-existant item
return cb2()
else if err
return cb2(err)
# Check for post authorship
author = el?.is('entry') and
el.getChild('author')?.getChild('uri')?.getText()
if author is "acct:#{@req.actor}"
# Authenticated!
cb2()
else
cb2 new errors.NotAllowed("You may not retract other people's posts")
, cb
class RetrieveUserSubscriptions extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
t.getSubscriptions @req.actor, (err, subscriptions) ->
if err
return cb err
subscriptions = rsm.cropResults subscriptions, 'node'
cb null, subscriptions
class RetrieveUserAffiliations extends ModelOperation
transaction: (t, cb) ->
rsm = @req.rsm
t.getAffiliations @req.actor, (err, affiliations) ->
if err
return cb err
affiliations = rsm.cropResults affiliations, 'node'
cb null, affiliations
class RetrieveNodeSubscriptions extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
rsm = @req.rsm
t.getSubscribers @req.node, (err, subscriptions) =>
if err
return cb err
subscriptions = subscriptions.filter @filterSubscription
subscriptions = rsm.cropResults subscriptions, 'user'
cb null, subscriptions
class RetrieveNodeAffiliations extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
rsm = @req.rsm
t.getAffiliated @req.node, (err, affiliations) =>
if err
return cb err
affiliations = affiliations.filter @filterAffiliation
affiliations = rsm.cropResults affiliations, 'user'
cb null, affiliations
class RetrieveNodeConfiguration extends PrivilegedOperation
##
# Allowed for anyone. We do not have hidden channels yet.
#
# * Even closed channels should be browsable so that subscription
# can be requested at all
# * outcast shall not receive too much punishment (or glorification)
transaction: (t, cb) ->
t.getConfig @req.node, (err, config) ->
# wrap into { config: ...} result
cb err, { config }
class ManageNodeSubscriptions extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
defaultAffiliation = null
async.waterfall [(cb2) =>
t.getConfig @req.node, (error, config) =>
defaultAffiliation = config.defaultAffiliation or 'member'
cb2(error)
, (cb2) =>
async.forEach @req.subscriptions
, ({user, subscription}, cb3) =>
async.waterfall [(cb4) =>
if @req.node.indexOf("/user/#{user}/") == 0 and
subscription isnt 'subscribed'
cb4 new errors.Forbidden("You may not unsubscribe the owner")
else
t.setSubscription @req.node, user, null, subscription, cb4
, (cb4) =>
t.getAffiliation @req.node, user, cb4
, (affiliation, cb4) =>
if affiliation is 'none'
t.setAffiliation @req.node, user, defaultAffiliation, cb4
else
cb4()
], cb3
, cb2
], cb
notification: ->
@req.subscriptions.map ({user, subscription}) =>
{
type: 'subscription'
node: @req.node
user
subscription
}
class ManageNodeAffiliations extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
@newModerators = []
async.series @req.affiliations.map(({user, affiliation}) =>
(cb2) =>
async.waterfall [ (cb3) =>
t.getAffiliation @req.node, user, cb3
, (oldAffiliation, cb3) =>
if oldAffiliation is affiliation
# No change
cb3()
else
if oldAffiliation isnt 'owner' and
affiliation is 'owner' and
@actorAffiliation isnt 'owner'
# Non-owner tries to elect a new owner!
cb3 new errors.Forbidden("You may not elect a new owner")
else
async.series [ (cb4) =>
if not canModerate(oldAffiliation) and
canModerate(affiliation)
t.getSubscriptionListener @req.node, user, (err, listener) =>
if (not err) and listener
@newModerators.push { user, listener, node: @req.node }
cb4 err
else
cb4()
, (cb4) =>
if @req.node.indexOf("/user/#{user}/") == 0 and
affiliation isnt 'owner'
cb4 new errors.Forbidden("You may not demote the owner")
else
t.setAffiliation @req.node, user, affiliation, cb4
], (err) ->
cb3 err
], cb2
), cb
notification: ->
affiliations = @req.affiliations.map ({user, affiliation}) =>
{
type: 'affiliation'
node: @req.node
user
affiliation
}
ALLOWED_ACCESS_MODELS = ['open', 'whitelist', 'authorize']
ALLOWED_PUBLISH_MODELS = ['open', 'subscribers', 'publishers']
class ManageNodeConfiguration extends PrivilegedOperation
requiredAffiliation: 'owner'
run: (cb) ->
# Validate some config
if @req.config.accessModel? and
ALLOWED_ACCESS_MODELS.indexOf(@req.config.accessModel) < 0
cb new errors.BadRequest("Invalid access model")
else if @req.config.publishModel? and
ALLOWED_PUBLISH_MODELS.indexOf(@req.config.publishModel) < 0
cb new errors.BadRequest("Invalid publish model")
else if @req.config.creationDate?
cb new errors.BadRequest("Cannot set creation date")
else
# All is well, actually run
super(cb)
privilegedTransaction: (t, cb) ->
t.setConfig @req.node, @req.config, cb
notification: ->
[{
type: 'config'
node: @req.node
config: @req.config
}]
##
# Removes all subscriptions of the actor, call back with all remote
# subscriptions that the backends must then unsubscribe for.
#
# Two uses:
#
# * Rm subscriptions of an anonymous (temporary) user
# * TODO: Completely clear out a user account
class RemoveUser extends ModelOperation
transaction: (t, cb) ->
t.getUserRemoteSubscriptions @req.actor, (err, subscriptions) =>
if err
return cb(err)
t.clearUserSubscriptions @req.actor, (err) =>
cb err, subscriptions
class AuthorizeSubscriber extends PrivilegedOperation
requiredAffiliation: =>
if @nodeConfig.channelType is 'topic'
'moderator'
else
'owner'
privilegedTransaction: (t, cb) ->
if @req.allow
@subscription = 'subscribed'
unless isAffiliationAtLeast @actorAffiliation, @nodeConfig.defaultAffiliation
# Less than current affiliation? Bump up to defaultAffiliation
@affiliation = @nodeConfig.defaultAffiliation or 'member'
else
@subscription = 'none'
async.waterfall [ (cb2) =>
t.setSubscription @req.node, @req.user, @req.sender, @subscription, cb2
, (cb2) =>
if @affiliation
t.setAffiliation @req.node, @req.user, @affiliation, cb2
else
cb2()
], (err) ->
cb err
notification: ->
ns = [{
type: 'subscription'
node: @req.node
user: @req.user
subscription: @subscription
}]
if @affiliation
ns.push
type: 'affiliation'
node: @req.node
user: @req.user
affiliation: @affiliation
ns
##
# MAM replay
# and authorization form query
#
# The RSM handling here respects only a <max/> value.
#
# Doesn't care about about subscriptions nodes.
class ReplayArchive extends ModelOperation
transaction: (t, cb) ->
max = @req.rsm?.max or 50
sent = 0
async.waterfall [ (cb2) =>
t.walkListenerArchive @req.sender, @req.start, @req.end, max, (results) =>
if sent < max
results.sort (a, b) ->
if a.updated < b.updated
-1
else if a.updated > b.updated
1
else
0
results = results.slice(0, max - sent)
@sendNotification results
sent += results.length
, cb2
, (cb2) =>
sent = 0
t.walkModeratorAuthorizationRequests @req.sender, (req) =>
if sent < max
req.type = 'authorizationPrompt'
@sendNotification req
sent++
, cb2
], cb
sendNotification: (results) ->
notification = Object.create(results)
notification.listener = @req.fullSender
notification.replay = true
@router.notify notification
class PushInbox extends ModelOperation
transaction: (t, cb) ->
notification = []
newNodes = []
newModerators = []
unsubscribedNodes = {}
async.waterfall [(cb2) =>
logger.debug "pushUpdates: #{inspect @req}"
async.filter @req, (update, cb3) =>
if update.type is 'subscription' and update.listener?
# Was successful remote subscription attempt
t.createNode update.node, (err, created) =>
if created
newNodes.push update.node
cb3 not err
else
# Just an update, to be cached locally?
t.nodeExists update.node, (err, exists) ->
cb3 not err and exists
, (updates) ->
cb2 null, updates
, (updates, cb2) =>
logger.debug "pushFilteredUpdates: #{inspect updates}"
async.forEach updates, (update, cb3) ->
switch update.type
when 'items'
notification.push update
{node, items} = update
async.forEach items, (item, cb4) ->
{id, el} = item
t.writeItem node, id, el, cb4
, cb3
when 'subscription'
notification.push update
{node, user, listener, subscription} = update
if subscription isnt 'subscribed'
unsubscribedNodes[node] = yes
t.setSubscription node, user, listener, subscription, cb3
when 'affiliation'
notification.push update
{node, user, affiliation} = update
t.getAffiliation node, user, (err, oldAffiliation) ->
if err
return cb3 err
async.series [ (cb4) =>
if not canModerate(oldAffiliation) and
canModerate(affiliation)
t.getSubscriptionListener node, user, (err, listener) ->
if (not err) and listener
newModerators.push { user, listener, node }
cb4 err
else
cb4()
, (cb4) =>
t.setAffiliation node, user, affiliation, cb4
], (err) ->
cb3 err
when 'config'
notification.push update
{node, config} = update
t.setConfig node, config, cb3
else
cb3 new errors.InternalServerError("Bogus push update type: #{update.type}")
, cb2
, (cb2) =>
# Memorize updates for notifications, same format:
@notification = -> notification
if newNodes.length > 0
@newNodes = newNodes
if newModerators.length > 0
@newModerators = newModerators
cb2()
, (cb2) =>
# no local subscriptions left to remote node? delete it.
checks = []
for own node, _ of unsubscribedNodes
checks.push (cb3) ->
t.getNodeListeners node, (err, listeners) ->
if err
return cb3 err
unless listeners? and listeners.length > 0
t.purgeNode node, cb3
async.parallel checks, cb2
], cb
class Notify extends ModelOperation
transaction: (t, cb) ->
async.waterfall [(cb2) =>
async.forEach @req, (update, cb3) =>
# First, we complete subscriptions node items
m = update.node.match(NODE_OWNER_TYPE_REGEXP)
# Fill in missing subscriptions node items
if update.type is 'items' and m?[2] is 'subscriptions'
subscriber = m[1]
t.getSubscriptions subscriber, (err, subscriptions) =>
if err
return cb3 err
async.map update.items, ({id, el}, cb4) =>
if el
# Content already exists, perhaps
# relaying a notification from another
# service
return cb4 null, { id, el }
userSubscriptions = subscriptions.filter (subscription) ->
subscription.node.indexOf("/user/#{id}/") is 0
affiliations = {}
async.forEach userSubscriptions, (subscription, cb5) =>
t.getAffiliation subscriber, subscription.node, (err, affiliation) =>
affiliations[subscription.node] = affiliation
cb5(err)
, (err) =>
el = new Element('query',
xmlns: NS.DISCO_ITEMS
'xmlns:pubsub': NS.PUBSUB
)
for subscription in userSubscriptions
itemAttrs =
jid: subscriber
node: subscription.node
itemAttrs['pubsub:subscription'] ?= subscription.subscription
itemAttrs['pubsub:affiliation'] ?= affiliations[subscription.node]
el.c('item', itemAttrs)
cb4 null, { id, el }
, (err, items) =>
if err
return cb3(err)
update.items = items
cb3()
else
cb3()
, cb2
, (cb2) =>
# Then, retrieve all listeners
# (assuming all updates pertain one single node)
# TODO: walk in batches
logger.debug "notifyNotification: #{inspect @req}"
t.getNodeListeners @req.node, cb2
, (listeners, cb2) =>
# Always notify all users pertained by a subscription
# notification, even if just unsubscribed.
for update in @req
if update.type is 'subscription' and
listeners.indexOf(update.user) < 0
listeners.push update.user
cb2 null, listeners
, (listeners, cb2) =>
moderatorListeners = []
otherListeners = []
async.forEach listeners, (listener, cb3) =>
t.getAffiliation @req.node, listener, (err, affiliation) ->
if err
return cb3 err
if canModerate affiliation
moderatorListeners.push listener
else
otherListeners.push listener
cb3()
, (err) =>
cb2 err, moderatorListeners, otherListeners
, (moderatorListeners, otherListeners, cb2) =>
# Send out through backends
if moderatorListeners.length > 0
for listener in moderatorListeners
notification = Object.create(@req)
notification.listener = listener
@router.notify notification
if otherListeners.length > 0
req = @req.filter (update) =>
switch update.type
when 'subscription'
PrivilegedOperation::filterSubscription update
when 'affiliation'
PrivilegedOperation::filterAffiliation update
else
yes
# Any left after filtering? Don't send empty
# notification when somebody got banned.
if req.length > 0
for listener in otherListeners
notification = Object.create(req)
notification.node = @req.node
notification.listener = listener
@router.notify notification
cb2()
], cb
class ModeratorNotify extends ModelOperation
transaction: (t, cb) ->
# TODO: walk in batches
logger.debug "moderatorNotifyNotification: #{inspect(@req)}"
t.getNodeModeratorListeners @req.node, (err, listeners) =>
if err
return cb err
for listener in listeners
notification = Object.create(@req)
notification.listener = listener
@router.notify notification
cb()
class NewModeratorNotify extends PrivilegedOperation
privilegedTransaction: (t, cb) ->
async.parallel [ (cb2) =>
t.getPending @req.node, cb2
, (cb2) =>
t.getOutcast @req.node, cb2
], (err, [pendingUsers, bannedUsers]) =>
if err
return cb err
notification = []
notification.node = @req.node
notification.listener = @req.listener
for user in pendingUsers
notification.push
type: 'subscription'
node: @req.node
user: PI:NAME:<NAME>END_PI
subscription: 'pending'
for user in bannedUsers
notification.push
type: 'affiliation'
node: @req.node
user: PI:NAME:<NAME>END_PI
affiliation: 'outcast'
@router.notify notification
cb()
OPERATIONS =
'browse-info': BrowseInfo
'browse-node-info': BrowseNodeInfo
'browse-nodes': BrowseNodes
'browse-top-followed-nodes': BrowseTopFollowedNodes
'browse-top-published-nodes': BrowseTopPublishedNodes
'browse-node-items': BrowseNodeItems
'register-user': Register
'create-node': CreateNode
'publish-node-items': Publish
'subscribe-node': Subscribe
'unsubscribe-node': Unsubscribe
'retrieve-node-items': RetrieveItems
'retract-node-items': RetractItems
'retrieve-user-subscriptions': RetrieveUserSubscriptions
'retrieve-user-affiliations': RetrieveUserAffiliations
'retrieve-node-subscriptions': RetrieveNodeSubscriptions
'retrieve-node-affiliations': RetrieveNodeAffiliations
'retrieve-node-configuration': RetrieveNodeConfiguration
'manage-node-subscriptions': ManageNodeSubscriptions
'manage-node-affiliations': ManageNodeAffiliations
'manage-node-configuration': ManageNodeConfiguration
'remove-user': RemoveUser
'confirm-subscriber-authorization': AuthorizeSubscriber
'replay-archive': ReplayArchive
'push-inbox': PushInbox
exports.run = (router, request, cb) ->
opName = request.operation
unless opName
# No operation specified, reply immediately
return cb?()
opClass = OPERATIONS[opName]
unless opClass
logger.warn "Unimplemented operation #{opName}: #{inspect request}"
return cb?(new errors.FeatureNotImplemented("Unimplemented operation #{opName}"))
logger.debug "operations.run: #{inspect request}"
op = new opClass(router, request)
op.run (error, result) ->
if error
logger.warn "Operation #{opName} failed: #{error.stack or error}"
cb? error
else
# Successfully done
logger.debug "Operation #{opName} ran: #{inspect result}"
async.series [(cb2) ->
# Run notifications
if (notification = op.notification?())
# Extend by subscriptions node notifications
notification = notification.concat generateSubscriptionsNotifications(notification)
# Call Notify operation grouped by node
# (looks up subscribers by node)
blocks = []
for own node, notifications of groupByNode(notification)
notifications.node = node
do (notifications) ->
blocks.push (cb3) ->
new Notify(router, notifications).run (err) ->
if err
logger.error("Error running notifications: #{err.stack or err.message or err}")
cb3()
async.series blocks, cb2
else
cb2()
, (cb2) ->
if (notification = op.moderatorNotification?())
new ModeratorNotify(router, notification).run (err) ->
if err
logger.error("Error running notifications: #{err.stack or err.message or err}")
cb2()
else
cb2()
, (cb2) ->
if (op.newModerators and op.newModerators.length > 0)
blocks = []
for {user, node, listener} in op.newModerators
req =
operation: 'new-moderator-notification'
node: node
actor: user
listener: listener
do (req) ->
blocks.push (cb3) ->
new NewModeratorNotify(router, req).run (err) ->
if err
logger.error("Error running new moderator notification: #{err.stack or err.message or err}")
cb3()
async.series blocks, cb2
else
cb2()
, (cb2) ->
# May need to sync new nodes
if op.newNodes?
async.forEach op.newNodes, (node, cb3) ->
router.syncNode node, cb3
, cb2
else
cb2()
], ->
# Ignore any sync result
try
cb? null, result
catch e
logger.error e.stack or e
groupByNode = (updates) ->
result = {}
for update in updates
unless result.hasOwnProperty(update.node)
result[update.node] = []
result[update.node].push update
result
generateSubscriptionsNotifications = (updates) ->
itemIdsSeen = {}
updates.filter((update) ->
(update.type is 'subscription' and
update.subscription is 'subscribed') or
update.type is 'affiliation'
).map((update) ->
followee = update.node.match(NODE_OWNER_TYPE_REGEXP)?[1]
type: 'items'
node: "/user/#{update.user}/subscriptions"
items: [{ id: followee }]
# Actual item payload will be completed by Notify transaction
).filter((update) ->
itemId = update.items[0].id
if itemIdsSeen[itemId]?
no
else
itemIdsSeen[itemId] = yes
yes
)
|
[
{
"context": "---------------------------------\n# Copyright 2014 Patrick Mueller\n#\n# Licensed under the Apache License, Version 2.",
"end": 2472,
"score": 0.9998105764389038,
"start": 2457,
"tag": "NAME",
"value": "Patrick Mueller"
}
] | lib-src/XstackTrace.coffee | pmuellr/gh-miner | 1 | # Licensed under the Apache License. See footer for details.
path = require "path"
Error.prepareStackTrace = (error, structuredStackTrace) ->
result = []
longestFile = 0
longestLine = 0
result.push "--------------------------------------------"
result.push "error: #{error}"
result.push "stack:"
for callSite in structuredStackTrace
callSite.normalizedFileName = normalizeFileName callSite.getFileName()
file = callSite.normalizedFileName
line = "#{callSite.getLineNumber()}"
if file.length > longestFile
longestFile = file.length
if line.length > longestLine
longestLine = line.length
for callSite in structuredStackTrace
func = callSite.getFunction()
file = callSite.normalizedFileName
line = callSite.getLineNumber()
#file = path.basename(file)
line = "#{line}"
file = alignLeft( file, longestFile)
line = alignRight( line, longestLine)
if callSite.getTypeName() and callSite.getMethodName()
if callSite.getTypeName() is "Object"
funcName = callSite.getMethodName()
else
funcName = "#{callSite.getTypeName()}::#{callSite.getMethodName()}"
else if callSite.getFunctionName()
funcName = callSite.getFunctionName()
else
funcName = func.displayName || func.name || '<anon>'
#if funcName == "Module._compile"
# result.pop()
# result.pop()
# break
result.push " #{file} #{line} - #{funcName}()"
result.join "\n"
#-------------------------------------------------------------------------------
normalizeFileName = (fileName) ->
dir = path.dirname fileName
base = path.basename fileName
unless dir is ""
relDir = path.relative process.cwd(), dir
if relDir.length < dir.length
dir = relDir
path.join dir, base
#-------------------------------------------------------------------------------
alignRight = (string, length) ->
while string.length < length
string = " #{string}"
string
#-------------------------------------------------------------------------------
alignLeft = (string, length) ->
while string.length < length
string = "#{string} "
string
#-------------------------------------------------------------------------------
# Copyright 2014 Patrick Mueller
#
# 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.
#-------------------------------------------------------------------------------
| 70570 | # Licensed under the Apache License. See footer for details.
path = require "path"
Error.prepareStackTrace = (error, structuredStackTrace) ->
result = []
longestFile = 0
longestLine = 0
result.push "--------------------------------------------"
result.push "error: #{error}"
result.push "stack:"
for callSite in structuredStackTrace
callSite.normalizedFileName = normalizeFileName callSite.getFileName()
file = callSite.normalizedFileName
line = "#{callSite.getLineNumber()}"
if file.length > longestFile
longestFile = file.length
if line.length > longestLine
longestLine = line.length
for callSite in structuredStackTrace
func = callSite.getFunction()
file = callSite.normalizedFileName
line = callSite.getLineNumber()
#file = path.basename(file)
line = "#{line}"
file = alignLeft( file, longestFile)
line = alignRight( line, longestLine)
if callSite.getTypeName() and callSite.getMethodName()
if callSite.getTypeName() is "Object"
funcName = callSite.getMethodName()
else
funcName = "#{callSite.getTypeName()}::#{callSite.getMethodName()}"
else if callSite.getFunctionName()
funcName = callSite.getFunctionName()
else
funcName = func.displayName || func.name || '<anon>'
#if funcName == "Module._compile"
# result.pop()
# result.pop()
# break
result.push " #{file} #{line} - #{funcName}()"
result.join "\n"
#-------------------------------------------------------------------------------
normalizeFileName = (fileName) ->
dir = path.dirname fileName
base = path.basename fileName
unless dir is ""
relDir = path.relative process.cwd(), dir
if relDir.length < dir.length
dir = relDir
path.join dir, base
#-------------------------------------------------------------------------------
alignRight = (string, length) ->
while string.length < length
string = " #{string}"
string
#-------------------------------------------------------------------------------
alignLeft = (string, length) ->
while string.length < length
string = "#{string} "
string
#-------------------------------------------------------------------------------
# Copyright 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.
#-------------------------------------------------------------------------------
| true | # Licensed under the Apache License. See footer for details.
path = require "path"
Error.prepareStackTrace = (error, structuredStackTrace) ->
result = []
longestFile = 0
longestLine = 0
result.push "--------------------------------------------"
result.push "error: #{error}"
result.push "stack:"
for callSite in structuredStackTrace
callSite.normalizedFileName = normalizeFileName callSite.getFileName()
file = callSite.normalizedFileName
line = "#{callSite.getLineNumber()}"
if file.length > longestFile
longestFile = file.length
if line.length > longestLine
longestLine = line.length
for callSite in structuredStackTrace
func = callSite.getFunction()
file = callSite.normalizedFileName
line = callSite.getLineNumber()
#file = path.basename(file)
line = "#{line}"
file = alignLeft( file, longestFile)
line = alignRight( line, longestLine)
if callSite.getTypeName() and callSite.getMethodName()
if callSite.getTypeName() is "Object"
funcName = callSite.getMethodName()
else
funcName = "#{callSite.getTypeName()}::#{callSite.getMethodName()}"
else if callSite.getFunctionName()
funcName = callSite.getFunctionName()
else
funcName = func.displayName || func.name || '<anon>'
#if funcName == "Module._compile"
# result.pop()
# result.pop()
# break
result.push " #{file} #{line} - #{funcName}()"
result.join "\n"
#-------------------------------------------------------------------------------
normalizeFileName = (fileName) ->
dir = path.dirname fileName
base = path.basename fileName
unless dir is ""
relDir = path.relative process.cwd(), dir
if relDir.length < dir.length
dir = relDir
path.join dir, base
#-------------------------------------------------------------------------------
alignRight = (string, length) ->
while string.length < length
string = " #{string}"
string
#-------------------------------------------------------------------------------
alignLeft = (string, length) ->
while string.length < length
string = "#{string} "
string
#-------------------------------------------------------------------------------
# Copyright 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.
#-------------------------------------------------------------------------------
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999170303344727,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/lib/score-helper.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.
# TODO: move to application state repository thingy later
export class ScoreHelper
@hasMenu: (score) ->
score.replay || (currentUser.id? && score.user_id != currentUser.id)
| 76007 | # 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.
# TODO: move to application state repository thingy later
export class ScoreHelper
@hasMenu: (score) ->
score.replay || (currentUser.id? && score.user_id != currentUser.id)
| 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.
# TODO: move to application state repository thingy later
export class ScoreHelper
@hasMenu: (score) ->
score.replay || (currentUser.id? && score.user_id != currentUser.id)
|
[
{
"context": " getSourceFor: (spellKey) ->\n # spellKey ex: 'tharin/plan'\n code = @get('code')\n parts = spellKey.spl",
"end": 611,
"score": 0.9717100262641907,
"start": 600,
"tag": "KEY",
"value": "tharin/plan"
}
] | app/models/LevelSession.coffee | flauta/codecombat | 1 | CocoModel = require('./CocoModel')
module.exports = class LevelSession extends CocoModel
@className: "LevelSession"
urlRoot: "/db/level.session"
initialize: ->
super()
@on 'sync', (e) =>
state = @get('state') or {}
state.scripts ?= {}
@set('state', state)
updatePermissions: ->
permissions = @get 'permissions'
permissions = (p for p in permissions when p.target isnt 'public')
if @get('multiplayer')
permissions.push {target:'public', access:'write'}
@set 'permissions', permissions
getSourceFor: (spellKey) ->
# spellKey ex: 'tharin/plan'
code = @get('code')
parts = spellKey.split '/'
code?[parts[0]]?[parts[1]]
| 222113 | CocoModel = require('./CocoModel')
module.exports = class LevelSession extends CocoModel
@className: "LevelSession"
urlRoot: "/db/level.session"
initialize: ->
super()
@on 'sync', (e) =>
state = @get('state') or {}
state.scripts ?= {}
@set('state', state)
updatePermissions: ->
permissions = @get 'permissions'
permissions = (p for p in permissions when p.target isnt 'public')
if @get('multiplayer')
permissions.push {target:'public', access:'write'}
@set 'permissions', permissions
getSourceFor: (spellKey) ->
# spellKey ex: '<KEY>'
code = @get('code')
parts = spellKey.split '/'
code?[parts[0]]?[parts[1]]
| true | CocoModel = require('./CocoModel')
module.exports = class LevelSession extends CocoModel
@className: "LevelSession"
urlRoot: "/db/level.session"
initialize: ->
super()
@on 'sync', (e) =>
state = @get('state') or {}
state.scripts ?= {}
@set('state', state)
updatePermissions: ->
permissions = @get 'permissions'
permissions = (p for p in permissions when p.target isnt 'public')
if @get('multiplayer')
permissions.push {target:'public', access:'write'}
@set 'permissions', permissions
getSourceFor: (spellKey) ->
# spellKey ex: 'PI:KEY:<KEY>END_PI'
code = @get('code')
parts = spellKey.split '/'
code?[parts[0]]?[parts[1]]
|
[
{
"context": "# Copyright 2018 Thomson Reuters\n# Permission is hereby granted, free of charge, t",
"end": 32,
"score": 0.9998226165771484,
"start": 17,
"tag": "NAME",
"value": "Thomson Reuters"
}
] | lib/turtle-provider.coffee | thomsonreuters/AtomOntologyCompleter | 9 | # Copyright 2018 Thomson Reuters
# 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.
PACKAGE_ONTOLOGIES = require './ontologies.json'
module.exports =
selector: '.source.trig, .source.turtle'
disableForSelector: '.source.turtle .comment, .source.trig .comment'
inclusionPriority: 1
suggestionPriority: 1
filterSuggestions: true
mergedOntologies: null
localOntologies: null
prefixCompletions: []
localConfigChanged: ->
localEnabled = atom.config.get('turtle-completer.enableLocalOntologies')
value = atom.config.get('turtle-completer.localOntologyConfigFile')
console.log "Config change #{localEnabled} for #{value}"
try
if localEnabled
@localOntologies = require value
else
@localOntologies = null
catch error
console.log 'Unable to load ', value, error
@loadOntologies()
buildCompletionEntry: (prefix, ontology) ->
text: prefix
description: ontology.title
descriptionMoreURL: ontology.spec
loadOntologies: ->
completions = []
@mergedOntologies = []
for key, ontology of PACKAGE_ONTOLOGIES
@mergedOntologies[key] = ontology
if @localOntologies?
for key,ontology of @localOntologies
completions.push(@buildCompletionEntry(key,ontology))
@mergedOntologies[key] = ontology
for key,ontology of @mergedOntologies
if not @localOntologies? or key not of @localOntologies
completions.push(@buildCompletionEntry(key,ontology))
@prefixCompletions = completions
loadOntology: (ontologyPrefix) ->
if ontologyPrefix of @mergedOntologies
try
completions = require @mergedOntologies[ontologyPrefix].ontology
@mergedOntologies[ontologyPrefix].completions = completions
catch error
console.log 'Unable to load ontology with prefix ', ontologyPrefix
# there seems to be a bug with scopedescriptors not being correctly set
# midline. For now, just look at the preceding text and make a decision
# about which type of suggestion to offer based on whether there is a
# turtle prefix
getSuggestions: ({editor,bufferPosition,scopeDescriptor, prefix}) ->
return [] if not prefix? or not prefix.length
scopes = scopeDescriptor.getScopesArray()
# return nothing if deep in a scope that isn't prefixed URIs
return [] if scopes.length > 1 and
not scopes.includes('entity.name.tag.prefixed-uri.turtle')
lineToCursor = editor.getTextInRange([[bufferPosition.row, 0],
bufferPosition])
namespace = @determineNamespace(lineToCursor)
if namespace? and namespace of @mergedOntologies
if not @mergedOntologies[namespace].completions?
@loadOntology(namespace)
return @getMatches(@mergedOntologies[namespace].completions,prefix)
else
return @getMatches(@prefixCompletions,prefix)
return []
buildMatch: (match) ->
text: match.text
description: match.description
descriptionMoreURL: match.descriptionMoreURL
getMatches: (candidateArray, prefix) ->
return [] if not candidateArray?
matches = []
for candidate in candidateArray when not prefix.trim() or
firstCharsEqual(candidate.text,prefix)
matches.push(@buildMatch(candidate))
matches
determineNamespace: (line) ->
return null if not line?
regex = /([\w]+):[^:\s]+$/
match = regex.exec(line)
return match?[1] or null
firstCharsEqual = (str1, str2) ->
str1[0].toLowerCase() is str2[0].toLowerCase()
| 223420 | # Copyright 2018 <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
PACKAGE_ONTOLOGIES = require './ontologies.json'
module.exports =
selector: '.source.trig, .source.turtle'
disableForSelector: '.source.turtle .comment, .source.trig .comment'
inclusionPriority: 1
suggestionPriority: 1
filterSuggestions: true
mergedOntologies: null
localOntologies: null
prefixCompletions: []
localConfigChanged: ->
localEnabled = atom.config.get('turtle-completer.enableLocalOntologies')
value = atom.config.get('turtle-completer.localOntologyConfigFile')
console.log "Config change #{localEnabled} for #{value}"
try
if localEnabled
@localOntologies = require value
else
@localOntologies = null
catch error
console.log 'Unable to load ', value, error
@loadOntologies()
buildCompletionEntry: (prefix, ontology) ->
text: prefix
description: ontology.title
descriptionMoreURL: ontology.spec
loadOntologies: ->
completions = []
@mergedOntologies = []
for key, ontology of PACKAGE_ONTOLOGIES
@mergedOntologies[key] = ontology
if @localOntologies?
for key,ontology of @localOntologies
completions.push(@buildCompletionEntry(key,ontology))
@mergedOntologies[key] = ontology
for key,ontology of @mergedOntologies
if not @localOntologies? or key not of @localOntologies
completions.push(@buildCompletionEntry(key,ontology))
@prefixCompletions = completions
loadOntology: (ontologyPrefix) ->
if ontologyPrefix of @mergedOntologies
try
completions = require @mergedOntologies[ontologyPrefix].ontology
@mergedOntologies[ontologyPrefix].completions = completions
catch error
console.log 'Unable to load ontology with prefix ', ontologyPrefix
# there seems to be a bug with scopedescriptors not being correctly set
# midline. For now, just look at the preceding text and make a decision
# about which type of suggestion to offer based on whether there is a
# turtle prefix
getSuggestions: ({editor,bufferPosition,scopeDescriptor, prefix}) ->
return [] if not prefix? or not prefix.length
scopes = scopeDescriptor.getScopesArray()
# return nothing if deep in a scope that isn't prefixed URIs
return [] if scopes.length > 1 and
not scopes.includes('entity.name.tag.prefixed-uri.turtle')
lineToCursor = editor.getTextInRange([[bufferPosition.row, 0],
bufferPosition])
namespace = @determineNamespace(lineToCursor)
if namespace? and namespace of @mergedOntologies
if not @mergedOntologies[namespace].completions?
@loadOntology(namespace)
return @getMatches(@mergedOntologies[namespace].completions,prefix)
else
return @getMatches(@prefixCompletions,prefix)
return []
buildMatch: (match) ->
text: match.text
description: match.description
descriptionMoreURL: match.descriptionMoreURL
getMatches: (candidateArray, prefix) ->
return [] if not candidateArray?
matches = []
for candidate in candidateArray when not prefix.trim() or
firstCharsEqual(candidate.text,prefix)
matches.push(@buildMatch(candidate))
matches
determineNamespace: (line) ->
return null if not line?
regex = /([\w]+):[^:\s]+$/
match = regex.exec(line)
return match?[1] or null
firstCharsEqual = (str1, str2) ->
str1[0].toLowerCase() is str2[0].toLowerCase()
| true | # Copyright 2018 PI:NAME:<NAME>END_PI
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
PACKAGE_ONTOLOGIES = require './ontologies.json'
module.exports =
selector: '.source.trig, .source.turtle'
disableForSelector: '.source.turtle .comment, .source.trig .comment'
inclusionPriority: 1
suggestionPriority: 1
filterSuggestions: true
mergedOntologies: null
localOntologies: null
prefixCompletions: []
localConfigChanged: ->
localEnabled = atom.config.get('turtle-completer.enableLocalOntologies')
value = atom.config.get('turtle-completer.localOntologyConfigFile')
console.log "Config change #{localEnabled} for #{value}"
try
if localEnabled
@localOntologies = require value
else
@localOntologies = null
catch error
console.log 'Unable to load ', value, error
@loadOntologies()
buildCompletionEntry: (prefix, ontology) ->
text: prefix
description: ontology.title
descriptionMoreURL: ontology.spec
loadOntologies: ->
completions = []
@mergedOntologies = []
for key, ontology of PACKAGE_ONTOLOGIES
@mergedOntologies[key] = ontology
if @localOntologies?
for key,ontology of @localOntologies
completions.push(@buildCompletionEntry(key,ontology))
@mergedOntologies[key] = ontology
for key,ontology of @mergedOntologies
if not @localOntologies? or key not of @localOntologies
completions.push(@buildCompletionEntry(key,ontology))
@prefixCompletions = completions
loadOntology: (ontologyPrefix) ->
if ontologyPrefix of @mergedOntologies
try
completions = require @mergedOntologies[ontologyPrefix].ontology
@mergedOntologies[ontologyPrefix].completions = completions
catch error
console.log 'Unable to load ontology with prefix ', ontologyPrefix
# there seems to be a bug with scopedescriptors not being correctly set
# midline. For now, just look at the preceding text and make a decision
# about which type of suggestion to offer based on whether there is a
# turtle prefix
getSuggestions: ({editor,bufferPosition,scopeDescriptor, prefix}) ->
return [] if not prefix? or not prefix.length
scopes = scopeDescriptor.getScopesArray()
# return nothing if deep in a scope that isn't prefixed URIs
return [] if scopes.length > 1 and
not scopes.includes('entity.name.tag.prefixed-uri.turtle')
lineToCursor = editor.getTextInRange([[bufferPosition.row, 0],
bufferPosition])
namespace = @determineNamespace(lineToCursor)
if namespace? and namespace of @mergedOntologies
if not @mergedOntologies[namespace].completions?
@loadOntology(namespace)
return @getMatches(@mergedOntologies[namespace].completions,prefix)
else
return @getMatches(@prefixCompletions,prefix)
return []
buildMatch: (match) ->
text: match.text
description: match.description
descriptionMoreURL: match.descriptionMoreURL
getMatches: (candidateArray, prefix) ->
return [] if not candidateArray?
matches = []
for candidate in candidateArray when not prefix.trim() or
firstCharsEqual(candidate.text,prefix)
matches.push(@buildMatch(candidate))
matches
determineNamespace: (line) ->
return null if not line?
regex = /([\w]+):[^:\s]+$/
match = regex.exec(line)
return match?[1] or null
firstCharsEqual = (str1, str2) ->
str1[0].toLowerCase() is str2[0].toLowerCase()
|
[
{
"context": " {\n ship: 'X-Wing'\n pilot: 'Luke Skywalker'\n upgrades: [\n null\n ",
"end": 258,
"score": 0.9019069671630859,
"start": 244,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "ToLastShip} #{common.selectorForPilotDropdown}\", 'Luke Skywalker')\n\n .run ->\n test.done()\n\ncasper.test.b",
"end": 578,
"score": 0.955588698387146,
"start": 564,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "'#rebel-builder', [\n {\n ship: 'X-Wing'\n pilot: 'Luke Skywalker'\n ",
"end": 2209,
"score": 0.7124868035316467,
"start": 2205,
"tag": "NAME",
"value": "Wing"
},
{
"context": " {\n ship: 'X-Wing'\n pilot: 'Luke Skywalker'\n upgrades: [\n null\n ",
"end": 2245,
"score": 0.9922060966491699,
"start": 2231,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "{\n ship: 'YT-1300'\n pilot: 'Lando Calrissian'\n upgrades: [\n null\n ",
"end": 2675,
"score": 0.9843199849128723,
"start": 2659,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "builder #{common.selectorForUpgradeIndex 2, 3}\", 'Luke Skywalker')\n common.assertMatchIsDisabled(test, \"#rebel-",
"end": 3018,
"score": 0.9796591997146606,
"start": 3004,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "builder #{common.selectorForUpgradeIndex 2, 4}\", 'Luke Skywalker')\n common.assertMatchIsDisabled(test, \"#rebel-",
"end": 3132,
"score": 0.9675378799438477,
"start": 3118,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "builder #{common.selectorForUpgradeIndex 3, 3}\", 'Luke Skywalker')\n common.assertMatchIsDisabled(test, \"#rebel-",
"end": 3512,
"score": 0.9519047737121582,
"start": 3498,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": "builder #{common.selectorForUpgradeIndex 3, 4}\", 'Luke Skywalker')\n common.assertMatchIsDisabled(test, \"#rebel-",
"end": 3626,
"score": 0.9554966688156128,
"start": 3612,
"tag": "NAME",
"value": "Luke Skywalker"
},
{
"context": " {\n ship: 'X-Wing'\n pilot: 'Luke Skywalker'\n upgrades: [\n null\n ",
"end": 4111,
"score": 0.9200228452682495,
"start": 4097,
"tag": "NAME",
"value": "Luke Skywalker"
}
] | tests/test_unique.coffee | CrazyVulcan/xwing | 100 | common = require './common'
common.setup()
casper.test.begin "Named pilot uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Luke Skywalker'
upgrades: [
null
null
null
]
}
])
common.setShipType('#rebel-builder', 2, 'X-Wing')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForSecondToLastShip} #{common.selectorForPilotDropdown}", 'Luke Skywalker')
.run ->
test.done()
casper.test.begin "Named upgrade uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
null
'R2-F2'
null
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
null
null
null
]
}
])
common.assertMatchIsDisabled(test, "#rebel-builder .ship:nth-of-type(2) .addon-container .select2-container:nth-of-type(2)", 'R2-F2')
.run ->
test.done()
casper.test.begin "Unnamed pilot and upgrade non-uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
common.assertTotalPoints(test, '#rebel-builder', 64)
.run ->
test.done()
casper.test.begin "Uniqueness across pilot and crew", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Luke Skywalker'
upgrades: [
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Chewbacca'
upgrades: [
null
null
null
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Lando Calrissian'
upgrades: [
null
null
null
null
null
null
]
}
])
# Can't put Luke or Chewie on Chewie's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'Luke Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'Luke Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'Chewbacca')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'Chewbacca')
# Can't put Luke or Chewie on Lando's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 3}", 'Luke Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", 'Luke Skywalker')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 3}", 'Chewbacca')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", 'Chewbacca')
.run ->
test.done()
casper.test.begin "R2-D2 Astromech is mutex with R2-D2 Crew", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Luke Skywalker'
upgrades: [
null
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Chewbacca'
upgrades: [
null
null
null
null
null
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 3, 'R2-D2')
# Can't put R2-D2 on Chewie's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'R2-D2 (Crew)')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'R2-D2 (Crew)')
common.removeUpgrade('#rebel-builder', 1, 3)
common.addUpgrade('#rebel-builder', 2, 3, 'R2-D2 (Crew)')
# Can't put R2-D2 on Luke's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'R2-D2')
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
| 10416 | common = require './common'
common.setup()
casper.test.begin "Named pilot uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: '<NAME>'
upgrades: [
null
null
null
]
}
])
common.setShipType('#rebel-builder', 2, 'X-Wing')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForSecondToLastShip} #{common.selectorForPilotDropdown}", '<NAME>')
.run ->
test.done()
casper.test.begin "Named upgrade uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
null
'R2-F2'
null
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
null
null
null
]
}
])
common.assertMatchIsDisabled(test, "#rebel-builder .ship:nth-of-type(2) .addon-container .select2-container:nth-of-type(2)", 'R2-F2')
.run ->
test.done()
casper.test.begin "Unnamed pilot and upgrade non-uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
common.assertTotalPoints(test, '#rebel-builder', 64)
.run ->
test.done()
casper.test.begin "Uniqueness across pilot and crew", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-<NAME>'
pilot: '<NAME>'
upgrades: [
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Chewbacca'
upgrades: [
null
null
null
null
null
null
]
}
{
ship: 'YT-1300'
pilot: '<NAME>'
upgrades: [
null
null
null
null
null
null
]
}
])
# Can't put Luke or Chewie on Chewie's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", '<NAME>')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", '<NAME>')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'Chewbacca')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'Chewbacca')
# Can't put Luke or Chewie on Lando's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 3}", '<NAME>')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", '<NAME>')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 3}", 'Chewbacca')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", 'Chewbacca')
.run ->
test.done()
casper.test.begin "R2-D2 Astromech is mutex with R2-D2 Crew", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: '<NAME>'
upgrades: [
null
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Chewbacca'
upgrades: [
null
null
null
null
null
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 3, 'R2-D2')
# Can't put R2-D2 on Chewie's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'R2-D2 (Crew)')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'R2-D2 (Crew)')
common.removeUpgrade('#rebel-builder', 1, 3)
common.addUpgrade('#rebel-builder', 2, 3, 'R2-D2 (Crew)')
# Can't put R2-D2 on Luke's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'R2-D2')
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
| true | common = require './common'
common.setup()
casper.test.begin "Named pilot uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
null
null
null
]
}
])
common.setShipType('#rebel-builder', 2, 'X-Wing')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForSecondToLastShip} #{common.selectorForPilotDropdown}", 'PI:NAME:<NAME>END_PI')
.run ->
test.done()
casper.test.begin "Named upgrade uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
null
'R2-F2'
null
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
null
null
null
]
}
])
common.assertMatchIsDisabled(test, "#rebel-builder .ship:nth-of-type(2) .addon-container .select2-container:nth-of-type(2)", 'R2-F2')
.run ->
test.done()
casper.test.begin "Unnamed pilot and upgrade non-uniqueness", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
{
ship: 'X-Wing'
pilot: 'Red Squadron Pilot'
upgrades: [
'Proton Torpedoes'
'R2 Astromech'
'Engine Upgrade'
]
}
])
common.assertTotalPoints(test, '#rebel-builder', 64)
.run ->
test.done()
casper.test.begin "Uniqueness across pilot and crew", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-PI:NAME:<NAME>END_PI'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Chewbacca'
upgrades: [
null
null
null
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
null
null
null
null
null
null
]
}
])
# Can't put Luke or Chewie on Chewie's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'PI:NAME:<NAME>END_PI')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'PI:NAME:<NAME>END_PI')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'Chewbacca')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'Chewbacca')
# Can't put Luke or Chewie on Lando's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 3}", 'PI:NAME:<NAME>END_PI')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", 'PI:NAME:<NAME>END_PI')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 3}", 'Chewbacca')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 3, 4}", 'Chewbacca')
.run ->
test.done()
casper.test.begin "R2-D2 Astromech is mutex with R2-D2 Crew", (test) ->
common.waitForStartup('#rebel-builder')
common.createList('#rebel-builder', [
{
ship: 'X-Wing'
pilot: 'PI:NAME:<NAME>END_PI'
upgrades: [
null
null
null
null
]
}
{
ship: 'YT-1300'
pilot: 'Chewbacca'
upgrades: [
null
null
null
null
null
null
]
}
])
common.addUpgrade('#rebel-builder', 1, 3, 'R2-D2')
# Can't put R2-D2 on Chewie's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 3}", 'R2-D2 (Crew)')
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 2, 4}", 'R2-D2 (Crew)')
common.removeUpgrade('#rebel-builder', 1, 3)
common.addUpgrade('#rebel-builder', 2, 3, 'R2-D2 (Crew)')
# Can't put R2-D2 on Luke's ship
common.assertMatchIsDisabled(test, "#rebel-builder #{common.selectorForUpgradeIndex 1, 3}", 'R2-D2')
common.removeShip('#rebel-builder', 1)
common.removeShip('#rebel-builder', 1)
.run ->
test.done()
|
[
{
"context": "analytics.graphs\n\n margin = 20\n keyHeight = 20\n xAxisHeight = 20\n yAxisWidth = 40\n cont",
"end": 22787,
"score": 0.8457512855529785,
"start": 22785,
"tag": "KEY",
"value": "20"
}
] | app/views/admin/AnalyticsSubscriptionsView.coffee | JurianLock/codecombat | 0 | RootView = require 'views/core/RootView'
template = require 'templates/admin/analytics-subscriptions'
ThangType = require 'models/ThangType'
User = require 'models/User'
# TODO: Graphing code copied/mangled from campaign editor level view. OMG, DRY.
require 'vendor/d3'
module.exports = class AnalyticsSubscriptionsView extends RootView
id: 'admin-analytics-subscriptions-view'
template: template
events:
'click .btn-show-more-cancellations': 'onClickShowMoreCancellations'
constructor: (options) ->
super options
@showMoreCancellations = false
@resetSubscriptionsData()
if me.isAdmin()
@refreshData()
_.delay (=> @refreshData()), 30 * 60 * 1000
getRenderData: ->
context = super()
context.analytics = @analytics ? graphs: []
context.cancellations = if @showMoreCancellations then @cancellations else (@cancellations ? []).slice(0, 40)
context.showMoreCancellations = @showMoreCancellations
context.subs = _.cloneDeep(@subs ? []).reverse()
context.subscribers = @subscribers ? []
context.subscriberCancelled = _.find context.subscribers, (subscriber) -> subscriber.cancel
context.subscriberSponsored = _.find context.subscribers, (subscriber) -> subscriber.user?.stripe?.sponsorID
context.total = @total ? 0
context.monthlyChurn = @monthlyChurn ? 0.0
context.monthlyGrowth = @monthlyGrowth ? 0.0
context.outstandingCancels = @outstandingCancels ? []
context.refreshDataState = @refreshDataState
context
afterRender: ->
super()
@updateAnalyticsGraphs()
onClickShowMoreCancellations: (e) ->
@showMoreCancellations = true
@render?()
resetSubscriptionsData: ->
@analytics = graphs: []
@subs = []
@total = 0
@monthlyChurn = 0.0
@monthlyGrowth = 0.0
@refreshDataState = 'Fetching dashboard data...'
refreshData: ->
return unless me.isAdmin()
@resetSubscriptionsData()
@getCancellations (cancellations) =>
@cancellations = cancellations
@render?()
@getOutstandingCancelledSubscriptions cancellations, (outstandingCancels) =>
@outstandingCancels = outstandingCancels
@getSubscriptions cancellations, (subscriptions) =>
@updateAnalyticsGraphData()
@render?()
@getSubscribers subscriptions, =>
@render?()
updateFetchDataState: (msg) ->
@refreshDataState = msg
@render?()
getCancellations: (done) ->
cancellations = []
@getCancellationEvents (cancelledSubscriptions) =>
# Get user objects for cancelled subscriptions
userIDs = _.map cancelledSubscriptions, (a) -> a.userID
options =
url: '/db/user/-/users'
method: 'POST'
data: {ids: userIDs}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get cancelled users', response
options.success = (cancelledUsers, response, options) =>
return if @destroyed
userMap = {}
userMap[user._id] = user for user in cancelledUsers
for cancellation in cancelledSubscriptions when cancellation.userID of userMap
cancellation.user = userMap[cancellation.userID]
cancellation.level = User.levelFromExp(cancellation.user.points)
cancelledSubscriptions.sort (a, b) -> if a.cancel > b.cancel then -1 else 1
done(cancelledSubscriptions)
@updateFetchDataState 'Fetching cancellations...'
@supermodel.addRequestResource('get_cancelled_users', options, 0).load()
getCancellationEvents: (done) ->
cancellationEvents = []
earliestEventDate = new Date()
earliestEventDate.setUTCMonth(earliestEventDate.getUTCMonth() - 2)
earliestEventDate.setUTCDate(earliestEventDate.getUTCDate() - 8)
nextBatch = (starting_after, done) =>
@updateFetchDataState "Fetching cancellations #{cancellationEvents.length}..."
options =
url: '/db/subscription/-/stripe_events'
method: 'POST'
data: {options: {limit: 100}}
options.data.options.starting_after = starting_after if starting_after
options.data.options.type = 'customer.subscription.updated'
options.data.options.created = gte: Math.floor(earliestEventDate.getTime() / 1000)
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get cancelled events', response
options.success = (events, response, options) =>
return if @destroyed
for event in events.data
continue unless event.data?.object?.cancel_at_period_end is true and event.data?.previous_attributes.cancel_at_period_end is false
continue unless event.data?.object?.plan?.id is 'basic'
continue unless event.data?.object?.id?
cancellationEvents.push
cancel: new Date(event.created * 1000)
customerID: event.data.object.customer
start: new Date(event.data.object.start * 1000)
subscriptionID: event.data.object.id
userID: event.data.object.metadata?.id
if events.has_more
return nextBatch(events.data[events.data.length - 1].id, done)
done(cancellationEvents)
@supermodel.addRequestResource('get_cancellation_events', options, 0).load()
nextBatch null, done
getOutstandingCancelledSubscriptions: (cancellations, done) ->
@updateFetchDataState "Fetching oustanding cancellations..."
options =
url: '/db/subscription/-/stripe_subscriptions'
method: 'POST'
data: {subscriptions: cancellations}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get outstanding cancellations', response
options.success = (subscriptions, response, options) =>
return if @destroyed
outstandingCancelledSubscriptions = []
for subscription in subscriptions
continue unless subscription?.cancel_at_period_end
outstandingCancelledSubscriptions.push
cancel: new Date(subscription.canceled_at * 1000)
customerID: subscription.customerID
start: new Date(subscription.start * 1000)
subscriptionID: subscription.id
userID: subscription.metadata?.id
done(outstandingCancelledSubscriptions)
@supermodel.addRequestResource('get_outstanding_cancelled_subscriptions', options, 0).load()
getSubscribers: (subscriptions, done) ->
# console.log 'getSubscribers', subscriptions.length
@updateFetchDataState "Fetching recent subscribers..."
@render?()
maxSubscribers = 40
subscribers = _.filter subscriptions, (a) -> a.userID?
subscribers.sort (a, b) -> if a.start > b.start then -1 else 1
subscribers = subscribers.slice(0, maxSubscribers)
subscriberUserIDs = _.map subscribers, (a) -> a.userID
options =
url: '/db/subscription/-/subscribers'
method: 'POST'
data: {ids: subscriberUserIDs}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get subscribers', response
options.success = (userMap, response, options) =>
return if @destroyed
for subscriber in subscribers
continue unless subscriber.userID of userMap
subscriber.user = userMap[subscriber.userID]
subscriber.level = User.levelFromExp subscriber.user.points
if hero = subscriber.user.heroConfig?.thangType
subscriber.hero = _.invert(ThangType.heroes)[hero]
@subscribers = subscribers
done()
@supermodel.addRequestResource('get_subscribers', options, 0).load()
getSubscriptions: (cancellations=[], done) ->
@getInvoices (invoices) =>
subMap = {}
for invoice in invoices
subID = invoice.subscriptionID
if subID of subMap
subMap[subID].first = new Date(invoice.date)
else
subMap[subID] =
first: new Date(invoice.date)
last: new Date(invoice.date)
customerID: invoice.customerID
subMap[subID].userID = invoice.userID if invoice.userID
@getSponsors (sponsors) =>
@getRecipientSubscriptions sponsors, (recipientSubscriptions) =>
for subscription in recipientSubscriptions
subMap[subscription.id] =
first: new Date(subscription.start * 1000)
subMap[subscription.id].userID = subscription.metadata.id if subscription.metadata?.id?
if subscription.cancel_at_period_end
subMap[subscription.id].cancel = new Date(subscription.canceled_at * 1000)
subMap[subscription.id].end = new Date(subscription.current_period_end * 1000)
subs = []
for subID of subMap
sub =
customerID: subMap[subID].customerID
start: subMap[subID].first
subscriptionID: subID
sub.cancel = subMap[subID].cancel if subMap[subID].cancel
oneMonthAgo = new Date()
oneMonthAgo.setUTCMonth(oneMonthAgo.getUTCMonth() - 1)
if subMap[subID].end?
sub.end = subMap[subID].end
else if subMap[subID].last < oneMonthAgo
sub.end = subMap[subID].last
sub.end.setUTCMonth(sub.end.getUTCMonth() + 1)
sub.userID = subMap[subID].userID if subMap[subID].userID
subs.push sub
subDayMap = {}
for sub in subs
startDay = sub.start.toISOString().substring(0, 10)
subDayMap[startDay] ?= {}
subDayMap[startDay]['start'] ?= 0
subDayMap[startDay]['start']++
if endDay = sub?.end?.toISOString().substring(0, 10)
subDayMap[endDay] ?= {}
subDayMap[endDay]['end'] ?= 0
subDayMap[endDay]['end']++
for cancellation in cancellations
if cancellation.subscriptionID is sub.subscriptionID
sub.cancel = cancellation.cancel
cancelDay = cancellation.cancel.toISOString().substring(0, 10)
subDayMap[cancelDay] ?= {}
subDayMap[cancelDay]['cancel'] ?= 0
subDayMap[cancelDay]['cancel']++
break
today = new Date().toISOString().substring(0, 10)
for day of subDayMap
continue if day > today
@subs.push
day: day
started: subDayMap[day]['start'] or 0
cancelled: subDayMap[day]['cancel'] or 0
ended: subDayMap[day]['end'] or 0
@subs.sort (a, b) -> a.day.localeCompare(b.day)
cancelledThisMonth = 0
totalLastMonth = 0
for sub, i in @subs
@total += sub.started
@total -= sub.ended
sub.total = @total
cancelledThisMonth += sub.cancelled if @subs.length - i < 31
totalLastMonth = @total if @subs.length - i is 31
@monthlyChurn = cancelledThisMonth / totalLastMonth * 100.0 if totalLastMonth > 0
if @subs.length > 30 and @subs[@subs.length - 31].total > 0
startMonthTotal = @subs[@subs.length - 31].total
endMonthTotal = @subs[@subs.length - 1].total
@monthlyGrowth = (endMonthTotal / startMonthTotal - 1) * 100
done(subs)
getInvoices: (done) ->
invoices = {}
addInvoice = (invoice) =>
return unless invoice.paid
return unless invoice.subscription
return unless invoice.total > 0
return unless invoice.lines?.data?[0]?.plan?.id is 'basic'
invoices[invoice.id] =
customerID: invoice.customer
subscriptionID: invoice.subscription
date: new Date(invoice.date * 1000)
invoices[invoice.id].userID = invoice.lines.data[0].metadata.id if invoice.lines?.data?[0]?.metadata?.id
getLiveInvoices = (ending_before, done) =>
nextBatch = (ending_before, done) =>
@updateFetchDataState "Fetching invoices #{Object.keys(invoices).length}..."
options =
url: '/db/subscription/-/stripe_invoices'
method: 'POST'
data: {options: {ending_before: ending_before, limit: 100}}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get live invoices', response
options.success = (invoiceData, response, options) =>
return if @destroyed
addInvoice(invoice) for invoice in invoiceData.data
if invoiceData.has_more
return nextBatch(invoiceData.data[0].id, done)
else
invoices = (invoice for invoiceID, invoice of invoices)
invoices.sort (a, b) -> if a.date > b.date then -1 else 1
return done(invoices)
@supermodel.addRequestResource('get_live_invoices', options, 0).load()
nextBatch ending_before, done
getAnalyticsInvoices = (done) =>
@updateFetchDataState "Fetching invoices #{Object.keys(invoices).length}..."
options =
url: '/db/analytics.stripe.invoice/-/all'
method: 'GET'
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get analytics stripe invoices', response
options.success = (docs, response, options) =>
return if @destroyed
docs.sort (a, b) -> b.date - a.date
addInvoice(doc.properties) for doc in docs
getLiveInvoices(docs[0]._id, done)
@supermodel.addRequestResource('get_analytics_invoices', options, 0).load()
getAnalyticsInvoices(done)
getRecipientSubscriptions: (sponsors, done) ->
@updateFetchDataState "Fetching recipient subscriptions..."
subscriptionsToFetch = []
for user in sponsors
for recipient in user.stripe?.recipients
subscriptionsToFetch.push
customerID: user.stripe.customerID
subscriptionID: recipient.subscriptionID
return done([]) if _.isEmpty subscriptionsToFetch
options =
url: '/db/subscription/-/stripe_subscriptions'
method: 'POST'
data: {subscriptions: subscriptionsToFetch}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get recipient subscriptions', response
options.success = (subscriptions, response, options) =>
return if @destroyed
done(subscriptions)
@supermodel.addRequestResource('get_recipient_subscriptions', options, 0).load()
getSponsors: (done) ->
@updateFetchDataState "Fetching sponsors..."
options =
url: '/db/user/-/sub_sponsors'
method: 'POST'
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get sponsors', response
options.success = (sponsors, response, options) =>
return if @destroyed
done(sponsors)
@supermodel.addRequestResource('get_sponsors', options, 0).load()
updateAnalyticsGraphData: ->
# console.log 'updateAnalyticsGraphData'
# Build graphs based on available @analytics data
# Currently only one graph
@analytics.graphs = []
return unless @subs?.length > 0
@addGraphData(60)
@addGraphData(180, true)
addGraphData: (timeframeDays, skipCancelled=false) ->
graph = {graphID: 'total-subs', lines: []}
# TODO: Where should this metadata live?
# TODO: lineIDs assumed to be unique across graphs
totalSubsID = 'total-subs'
startedSubsID = 'started-subs'
cancelledSubsID = 'cancelled-subs'
netSubsID = 'net-subs'
averageNewID = 'average-new'
lineMetadata = {}
lineMetadata[totalSubsID] =
description: 'Total Active Subscriptions'
color: 'green'
strokeWidth: 1
lineMetadata[startedSubsID] =
description: 'New Subscriptions'
color: 'blue'
strokeWidth: 1
lineMetadata[cancelledSubsID] =
description: 'Cancelled Subscriptions'
color: 'red'
strokeWidth: 1
lineMetadata[netSubsID] =
description: '7-day Average Net Subscriptions (started - cancelled)'
color: 'black'
strokeWidth: 4
lineMetadata[averageNewID] =
description: '7-day Average New Subscriptions'
color: 'black'
strokeWidth: 4
days = (sub.day for sub in @subs)
if days.length > 0
currentIndex = 0
currentDay = days[currentIndex]
currentDate = new Date(currentDay + "T00:00:00.000Z")
lastDay = days[days.length - 1]
while currentDay isnt lastDay
days.splice currentIndex, 0, currentDay if days[currentIndex] isnt currentDay
currentIndex++
currentDate.setUTCDate(currentDate.getUTCDate() + 1)
currentDay = currentDate.toISOString().substr(0, 10)
## Totals
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: i
y: sub.total
day: sub.day
pointID: "#{totalSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{totalSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: totalSubsID
enabled: true
points: levelPoints
description: lineMetadata[totalSubsID].description
lineColor: lineMetadata[totalSubsID].color
strokeWidth: lineMetadata[totalSubsID].strokeWidth
min: 0
max: d3.max(@subs, (d) -> d.total)
## Started
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: i
y: sub.started
day: sub.day
pointID: "#{startedSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{startedSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: startedSubsID
enabled: true
points: levelPoints
description: lineMetadata[startedSubsID].description
lineColor: lineMetadata[startedSubsID].color
strokeWidth: lineMetadata[startedSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
if skipCancelled
## 7-Day average started
# Build line data
levelPoints = []
sevenStarts = []
for sub, i in @subs
average = 0
sevenStarts.push sub.started
if sevenStarts.length > 7
sevenStarts.shift()
if sevenStarts.length is 7
average = sevenStarts.reduce((a, b) -> a + b) / sevenStarts.length
levelPoints.push
x: i
y: average
day: sub.day
pointID: "#{averageNewID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{averageNewID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: averageNewID
enabled: true
points: levelPoints
description: lineMetadata[averageNewID].description
lineColor: lineMetadata[averageNewID].color
strokeWidth: lineMetadata[averageNewID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
else
## Cancelled
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: @subs.length - 30 + i
y: sub.cancelled
day: sub.day
pointID: "#{cancelledSubsID}#{@subs.length - 30 + i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{cancelledSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: cancelledSubsID
enabled: true
points: levelPoints
description: lineMetadata[cancelledSubsID].description
lineColor: lineMetadata[cancelledSubsID].color
strokeWidth: lineMetadata[cancelledSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
## 7-Day Net Subs
# Build line data
levelPoints = []
sevenNets = []
for sub, i in @subs
net = 0
sevenNets.push sub.started - sub.cancelled
if sevenNets.length > 7
sevenNets.shift()
if sevenNets.length is 7
net = sevenNets.reduce((a, b) -> a + b) / 7
levelPoints.push
x: i
y: net
day: sub.day
pointID: "#{netSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{netSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: netSubsID
enabled: true
points: levelPoints
description: lineMetadata[netSubsID].description
lineColor: lineMetadata[netSubsID].color
strokeWidth: lineMetadata[netSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
@analytics.graphs.push(graph)
updateAnalyticsGraphs: ->
# Build d3 graphs
return unless @analytics?.graphs?.length > 0
containerSelector = '.line-graph-container'
# console.log 'updateAnalyticsGraphs', containerSelector, @analytics.graphs
margin = 20
keyHeight = 20
xAxisHeight = 20
yAxisWidth = 40
containerWidth = $(containerSelector).width()
containerHeight = $(containerSelector).height()
for graph in @analytics.graphs
graphLineCount = _.reduce graph.lines, ((sum, item) -> if item.enabled then sum + 1 else sum), 0
svg = d3.select(containerSelector).append("svg")
.attr("width", containerWidth)
.attr("height", containerHeight)
width = containerWidth - margin * 2 - yAxisWidth * 2
height = containerHeight - margin * 2 - xAxisHeight - keyHeight * graphLineCount
currentLine = 0
for line in graph.lines
continue unless line.enabled
xRange = d3.scale.linear().range([0, width]).domain([d3.min(line.points, (d) -> d.x), d3.max(line.points, (d) -> d.x)])
yRange = d3.scale.linear().range([height, 0]).domain([line.min, line.max])
# x-Axis
if currentLine is 0
startDay = new Date(line.points[0].day)
endDay = new Date(line.points[line.points.length - 1].day)
xAxisRange = d3.time.scale()
.domain([startDay, endDay])
.range([0, width])
xAxis = d3.svg.axis()
.scale(xAxisRange)
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.selectAll("text")
.attr("dy", ".35em")
.attr("transform", "translate(" + (margin + yAxisWidth) + "," + (height + margin) + ")")
.style("text-anchor", "start")
if line.lineID is 'started-subs'
# Horizontal guidelines
marks = (Math.round(i * line.max / 5) for i in [1...5])
svg.selectAll(".line")
.data(marks)
.enter()
.append("line")
.attr("x1", margin + yAxisWidth * 2)
.attr("y1", (d) -> margin + yRange(d))
.attr("x2", margin + yAxisWidth * 2 + width)
.attr("y2", (d) -> margin + yRange(d))
.attr("stroke", line.lineColor)
.style("opacity", "0.5")
if currentLine < 2
# y-Axis
yAxisRange = d3.scale.linear().range([height, 0]).domain([line.min, line.max])
yAxis = d3.svg.axis()
.scale(yRange)
.orient("left")
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + (margin + yAxisWidth * currentLine) + "," + margin + ")")
.style("color", line.lineColor)
.call(yAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 0)
.attr("fill", line.lineColor)
.style("text-anchor", "start")
# Key
svg.append("line")
.attr("x1", margin)
.attr("y1", margin + height + xAxisHeight + keyHeight * currentLine + keyHeight / 2)
.attr("x2", margin + 40)
.attr("y2", margin + height + xAxisHeight + keyHeight * currentLine + keyHeight / 2)
.attr("stroke", line.lineColor)
.attr("class", "key-line")
svg.append("text")
.attr("x", margin + 40 + 10)
.attr("y", margin + height + xAxisHeight + keyHeight * currentLine + (keyHeight + 10) / 2)
.attr("fill", if line.lineColor is 'gold' then 'orange' else line.lineColor)
.attr("class", "key-text")
.text(line.description)
# Path and points
svg.selectAll(".circle")
.data(line.points)
.enter()
.append("circle")
.attr("transform", "translate(" + (margin + yAxisWidth * 2) + "," + margin + ")")
.attr("cx", (d) -> xRange(d.x))
.attr("cy", (d) -> yRange(d.y))
.attr("r", 2)
.attr("fill", line.lineColor)
.attr("stroke-width", 1)
.attr("class", "graph-point")
.attr("data-pointid", (d) -> "#{line.lineID}#{d.x}")
d3line = d3.svg.line()
.x((d) -> xRange(d.x))
.y((d) -> yRange(d.y))
.interpolate("linear")
svg.append("path")
.attr("d", d3line(line.points))
.attr("transform", "translate(" + (margin + yAxisWidth * 2) + "," + margin + ")")
.style("stroke-width", line.strokeWidth)
.style("stroke", line.lineColor)
.style("fill", "none")
currentLine++
| 116279 | RootView = require 'views/core/RootView'
template = require 'templates/admin/analytics-subscriptions'
ThangType = require 'models/ThangType'
User = require 'models/User'
# TODO: Graphing code copied/mangled from campaign editor level view. OMG, DRY.
require 'vendor/d3'
module.exports = class AnalyticsSubscriptionsView extends RootView
id: 'admin-analytics-subscriptions-view'
template: template
events:
'click .btn-show-more-cancellations': 'onClickShowMoreCancellations'
constructor: (options) ->
super options
@showMoreCancellations = false
@resetSubscriptionsData()
if me.isAdmin()
@refreshData()
_.delay (=> @refreshData()), 30 * 60 * 1000
getRenderData: ->
context = super()
context.analytics = @analytics ? graphs: []
context.cancellations = if @showMoreCancellations then @cancellations else (@cancellations ? []).slice(0, 40)
context.showMoreCancellations = @showMoreCancellations
context.subs = _.cloneDeep(@subs ? []).reverse()
context.subscribers = @subscribers ? []
context.subscriberCancelled = _.find context.subscribers, (subscriber) -> subscriber.cancel
context.subscriberSponsored = _.find context.subscribers, (subscriber) -> subscriber.user?.stripe?.sponsorID
context.total = @total ? 0
context.monthlyChurn = @monthlyChurn ? 0.0
context.monthlyGrowth = @monthlyGrowth ? 0.0
context.outstandingCancels = @outstandingCancels ? []
context.refreshDataState = @refreshDataState
context
afterRender: ->
super()
@updateAnalyticsGraphs()
onClickShowMoreCancellations: (e) ->
@showMoreCancellations = true
@render?()
resetSubscriptionsData: ->
@analytics = graphs: []
@subs = []
@total = 0
@monthlyChurn = 0.0
@monthlyGrowth = 0.0
@refreshDataState = 'Fetching dashboard data...'
refreshData: ->
return unless me.isAdmin()
@resetSubscriptionsData()
@getCancellations (cancellations) =>
@cancellations = cancellations
@render?()
@getOutstandingCancelledSubscriptions cancellations, (outstandingCancels) =>
@outstandingCancels = outstandingCancels
@getSubscriptions cancellations, (subscriptions) =>
@updateAnalyticsGraphData()
@render?()
@getSubscribers subscriptions, =>
@render?()
updateFetchDataState: (msg) ->
@refreshDataState = msg
@render?()
getCancellations: (done) ->
cancellations = []
@getCancellationEvents (cancelledSubscriptions) =>
# Get user objects for cancelled subscriptions
userIDs = _.map cancelledSubscriptions, (a) -> a.userID
options =
url: '/db/user/-/users'
method: 'POST'
data: {ids: userIDs}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get cancelled users', response
options.success = (cancelledUsers, response, options) =>
return if @destroyed
userMap = {}
userMap[user._id] = user for user in cancelledUsers
for cancellation in cancelledSubscriptions when cancellation.userID of userMap
cancellation.user = userMap[cancellation.userID]
cancellation.level = User.levelFromExp(cancellation.user.points)
cancelledSubscriptions.sort (a, b) -> if a.cancel > b.cancel then -1 else 1
done(cancelledSubscriptions)
@updateFetchDataState 'Fetching cancellations...'
@supermodel.addRequestResource('get_cancelled_users', options, 0).load()
getCancellationEvents: (done) ->
cancellationEvents = []
earliestEventDate = new Date()
earliestEventDate.setUTCMonth(earliestEventDate.getUTCMonth() - 2)
earliestEventDate.setUTCDate(earliestEventDate.getUTCDate() - 8)
nextBatch = (starting_after, done) =>
@updateFetchDataState "Fetching cancellations #{cancellationEvents.length}..."
options =
url: '/db/subscription/-/stripe_events'
method: 'POST'
data: {options: {limit: 100}}
options.data.options.starting_after = starting_after if starting_after
options.data.options.type = 'customer.subscription.updated'
options.data.options.created = gte: Math.floor(earliestEventDate.getTime() / 1000)
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get cancelled events', response
options.success = (events, response, options) =>
return if @destroyed
for event in events.data
continue unless event.data?.object?.cancel_at_period_end is true and event.data?.previous_attributes.cancel_at_period_end is false
continue unless event.data?.object?.plan?.id is 'basic'
continue unless event.data?.object?.id?
cancellationEvents.push
cancel: new Date(event.created * 1000)
customerID: event.data.object.customer
start: new Date(event.data.object.start * 1000)
subscriptionID: event.data.object.id
userID: event.data.object.metadata?.id
if events.has_more
return nextBatch(events.data[events.data.length - 1].id, done)
done(cancellationEvents)
@supermodel.addRequestResource('get_cancellation_events', options, 0).load()
nextBatch null, done
getOutstandingCancelledSubscriptions: (cancellations, done) ->
@updateFetchDataState "Fetching oustanding cancellations..."
options =
url: '/db/subscription/-/stripe_subscriptions'
method: 'POST'
data: {subscriptions: cancellations}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get outstanding cancellations', response
options.success = (subscriptions, response, options) =>
return if @destroyed
outstandingCancelledSubscriptions = []
for subscription in subscriptions
continue unless subscription?.cancel_at_period_end
outstandingCancelledSubscriptions.push
cancel: new Date(subscription.canceled_at * 1000)
customerID: subscription.customerID
start: new Date(subscription.start * 1000)
subscriptionID: subscription.id
userID: subscription.metadata?.id
done(outstandingCancelledSubscriptions)
@supermodel.addRequestResource('get_outstanding_cancelled_subscriptions', options, 0).load()
getSubscribers: (subscriptions, done) ->
# console.log 'getSubscribers', subscriptions.length
@updateFetchDataState "Fetching recent subscribers..."
@render?()
maxSubscribers = 40
subscribers = _.filter subscriptions, (a) -> a.userID?
subscribers.sort (a, b) -> if a.start > b.start then -1 else 1
subscribers = subscribers.slice(0, maxSubscribers)
subscriberUserIDs = _.map subscribers, (a) -> a.userID
options =
url: '/db/subscription/-/subscribers'
method: 'POST'
data: {ids: subscriberUserIDs}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get subscribers', response
options.success = (userMap, response, options) =>
return if @destroyed
for subscriber in subscribers
continue unless subscriber.userID of userMap
subscriber.user = userMap[subscriber.userID]
subscriber.level = User.levelFromExp subscriber.user.points
if hero = subscriber.user.heroConfig?.thangType
subscriber.hero = _.invert(ThangType.heroes)[hero]
@subscribers = subscribers
done()
@supermodel.addRequestResource('get_subscribers', options, 0).load()
getSubscriptions: (cancellations=[], done) ->
@getInvoices (invoices) =>
subMap = {}
for invoice in invoices
subID = invoice.subscriptionID
if subID of subMap
subMap[subID].first = new Date(invoice.date)
else
subMap[subID] =
first: new Date(invoice.date)
last: new Date(invoice.date)
customerID: invoice.customerID
subMap[subID].userID = invoice.userID if invoice.userID
@getSponsors (sponsors) =>
@getRecipientSubscriptions sponsors, (recipientSubscriptions) =>
for subscription in recipientSubscriptions
subMap[subscription.id] =
first: new Date(subscription.start * 1000)
subMap[subscription.id].userID = subscription.metadata.id if subscription.metadata?.id?
if subscription.cancel_at_period_end
subMap[subscription.id].cancel = new Date(subscription.canceled_at * 1000)
subMap[subscription.id].end = new Date(subscription.current_period_end * 1000)
subs = []
for subID of subMap
sub =
customerID: subMap[subID].customerID
start: subMap[subID].first
subscriptionID: subID
sub.cancel = subMap[subID].cancel if subMap[subID].cancel
oneMonthAgo = new Date()
oneMonthAgo.setUTCMonth(oneMonthAgo.getUTCMonth() - 1)
if subMap[subID].end?
sub.end = subMap[subID].end
else if subMap[subID].last < oneMonthAgo
sub.end = subMap[subID].last
sub.end.setUTCMonth(sub.end.getUTCMonth() + 1)
sub.userID = subMap[subID].userID if subMap[subID].userID
subs.push sub
subDayMap = {}
for sub in subs
startDay = sub.start.toISOString().substring(0, 10)
subDayMap[startDay] ?= {}
subDayMap[startDay]['start'] ?= 0
subDayMap[startDay]['start']++
if endDay = sub?.end?.toISOString().substring(0, 10)
subDayMap[endDay] ?= {}
subDayMap[endDay]['end'] ?= 0
subDayMap[endDay]['end']++
for cancellation in cancellations
if cancellation.subscriptionID is sub.subscriptionID
sub.cancel = cancellation.cancel
cancelDay = cancellation.cancel.toISOString().substring(0, 10)
subDayMap[cancelDay] ?= {}
subDayMap[cancelDay]['cancel'] ?= 0
subDayMap[cancelDay]['cancel']++
break
today = new Date().toISOString().substring(0, 10)
for day of subDayMap
continue if day > today
@subs.push
day: day
started: subDayMap[day]['start'] or 0
cancelled: subDayMap[day]['cancel'] or 0
ended: subDayMap[day]['end'] or 0
@subs.sort (a, b) -> a.day.localeCompare(b.day)
cancelledThisMonth = 0
totalLastMonth = 0
for sub, i in @subs
@total += sub.started
@total -= sub.ended
sub.total = @total
cancelledThisMonth += sub.cancelled if @subs.length - i < 31
totalLastMonth = @total if @subs.length - i is 31
@monthlyChurn = cancelledThisMonth / totalLastMonth * 100.0 if totalLastMonth > 0
if @subs.length > 30 and @subs[@subs.length - 31].total > 0
startMonthTotal = @subs[@subs.length - 31].total
endMonthTotal = @subs[@subs.length - 1].total
@monthlyGrowth = (endMonthTotal / startMonthTotal - 1) * 100
done(subs)
getInvoices: (done) ->
invoices = {}
addInvoice = (invoice) =>
return unless invoice.paid
return unless invoice.subscription
return unless invoice.total > 0
return unless invoice.lines?.data?[0]?.plan?.id is 'basic'
invoices[invoice.id] =
customerID: invoice.customer
subscriptionID: invoice.subscription
date: new Date(invoice.date * 1000)
invoices[invoice.id].userID = invoice.lines.data[0].metadata.id if invoice.lines?.data?[0]?.metadata?.id
getLiveInvoices = (ending_before, done) =>
nextBatch = (ending_before, done) =>
@updateFetchDataState "Fetching invoices #{Object.keys(invoices).length}..."
options =
url: '/db/subscription/-/stripe_invoices'
method: 'POST'
data: {options: {ending_before: ending_before, limit: 100}}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get live invoices', response
options.success = (invoiceData, response, options) =>
return if @destroyed
addInvoice(invoice) for invoice in invoiceData.data
if invoiceData.has_more
return nextBatch(invoiceData.data[0].id, done)
else
invoices = (invoice for invoiceID, invoice of invoices)
invoices.sort (a, b) -> if a.date > b.date then -1 else 1
return done(invoices)
@supermodel.addRequestResource('get_live_invoices', options, 0).load()
nextBatch ending_before, done
getAnalyticsInvoices = (done) =>
@updateFetchDataState "Fetching invoices #{Object.keys(invoices).length}..."
options =
url: '/db/analytics.stripe.invoice/-/all'
method: 'GET'
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get analytics stripe invoices', response
options.success = (docs, response, options) =>
return if @destroyed
docs.sort (a, b) -> b.date - a.date
addInvoice(doc.properties) for doc in docs
getLiveInvoices(docs[0]._id, done)
@supermodel.addRequestResource('get_analytics_invoices', options, 0).load()
getAnalyticsInvoices(done)
getRecipientSubscriptions: (sponsors, done) ->
@updateFetchDataState "Fetching recipient subscriptions..."
subscriptionsToFetch = []
for user in sponsors
for recipient in user.stripe?.recipients
subscriptionsToFetch.push
customerID: user.stripe.customerID
subscriptionID: recipient.subscriptionID
return done([]) if _.isEmpty subscriptionsToFetch
options =
url: '/db/subscription/-/stripe_subscriptions'
method: 'POST'
data: {subscriptions: subscriptionsToFetch}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get recipient subscriptions', response
options.success = (subscriptions, response, options) =>
return if @destroyed
done(subscriptions)
@supermodel.addRequestResource('get_recipient_subscriptions', options, 0).load()
getSponsors: (done) ->
@updateFetchDataState "Fetching sponsors..."
options =
url: '/db/user/-/sub_sponsors'
method: 'POST'
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get sponsors', response
options.success = (sponsors, response, options) =>
return if @destroyed
done(sponsors)
@supermodel.addRequestResource('get_sponsors', options, 0).load()
updateAnalyticsGraphData: ->
# console.log 'updateAnalyticsGraphData'
# Build graphs based on available @analytics data
# Currently only one graph
@analytics.graphs = []
return unless @subs?.length > 0
@addGraphData(60)
@addGraphData(180, true)
addGraphData: (timeframeDays, skipCancelled=false) ->
graph = {graphID: 'total-subs', lines: []}
# TODO: Where should this metadata live?
# TODO: lineIDs assumed to be unique across graphs
totalSubsID = 'total-subs'
startedSubsID = 'started-subs'
cancelledSubsID = 'cancelled-subs'
netSubsID = 'net-subs'
averageNewID = 'average-new'
lineMetadata = {}
lineMetadata[totalSubsID] =
description: 'Total Active Subscriptions'
color: 'green'
strokeWidth: 1
lineMetadata[startedSubsID] =
description: 'New Subscriptions'
color: 'blue'
strokeWidth: 1
lineMetadata[cancelledSubsID] =
description: 'Cancelled Subscriptions'
color: 'red'
strokeWidth: 1
lineMetadata[netSubsID] =
description: '7-day Average Net Subscriptions (started - cancelled)'
color: 'black'
strokeWidth: 4
lineMetadata[averageNewID] =
description: '7-day Average New Subscriptions'
color: 'black'
strokeWidth: 4
days = (sub.day for sub in @subs)
if days.length > 0
currentIndex = 0
currentDay = days[currentIndex]
currentDate = new Date(currentDay + "T00:00:00.000Z")
lastDay = days[days.length - 1]
while currentDay isnt lastDay
days.splice currentIndex, 0, currentDay if days[currentIndex] isnt currentDay
currentIndex++
currentDate.setUTCDate(currentDate.getUTCDate() + 1)
currentDay = currentDate.toISOString().substr(0, 10)
## Totals
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: i
y: sub.total
day: sub.day
pointID: "#{totalSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{totalSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: totalSubsID
enabled: true
points: levelPoints
description: lineMetadata[totalSubsID].description
lineColor: lineMetadata[totalSubsID].color
strokeWidth: lineMetadata[totalSubsID].strokeWidth
min: 0
max: d3.max(@subs, (d) -> d.total)
## Started
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: i
y: sub.started
day: sub.day
pointID: "#{startedSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{startedSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: startedSubsID
enabled: true
points: levelPoints
description: lineMetadata[startedSubsID].description
lineColor: lineMetadata[startedSubsID].color
strokeWidth: lineMetadata[startedSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
if skipCancelled
## 7-Day average started
# Build line data
levelPoints = []
sevenStarts = []
for sub, i in @subs
average = 0
sevenStarts.push sub.started
if sevenStarts.length > 7
sevenStarts.shift()
if sevenStarts.length is 7
average = sevenStarts.reduce((a, b) -> a + b) / sevenStarts.length
levelPoints.push
x: i
y: average
day: sub.day
pointID: "#{averageNewID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{averageNewID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: averageNewID
enabled: true
points: levelPoints
description: lineMetadata[averageNewID].description
lineColor: lineMetadata[averageNewID].color
strokeWidth: lineMetadata[averageNewID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
else
## Cancelled
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: @subs.length - 30 + i
y: sub.cancelled
day: sub.day
pointID: "#{cancelledSubsID}#{@subs.length - 30 + i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{cancelledSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: cancelledSubsID
enabled: true
points: levelPoints
description: lineMetadata[cancelledSubsID].description
lineColor: lineMetadata[cancelledSubsID].color
strokeWidth: lineMetadata[cancelledSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
## 7-Day Net Subs
# Build line data
levelPoints = []
sevenNets = []
for sub, i in @subs
net = 0
sevenNets.push sub.started - sub.cancelled
if sevenNets.length > 7
sevenNets.shift()
if sevenNets.length is 7
net = sevenNets.reduce((a, b) -> a + b) / 7
levelPoints.push
x: i
y: net
day: sub.day
pointID: "#{netSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{netSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: netSubsID
enabled: true
points: levelPoints
description: lineMetadata[netSubsID].description
lineColor: lineMetadata[netSubsID].color
strokeWidth: lineMetadata[netSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
@analytics.graphs.push(graph)
updateAnalyticsGraphs: ->
# Build d3 graphs
return unless @analytics?.graphs?.length > 0
containerSelector = '.line-graph-container'
# console.log 'updateAnalyticsGraphs', containerSelector, @analytics.graphs
margin = 20
keyHeight = <KEY>
xAxisHeight = 20
yAxisWidth = 40
containerWidth = $(containerSelector).width()
containerHeight = $(containerSelector).height()
for graph in @analytics.graphs
graphLineCount = _.reduce graph.lines, ((sum, item) -> if item.enabled then sum + 1 else sum), 0
svg = d3.select(containerSelector).append("svg")
.attr("width", containerWidth)
.attr("height", containerHeight)
width = containerWidth - margin * 2 - yAxisWidth * 2
height = containerHeight - margin * 2 - xAxisHeight - keyHeight * graphLineCount
currentLine = 0
for line in graph.lines
continue unless line.enabled
xRange = d3.scale.linear().range([0, width]).domain([d3.min(line.points, (d) -> d.x), d3.max(line.points, (d) -> d.x)])
yRange = d3.scale.linear().range([height, 0]).domain([line.min, line.max])
# x-Axis
if currentLine is 0
startDay = new Date(line.points[0].day)
endDay = new Date(line.points[line.points.length - 1].day)
xAxisRange = d3.time.scale()
.domain([startDay, endDay])
.range([0, width])
xAxis = d3.svg.axis()
.scale(xAxisRange)
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.selectAll("text")
.attr("dy", ".35em")
.attr("transform", "translate(" + (margin + yAxisWidth) + "," + (height + margin) + ")")
.style("text-anchor", "start")
if line.lineID is 'started-subs'
# Horizontal guidelines
marks = (Math.round(i * line.max / 5) for i in [1...5])
svg.selectAll(".line")
.data(marks)
.enter()
.append("line")
.attr("x1", margin + yAxisWidth * 2)
.attr("y1", (d) -> margin + yRange(d))
.attr("x2", margin + yAxisWidth * 2 + width)
.attr("y2", (d) -> margin + yRange(d))
.attr("stroke", line.lineColor)
.style("opacity", "0.5")
if currentLine < 2
# y-Axis
yAxisRange = d3.scale.linear().range([height, 0]).domain([line.min, line.max])
yAxis = d3.svg.axis()
.scale(yRange)
.orient("left")
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + (margin + yAxisWidth * currentLine) + "," + margin + ")")
.style("color", line.lineColor)
.call(yAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 0)
.attr("fill", line.lineColor)
.style("text-anchor", "start")
# Key
svg.append("line")
.attr("x1", margin)
.attr("y1", margin + height + xAxisHeight + keyHeight * currentLine + keyHeight / 2)
.attr("x2", margin + 40)
.attr("y2", margin + height + xAxisHeight + keyHeight * currentLine + keyHeight / 2)
.attr("stroke", line.lineColor)
.attr("class", "key-line")
svg.append("text")
.attr("x", margin + 40 + 10)
.attr("y", margin + height + xAxisHeight + keyHeight * currentLine + (keyHeight + 10) / 2)
.attr("fill", if line.lineColor is 'gold' then 'orange' else line.lineColor)
.attr("class", "key-text")
.text(line.description)
# Path and points
svg.selectAll(".circle")
.data(line.points)
.enter()
.append("circle")
.attr("transform", "translate(" + (margin + yAxisWidth * 2) + "," + margin + ")")
.attr("cx", (d) -> xRange(d.x))
.attr("cy", (d) -> yRange(d.y))
.attr("r", 2)
.attr("fill", line.lineColor)
.attr("stroke-width", 1)
.attr("class", "graph-point")
.attr("data-pointid", (d) -> "#{line.lineID}#{d.x}")
d3line = d3.svg.line()
.x((d) -> xRange(d.x))
.y((d) -> yRange(d.y))
.interpolate("linear")
svg.append("path")
.attr("d", d3line(line.points))
.attr("transform", "translate(" + (margin + yAxisWidth * 2) + "," + margin + ")")
.style("stroke-width", line.strokeWidth)
.style("stroke", line.lineColor)
.style("fill", "none")
currentLine++
| true | RootView = require 'views/core/RootView'
template = require 'templates/admin/analytics-subscriptions'
ThangType = require 'models/ThangType'
User = require 'models/User'
# TODO: Graphing code copied/mangled from campaign editor level view. OMG, DRY.
require 'vendor/d3'
module.exports = class AnalyticsSubscriptionsView extends RootView
id: 'admin-analytics-subscriptions-view'
template: template
events:
'click .btn-show-more-cancellations': 'onClickShowMoreCancellations'
constructor: (options) ->
super options
@showMoreCancellations = false
@resetSubscriptionsData()
if me.isAdmin()
@refreshData()
_.delay (=> @refreshData()), 30 * 60 * 1000
getRenderData: ->
context = super()
context.analytics = @analytics ? graphs: []
context.cancellations = if @showMoreCancellations then @cancellations else (@cancellations ? []).slice(0, 40)
context.showMoreCancellations = @showMoreCancellations
context.subs = _.cloneDeep(@subs ? []).reverse()
context.subscribers = @subscribers ? []
context.subscriberCancelled = _.find context.subscribers, (subscriber) -> subscriber.cancel
context.subscriberSponsored = _.find context.subscribers, (subscriber) -> subscriber.user?.stripe?.sponsorID
context.total = @total ? 0
context.monthlyChurn = @monthlyChurn ? 0.0
context.monthlyGrowth = @monthlyGrowth ? 0.0
context.outstandingCancels = @outstandingCancels ? []
context.refreshDataState = @refreshDataState
context
afterRender: ->
super()
@updateAnalyticsGraphs()
onClickShowMoreCancellations: (e) ->
@showMoreCancellations = true
@render?()
resetSubscriptionsData: ->
@analytics = graphs: []
@subs = []
@total = 0
@monthlyChurn = 0.0
@monthlyGrowth = 0.0
@refreshDataState = 'Fetching dashboard data...'
refreshData: ->
return unless me.isAdmin()
@resetSubscriptionsData()
@getCancellations (cancellations) =>
@cancellations = cancellations
@render?()
@getOutstandingCancelledSubscriptions cancellations, (outstandingCancels) =>
@outstandingCancels = outstandingCancels
@getSubscriptions cancellations, (subscriptions) =>
@updateAnalyticsGraphData()
@render?()
@getSubscribers subscriptions, =>
@render?()
updateFetchDataState: (msg) ->
@refreshDataState = msg
@render?()
getCancellations: (done) ->
cancellations = []
@getCancellationEvents (cancelledSubscriptions) =>
# Get user objects for cancelled subscriptions
userIDs = _.map cancelledSubscriptions, (a) -> a.userID
options =
url: '/db/user/-/users'
method: 'POST'
data: {ids: userIDs}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get cancelled users', response
options.success = (cancelledUsers, response, options) =>
return if @destroyed
userMap = {}
userMap[user._id] = user for user in cancelledUsers
for cancellation in cancelledSubscriptions when cancellation.userID of userMap
cancellation.user = userMap[cancellation.userID]
cancellation.level = User.levelFromExp(cancellation.user.points)
cancelledSubscriptions.sort (a, b) -> if a.cancel > b.cancel then -1 else 1
done(cancelledSubscriptions)
@updateFetchDataState 'Fetching cancellations...'
@supermodel.addRequestResource('get_cancelled_users', options, 0).load()
getCancellationEvents: (done) ->
cancellationEvents = []
earliestEventDate = new Date()
earliestEventDate.setUTCMonth(earliestEventDate.getUTCMonth() - 2)
earliestEventDate.setUTCDate(earliestEventDate.getUTCDate() - 8)
nextBatch = (starting_after, done) =>
@updateFetchDataState "Fetching cancellations #{cancellationEvents.length}..."
options =
url: '/db/subscription/-/stripe_events'
method: 'POST'
data: {options: {limit: 100}}
options.data.options.starting_after = starting_after if starting_after
options.data.options.type = 'customer.subscription.updated'
options.data.options.created = gte: Math.floor(earliestEventDate.getTime() / 1000)
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get cancelled events', response
options.success = (events, response, options) =>
return if @destroyed
for event in events.data
continue unless event.data?.object?.cancel_at_period_end is true and event.data?.previous_attributes.cancel_at_period_end is false
continue unless event.data?.object?.plan?.id is 'basic'
continue unless event.data?.object?.id?
cancellationEvents.push
cancel: new Date(event.created * 1000)
customerID: event.data.object.customer
start: new Date(event.data.object.start * 1000)
subscriptionID: event.data.object.id
userID: event.data.object.metadata?.id
if events.has_more
return nextBatch(events.data[events.data.length - 1].id, done)
done(cancellationEvents)
@supermodel.addRequestResource('get_cancellation_events', options, 0).load()
nextBatch null, done
getOutstandingCancelledSubscriptions: (cancellations, done) ->
@updateFetchDataState "Fetching oustanding cancellations..."
options =
url: '/db/subscription/-/stripe_subscriptions'
method: 'POST'
data: {subscriptions: cancellations}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get outstanding cancellations', response
options.success = (subscriptions, response, options) =>
return if @destroyed
outstandingCancelledSubscriptions = []
for subscription in subscriptions
continue unless subscription?.cancel_at_period_end
outstandingCancelledSubscriptions.push
cancel: new Date(subscription.canceled_at * 1000)
customerID: subscription.customerID
start: new Date(subscription.start * 1000)
subscriptionID: subscription.id
userID: subscription.metadata?.id
done(outstandingCancelledSubscriptions)
@supermodel.addRequestResource('get_outstanding_cancelled_subscriptions', options, 0).load()
getSubscribers: (subscriptions, done) ->
# console.log 'getSubscribers', subscriptions.length
@updateFetchDataState "Fetching recent subscribers..."
@render?()
maxSubscribers = 40
subscribers = _.filter subscriptions, (a) -> a.userID?
subscribers.sort (a, b) -> if a.start > b.start then -1 else 1
subscribers = subscribers.slice(0, maxSubscribers)
subscriberUserIDs = _.map subscribers, (a) -> a.userID
options =
url: '/db/subscription/-/subscribers'
method: 'POST'
data: {ids: subscriberUserIDs}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get subscribers', response
options.success = (userMap, response, options) =>
return if @destroyed
for subscriber in subscribers
continue unless subscriber.userID of userMap
subscriber.user = userMap[subscriber.userID]
subscriber.level = User.levelFromExp subscriber.user.points
if hero = subscriber.user.heroConfig?.thangType
subscriber.hero = _.invert(ThangType.heroes)[hero]
@subscribers = subscribers
done()
@supermodel.addRequestResource('get_subscribers', options, 0).load()
getSubscriptions: (cancellations=[], done) ->
@getInvoices (invoices) =>
subMap = {}
for invoice in invoices
subID = invoice.subscriptionID
if subID of subMap
subMap[subID].first = new Date(invoice.date)
else
subMap[subID] =
first: new Date(invoice.date)
last: new Date(invoice.date)
customerID: invoice.customerID
subMap[subID].userID = invoice.userID if invoice.userID
@getSponsors (sponsors) =>
@getRecipientSubscriptions sponsors, (recipientSubscriptions) =>
for subscription in recipientSubscriptions
subMap[subscription.id] =
first: new Date(subscription.start * 1000)
subMap[subscription.id].userID = subscription.metadata.id if subscription.metadata?.id?
if subscription.cancel_at_period_end
subMap[subscription.id].cancel = new Date(subscription.canceled_at * 1000)
subMap[subscription.id].end = new Date(subscription.current_period_end * 1000)
subs = []
for subID of subMap
sub =
customerID: subMap[subID].customerID
start: subMap[subID].first
subscriptionID: subID
sub.cancel = subMap[subID].cancel if subMap[subID].cancel
oneMonthAgo = new Date()
oneMonthAgo.setUTCMonth(oneMonthAgo.getUTCMonth() - 1)
if subMap[subID].end?
sub.end = subMap[subID].end
else if subMap[subID].last < oneMonthAgo
sub.end = subMap[subID].last
sub.end.setUTCMonth(sub.end.getUTCMonth() + 1)
sub.userID = subMap[subID].userID if subMap[subID].userID
subs.push sub
subDayMap = {}
for sub in subs
startDay = sub.start.toISOString().substring(0, 10)
subDayMap[startDay] ?= {}
subDayMap[startDay]['start'] ?= 0
subDayMap[startDay]['start']++
if endDay = sub?.end?.toISOString().substring(0, 10)
subDayMap[endDay] ?= {}
subDayMap[endDay]['end'] ?= 0
subDayMap[endDay]['end']++
for cancellation in cancellations
if cancellation.subscriptionID is sub.subscriptionID
sub.cancel = cancellation.cancel
cancelDay = cancellation.cancel.toISOString().substring(0, 10)
subDayMap[cancelDay] ?= {}
subDayMap[cancelDay]['cancel'] ?= 0
subDayMap[cancelDay]['cancel']++
break
today = new Date().toISOString().substring(0, 10)
for day of subDayMap
continue if day > today
@subs.push
day: day
started: subDayMap[day]['start'] or 0
cancelled: subDayMap[day]['cancel'] or 0
ended: subDayMap[day]['end'] or 0
@subs.sort (a, b) -> a.day.localeCompare(b.day)
cancelledThisMonth = 0
totalLastMonth = 0
for sub, i in @subs
@total += sub.started
@total -= sub.ended
sub.total = @total
cancelledThisMonth += sub.cancelled if @subs.length - i < 31
totalLastMonth = @total if @subs.length - i is 31
@monthlyChurn = cancelledThisMonth / totalLastMonth * 100.0 if totalLastMonth > 0
if @subs.length > 30 and @subs[@subs.length - 31].total > 0
startMonthTotal = @subs[@subs.length - 31].total
endMonthTotal = @subs[@subs.length - 1].total
@monthlyGrowth = (endMonthTotal / startMonthTotal - 1) * 100
done(subs)
getInvoices: (done) ->
invoices = {}
addInvoice = (invoice) =>
return unless invoice.paid
return unless invoice.subscription
return unless invoice.total > 0
return unless invoice.lines?.data?[0]?.plan?.id is 'basic'
invoices[invoice.id] =
customerID: invoice.customer
subscriptionID: invoice.subscription
date: new Date(invoice.date * 1000)
invoices[invoice.id].userID = invoice.lines.data[0].metadata.id if invoice.lines?.data?[0]?.metadata?.id
getLiveInvoices = (ending_before, done) =>
nextBatch = (ending_before, done) =>
@updateFetchDataState "Fetching invoices #{Object.keys(invoices).length}..."
options =
url: '/db/subscription/-/stripe_invoices'
method: 'POST'
data: {options: {ending_before: ending_before, limit: 100}}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get live invoices', response
options.success = (invoiceData, response, options) =>
return if @destroyed
addInvoice(invoice) for invoice in invoiceData.data
if invoiceData.has_more
return nextBatch(invoiceData.data[0].id, done)
else
invoices = (invoice for invoiceID, invoice of invoices)
invoices.sort (a, b) -> if a.date > b.date then -1 else 1
return done(invoices)
@supermodel.addRequestResource('get_live_invoices', options, 0).load()
nextBatch ending_before, done
getAnalyticsInvoices = (done) =>
@updateFetchDataState "Fetching invoices #{Object.keys(invoices).length}..."
options =
url: '/db/analytics.stripe.invoice/-/all'
method: 'GET'
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get analytics stripe invoices', response
options.success = (docs, response, options) =>
return if @destroyed
docs.sort (a, b) -> b.date - a.date
addInvoice(doc.properties) for doc in docs
getLiveInvoices(docs[0]._id, done)
@supermodel.addRequestResource('get_analytics_invoices', options, 0).load()
getAnalyticsInvoices(done)
getRecipientSubscriptions: (sponsors, done) ->
@updateFetchDataState "Fetching recipient subscriptions..."
subscriptionsToFetch = []
for user in sponsors
for recipient in user.stripe?.recipients
subscriptionsToFetch.push
customerID: user.stripe.customerID
subscriptionID: recipient.subscriptionID
return done([]) if _.isEmpty subscriptionsToFetch
options =
url: '/db/subscription/-/stripe_subscriptions'
method: 'POST'
data: {subscriptions: subscriptionsToFetch}
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get recipient subscriptions', response
options.success = (subscriptions, response, options) =>
return if @destroyed
done(subscriptions)
@supermodel.addRequestResource('get_recipient_subscriptions', options, 0).load()
getSponsors: (done) ->
@updateFetchDataState "Fetching sponsors..."
options =
url: '/db/user/-/sub_sponsors'
method: 'POST'
options.error = (model, response, options) =>
return if @destroyed
console.error 'Failed to get sponsors', response
options.success = (sponsors, response, options) =>
return if @destroyed
done(sponsors)
@supermodel.addRequestResource('get_sponsors', options, 0).load()
updateAnalyticsGraphData: ->
# console.log 'updateAnalyticsGraphData'
# Build graphs based on available @analytics data
# Currently only one graph
@analytics.graphs = []
return unless @subs?.length > 0
@addGraphData(60)
@addGraphData(180, true)
addGraphData: (timeframeDays, skipCancelled=false) ->
graph = {graphID: 'total-subs', lines: []}
# TODO: Where should this metadata live?
# TODO: lineIDs assumed to be unique across graphs
totalSubsID = 'total-subs'
startedSubsID = 'started-subs'
cancelledSubsID = 'cancelled-subs'
netSubsID = 'net-subs'
averageNewID = 'average-new'
lineMetadata = {}
lineMetadata[totalSubsID] =
description: 'Total Active Subscriptions'
color: 'green'
strokeWidth: 1
lineMetadata[startedSubsID] =
description: 'New Subscriptions'
color: 'blue'
strokeWidth: 1
lineMetadata[cancelledSubsID] =
description: 'Cancelled Subscriptions'
color: 'red'
strokeWidth: 1
lineMetadata[netSubsID] =
description: '7-day Average Net Subscriptions (started - cancelled)'
color: 'black'
strokeWidth: 4
lineMetadata[averageNewID] =
description: '7-day Average New Subscriptions'
color: 'black'
strokeWidth: 4
days = (sub.day for sub in @subs)
if days.length > 0
currentIndex = 0
currentDay = days[currentIndex]
currentDate = new Date(currentDay + "T00:00:00.000Z")
lastDay = days[days.length - 1]
while currentDay isnt lastDay
days.splice currentIndex, 0, currentDay if days[currentIndex] isnt currentDay
currentIndex++
currentDate.setUTCDate(currentDate.getUTCDate() + 1)
currentDay = currentDate.toISOString().substr(0, 10)
## Totals
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: i
y: sub.total
day: sub.day
pointID: "#{totalSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{totalSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: totalSubsID
enabled: true
points: levelPoints
description: lineMetadata[totalSubsID].description
lineColor: lineMetadata[totalSubsID].color
strokeWidth: lineMetadata[totalSubsID].strokeWidth
min: 0
max: d3.max(@subs, (d) -> d.total)
## Started
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: i
y: sub.started
day: sub.day
pointID: "#{startedSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{startedSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: startedSubsID
enabled: true
points: levelPoints
description: lineMetadata[startedSubsID].description
lineColor: lineMetadata[startedSubsID].color
strokeWidth: lineMetadata[startedSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
if skipCancelled
## 7-Day average started
# Build line data
levelPoints = []
sevenStarts = []
for sub, i in @subs
average = 0
sevenStarts.push sub.started
if sevenStarts.length > 7
sevenStarts.shift()
if sevenStarts.length is 7
average = sevenStarts.reduce((a, b) -> a + b) / sevenStarts.length
levelPoints.push
x: i
y: average
day: sub.day
pointID: "#{averageNewID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{averageNewID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: averageNewID
enabled: true
points: levelPoints
description: lineMetadata[averageNewID].description
lineColor: lineMetadata[averageNewID].color
strokeWidth: lineMetadata[averageNewID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
else
## Cancelled
# Build line data
levelPoints = []
for sub, i in @subs
levelPoints.push
x: @subs.length - 30 + i
y: sub.cancelled
day: sub.day
pointID: "#{cancelledSubsID}#{@subs.length - 30 + i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{cancelledSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: cancelledSubsID
enabled: true
points: levelPoints
description: lineMetadata[cancelledSubsID].description
lineColor: lineMetadata[cancelledSubsID].color
strokeWidth: lineMetadata[cancelledSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
## 7-Day Net Subs
# Build line data
levelPoints = []
sevenNets = []
for sub, i in @subs
net = 0
sevenNets.push sub.started - sub.cancelled
if sevenNets.length > 7
sevenNets.shift()
if sevenNets.length is 7
net = sevenNets.reduce((a, b) -> a + b) / 7
levelPoints.push
x: i
y: net
day: sub.day
pointID: "#{netSubsID}#{i}"
values: []
# Ensure points for each day
for day, i in days
if levelPoints.length <= i or levelPoints[i].day isnt day
prevY = if i > 0 then levelPoints[i - 1].y else 0.0
levelPoints.splice i, 0,
y: prevY
day: day
values: []
levelPoints[i].x = i
levelPoints[i].pointID = "#{netSubsID}#{i}"
levelPoints.splice(0, levelPoints.length - timeframeDays) if levelPoints.length > timeframeDays
graph.lines.push
lineID: netSubsID
enabled: true
points: levelPoints
description: lineMetadata[netSubsID].description
lineColor: lineMetadata[netSubsID].color
strokeWidth: lineMetadata[netSubsID].strokeWidth
min: 0
max: d3.max(@subs[-timeframeDays..], (d) -> d.started + 2)
@analytics.graphs.push(graph)
updateAnalyticsGraphs: ->
# Build d3 graphs
return unless @analytics?.graphs?.length > 0
containerSelector = '.line-graph-container'
# console.log 'updateAnalyticsGraphs', containerSelector, @analytics.graphs
margin = 20
keyHeight = PI:KEY:<KEY>END_PI
xAxisHeight = 20
yAxisWidth = 40
containerWidth = $(containerSelector).width()
containerHeight = $(containerSelector).height()
for graph in @analytics.graphs
graphLineCount = _.reduce graph.lines, ((sum, item) -> if item.enabled then sum + 1 else sum), 0
svg = d3.select(containerSelector).append("svg")
.attr("width", containerWidth)
.attr("height", containerHeight)
width = containerWidth - margin * 2 - yAxisWidth * 2
height = containerHeight - margin * 2 - xAxisHeight - keyHeight * graphLineCount
currentLine = 0
for line in graph.lines
continue unless line.enabled
xRange = d3.scale.linear().range([0, width]).domain([d3.min(line.points, (d) -> d.x), d3.max(line.points, (d) -> d.x)])
yRange = d3.scale.linear().range([height, 0]).domain([line.min, line.max])
# x-Axis
if currentLine is 0
startDay = new Date(line.points[0].day)
endDay = new Date(line.points[line.points.length - 1].day)
xAxisRange = d3.time.scale()
.domain([startDay, endDay])
.range([0, width])
xAxis = d3.svg.axis()
.scale(xAxisRange)
svg.append("g")
.attr("class", "x axis")
.call(xAxis)
.selectAll("text")
.attr("dy", ".35em")
.attr("transform", "translate(" + (margin + yAxisWidth) + "," + (height + margin) + ")")
.style("text-anchor", "start")
if line.lineID is 'started-subs'
# Horizontal guidelines
marks = (Math.round(i * line.max / 5) for i in [1...5])
svg.selectAll(".line")
.data(marks)
.enter()
.append("line")
.attr("x1", margin + yAxisWidth * 2)
.attr("y1", (d) -> margin + yRange(d))
.attr("x2", margin + yAxisWidth * 2 + width)
.attr("y2", (d) -> margin + yRange(d))
.attr("stroke", line.lineColor)
.style("opacity", "0.5")
if currentLine < 2
# y-Axis
yAxisRange = d3.scale.linear().range([height, 0]).domain([line.min, line.max])
yAxis = d3.svg.axis()
.scale(yRange)
.orient("left")
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + (margin + yAxisWidth * currentLine) + "," + margin + ")")
.style("color", line.lineColor)
.call(yAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 0)
.attr("fill", line.lineColor)
.style("text-anchor", "start")
# Key
svg.append("line")
.attr("x1", margin)
.attr("y1", margin + height + xAxisHeight + keyHeight * currentLine + keyHeight / 2)
.attr("x2", margin + 40)
.attr("y2", margin + height + xAxisHeight + keyHeight * currentLine + keyHeight / 2)
.attr("stroke", line.lineColor)
.attr("class", "key-line")
svg.append("text")
.attr("x", margin + 40 + 10)
.attr("y", margin + height + xAxisHeight + keyHeight * currentLine + (keyHeight + 10) / 2)
.attr("fill", if line.lineColor is 'gold' then 'orange' else line.lineColor)
.attr("class", "key-text")
.text(line.description)
# Path and points
svg.selectAll(".circle")
.data(line.points)
.enter()
.append("circle")
.attr("transform", "translate(" + (margin + yAxisWidth * 2) + "," + margin + ")")
.attr("cx", (d) -> xRange(d.x))
.attr("cy", (d) -> yRange(d.y))
.attr("r", 2)
.attr("fill", line.lineColor)
.attr("stroke-width", 1)
.attr("class", "graph-point")
.attr("data-pointid", (d) -> "#{line.lineID}#{d.x}")
d3line = d3.svg.line()
.x((d) -> xRange(d.x))
.y((d) -> yRange(d.y))
.interpolate("linear")
svg.append("path")
.attr("d", d3line(line.points))
.attr("transform", "translate(" + (margin + yAxisWidth * 2) + "," + margin + ")")
.style("stroke-width", line.strokeWidth)
.style("stroke", line.lineColor)
.style("fill", "none")
currentLine++
|
[
{
"context": ",\n grant_type: 'password'\n username: username\n password: password\n client_id: @co",
"end": 796,
"score": 0.9929350018501282,
"start": 788,
"tag": "USERNAME",
"value": "username"
},
{
"context": "word'\n username: username\n password: password\n client_id: @config.oauthKey\n clien",
"end": 823,
"score": 0.9978662133216858,
"start": 815,
"tag": "PASSWORD",
"value": "password"
}
] | lib/designer-news/authenticate.coffee | layervault/designer_news_js_client | 2 | RSVP = require 'rsvp'
needle = require 'needle'
# Handles API authentication and the related client configuration.
module.exports = class Authenticate
# Constructs a new Authenticate object
#
# @param [Configuration] config The client configuration
constructor: (@config) ->
@tokenEndpoint = @config.apiBase + '/oauth/token'
# Performs username/password authentication to retrieve OAuth tokens.
#
# @param [String] username The login username. For LayerVault this is the user's email address.
# @param [String] paassword The login password.
# @param [Function] cb The finished callback
withPassword: (username, password, cb = ->) ->
new RSVP.Promise (resolve, reject) =>
needle.post @tokenEndpoint,
grant_type: 'password'
username: username
password: password
client_id: @config.oauthKey
client_secret: @config.oauthSecret
, (error, resp, body) =>
error or= body.error
if error?
reject(error)
cb(error, null)
return
@config.accessToken = body.access_token
data = accessToken: @config.accessToken
@trigger 'authorized', data
resolve(data)
cb(null, data)
RSVP.EventTarget.mixin(Authenticate::) | 134123 | RSVP = require 'rsvp'
needle = require 'needle'
# Handles API authentication and the related client configuration.
module.exports = class Authenticate
# Constructs a new Authenticate object
#
# @param [Configuration] config The client configuration
constructor: (@config) ->
@tokenEndpoint = @config.apiBase + '/oauth/token'
# Performs username/password authentication to retrieve OAuth tokens.
#
# @param [String] username The login username. For LayerVault this is the user's email address.
# @param [String] paassword The login password.
# @param [Function] cb The finished callback
withPassword: (username, password, cb = ->) ->
new RSVP.Promise (resolve, reject) =>
needle.post @tokenEndpoint,
grant_type: 'password'
username: username
password: <PASSWORD>
client_id: @config.oauthKey
client_secret: @config.oauthSecret
, (error, resp, body) =>
error or= body.error
if error?
reject(error)
cb(error, null)
return
@config.accessToken = body.access_token
data = accessToken: @config.accessToken
@trigger 'authorized', data
resolve(data)
cb(null, data)
RSVP.EventTarget.mixin(Authenticate::) | true | RSVP = require 'rsvp'
needle = require 'needle'
# Handles API authentication and the related client configuration.
module.exports = class Authenticate
# Constructs a new Authenticate object
#
# @param [Configuration] config The client configuration
constructor: (@config) ->
@tokenEndpoint = @config.apiBase + '/oauth/token'
# Performs username/password authentication to retrieve OAuth tokens.
#
# @param [String] username The login username. For LayerVault this is the user's email address.
# @param [String] paassword The login password.
# @param [Function] cb The finished callback
withPassword: (username, password, cb = ->) ->
new RSVP.Promise (resolve, reject) =>
needle.post @tokenEndpoint,
grant_type: 'password'
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
client_id: @config.oauthKey
client_secret: @config.oauthSecret
, (error, resp, body) =>
error or= body.error
if error?
reject(error)
cb(error, null)
return
@config.accessToken = body.access_token
data = accessToken: @config.accessToken
@trigger 'authorized', data
resolve(data)
cb(null, data)
RSVP.EventTarget.mixin(Authenticate::) |
[
{
"context": "ch\r\n\r\ngenid = (len = 16, prefix = \"\", keyspace = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\") ->\r\n prefix += keyspace.charAt(Math.floor(Math",
"end": 373,
"score": 0.99954754114151,
"start": 311,
"tag": "KEY",
"value": "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
},
{
"context": " unless $scope.message then $scope.message = \"@#{user.name} \"\r\n \r\n $(\"#comments-message\").focus()\r",
"end": 5776,
"score": 0.9480969905853271,
"start": 5767,
"tag": "USERNAME",
"value": "user.name"
}
] | servers/www/assets/js/directives/discussion.coffee | sitedata/plunker | 340 | #= require ../vendor/angular-ui
#= require ../vendor/showdown
#= require ../vendor/prettify
#= require ../vendor/jquery.timeago
#= require ../vendor/jquery.cookie
#= require ../services/panels
#= require ../services/session
#= require ../services/scratch
genid = (len = 16, prefix = "", keyspace = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
module = angular.module("plunker.discussion", [])
module.requires.push("ngSanitize")
module.requires.push("ui.directives")
module.filter "iso8601", ->
(value) -> (new Date(value)).toISOString()
module.filter "markdown", ->
converter = new Showdown.converter()
(value) -> converter.makeHtml(value)
module.directive "chatMessage", ["$timeout", ($timeout) ->
restrict: "E"
replace: true
template: """
<li class="message">
<div class="body" ng-bind-html="message.body | markdown"></div>
<div class="meta">
<a href="javascript:void(0)" ng-click="targetMessage(message.user)" title="{{message.user.name}}">
<img class="gravatar" ng-src="http://www.gravatar.com/avatar/{{message.user.gravatar_id}}?s=18&d=mm" />
<span class="username" ng-class="{existing: message.user.type == 'registered'}">{{message.user.name}}</span>
</a>
<abbr class="timeago posted_at" title="{{message.posted_at | iso8601}}">{{message.posted_at | date:'MM/dd/yyyy @ h:mma'}}</abbr>
</div>
</li>
"""
link: ($scope, $el, attrs) ->
converter = new Showdown.converter()
$timeout ->
$(".timeago", $el).timeago()
prettyPrint()
$scope.$watch "message.body", (body) ->
$scope.markdown = converter.makeHtml(body)
]
module.directive "plunkerDiscussion", [ "$timeout", "$location", "panels", "session", "scratch", ($timeout, $location, panels, session, scratch) ->
restrict: "E"
replace: true
scope:
room: "="
template: """
<div class="plunker-discussion">
<ul class="thumbnails">
<li class="user" ng-repeat="(public_id, user) in users">
<a href="javascript:void(0)" ng-click="targetMessage(user)" class="thumbnail" title="{{user.name}}">
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}?s=32&d=mm" />
<span class="username" title="{{user.name}}">{{user.name}}</span>
</a>
</li>
</ul>
<form ng-submit="postChatMessage()">
<label>Discussion:</label>
<textarea ui-keypress="{'ctrl-enter':'postChatMessage()'}" id="comments-message" type="text" placeholder="Enter message..." class="span4" ng-model="message"></textarea>
<span class="help-block">Comments are markdown formatted.</span>
<button class="btn btn-primary" ng-click="postChatMessage()">Comment</button>
</form>
<ul class="chat-messages">
<chat-message message="message" ng-repeat="message in messages | orderBy:'posted_at':true"></chat-message>
</ul>
</div>
"""
link: ($scope, el, attrs) ->
self = @
roomRef = null
chatRef = null
usersRef = null
presenceRef = null
handlePresenceValue = (snapshot) ->
if snapshot.val() is null then setOwnPresence(presenceRef)
handleUsersValue = (snapshot) ->
if (users = snapshot.val()) isnt null then $scope.$apply ->
angular.copy(users, $scope.users)
handleChatAdded = (snapshot) -> $timeout ->
$scope.messages.push(snapshot.val())
$scope.$emit "discussion.message", snapshot.val()
$scope.message = ""
$scope.messages = []
$scope.users = {}
$scope.$watch ( -> session.user), (user) ->
$scope.user = do ->
if user
type: "registered"
name: user.login
pubId: session.public_id
gravatar_id: user.gravatar_id
else
type: "anonymous"
name: $.cookie("plnk_anonName") or do ->
$.cookie "plnk_anonName", prompt("You are not logged in. Please provide a name for streaming:", genid(5, "Anon-")) or genid(5, "Anon-")
$.cookie "plnk_anonName"
pubId: session.public_id
gravatar_id: 0
$scope.$watch "user", (user) ->
setOwnPresence(presenceRef) if presenceRef
$scope.$watch "room", (room) ->
# Reset messages
$scope.messages.length = 0
# Remove presenceRef
if presenceRef
presenceRef.off "value", handlePresenceValue
usersRef.off "value", handleUsersValue
presenceRef.remove()
roomRef = null
chatRef = null
return unless room
roomRef = new Firebase("https://filearts.firebaseio.com/rooms/#{room}/")
chatRef = roomRef.child("messages")
usersRef = roomRef.child("users")
presenceRef = usersRef.child(session.public_id)
setOwnPresence(presenceRef)
chatRef.limit(50).on "child_added", handleChatAdded
presenceRef.on "value", handlePresenceValue
usersRef.on "value", handleUsersValue
setOwnPresence = (presenceRef) -> $timeout ->
presenceRef.removeOnDisconnect()
presenceRef.set($scope.user)
$scope.postChatMessage = ->
if chatRef and $scope.message
message =
body: $scope.message
posted_at: +new Date
user: $scope.user
chatRef.push(message)
$scope.message = ""
$scope.targetMessage = (user) ->
unless $scope.message then $scope.message = "@#{user.name} "
$("#comments-message").focus()
]
| 146427 | #= require ../vendor/angular-ui
#= require ../vendor/showdown
#= require ../vendor/prettify
#= require ../vendor/jquery.timeago
#= require ../vendor/jquery.cookie
#= require ../services/panels
#= require ../services/session
#= require ../services/scratch
genid = (len = 16, prefix = "", keyspace = "<KEY>") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
module = angular.module("plunker.discussion", [])
module.requires.push("ngSanitize")
module.requires.push("ui.directives")
module.filter "iso8601", ->
(value) -> (new Date(value)).toISOString()
module.filter "markdown", ->
converter = new Showdown.converter()
(value) -> converter.makeHtml(value)
module.directive "chatMessage", ["$timeout", ($timeout) ->
restrict: "E"
replace: true
template: """
<li class="message">
<div class="body" ng-bind-html="message.body | markdown"></div>
<div class="meta">
<a href="javascript:void(0)" ng-click="targetMessage(message.user)" title="{{message.user.name}}">
<img class="gravatar" ng-src="http://www.gravatar.com/avatar/{{message.user.gravatar_id}}?s=18&d=mm" />
<span class="username" ng-class="{existing: message.user.type == 'registered'}">{{message.user.name}}</span>
</a>
<abbr class="timeago posted_at" title="{{message.posted_at | iso8601}}">{{message.posted_at | date:'MM/dd/yyyy @ h:mma'}}</abbr>
</div>
</li>
"""
link: ($scope, $el, attrs) ->
converter = new Showdown.converter()
$timeout ->
$(".timeago", $el).timeago()
prettyPrint()
$scope.$watch "message.body", (body) ->
$scope.markdown = converter.makeHtml(body)
]
module.directive "plunkerDiscussion", [ "$timeout", "$location", "panels", "session", "scratch", ($timeout, $location, panels, session, scratch) ->
restrict: "E"
replace: true
scope:
room: "="
template: """
<div class="plunker-discussion">
<ul class="thumbnails">
<li class="user" ng-repeat="(public_id, user) in users">
<a href="javascript:void(0)" ng-click="targetMessage(user)" class="thumbnail" title="{{user.name}}">
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}?s=32&d=mm" />
<span class="username" title="{{user.name}}">{{user.name}}</span>
</a>
</li>
</ul>
<form ng-submit="postChatMessage()">
<label>Discussion:</label>
<textarea ui-keypress="{'ctrl-enter':'postChatMessage()'}" id="comments-message" type="text" placeholder="Enter message..." class="span4" ng-model="message"></textarea>
<span class="help-block">Comments are markdown formatted.</span>
<button class="btn btn-primary" ng-click="postChatMessage()">Comment</button>
</form>
<ul class="chat-messages">
<chat-message message="message" ng-repeat="message in messages | orderBy:'posted_at':true"></chat-message>
</ul>
</div>
"""
link: ($scope, el, attrs) ->
self = @
roomRef = null
chatRef = null
usersRef = null
presenceRef = null
handlePresenceValue = (snapshot) ->
if snapshot.val() is null then setOwnPresence(presenceRef)
handleUsersValue = (snapshot) ->
if (users = snapshot.val()) isnt null then $scope.$apply ->
angular.copy(users, $scope.users)
handleChatAdded = (snapshot) -> $timeout ->
$scope.messages.push(snapshot.val())
$scope.$emit "discussion.message", snapshot.val()
$scope.message = ""
$scope.messages = []
$scope.users = {}
$scope.$watch ( -> session.user), (user) ->
$scope.user = do ->
if user
type: "registered"
name: user.login
pubId: session.public_id
gravatar_id: user.gravatar_id
else
type: "anonymous"
name: $.cookie("plnk_anonName") or do ->
$.cookie "plnk_anonName", prompt("You are not logged in. Please provide a name for streaming:", genid(5, "Anon-")) or genid(5, "Anon-")
$.cookie "plnk_anonName"
pubId: session.public_id
gravatar_id: 0
$scope.$watch "user", (user) ->
setOwnPresence(presenceRef) if presenceRef
$scope.$watch "room", (room) ->
# Reset messages
$scope.messages.length = 0
# Remove presenceRef
if presenceRef
presenceRef.off "value", handlePresenceValue
usersRef.off "value", handleUsersValue
presenceRef.remove()
roomRef = null
chatRef = null
return unless room
roomRef = new Firebase("https://filearts.firebaseio.com/rooms/#{room}/")
chatRef = roomRef.child("messages")
usersRef = roomRef.child("users")
presenceRef = usersRef.child(session.public_id)
setOwnPresence(presenceRef)
chatRef.limit(50).on "child_added", handleChatAdded
presenceRef.on "value", handlePresenceValue
usersRef.on "value", handleUsersValue
setOwnPresence = (presenceRef) -> $timeout ->
presenceRef.removeOnDisconnect()
presenceRef.set($scope.user)
$scope.postChatMessage = ->
if chatRef and $scope.message
message =
body: $scope.message
posted_at: +new Date
user: $scope.user
chatRef.push(message)
$scope.message = ""
$scope.targetMessage = (user) ->
unless $scope.message then $scope.message = "@#{user.name} "
$("#comments-message").focus()
]
| true | #= require ../vendor/angular-ui
#= require ../vendor/showdown
#= require ../vendor/prettify
#= require ../vendor/jquery.timeago
#= require ../vendor/jquery.cookie
#= require ../services/panels
#= require ../services/session
#= require ../services/scratch
genid = (len = 16, prefix = "", keyspace = "PI:KEY:<KEY>END_PI") ->
prefix += keyspace.charAt(Math.floor(Math.random() * keyspace.length)) while len-- > 0
prefix
module = angular.module("plunker.discussion", [])
module.requires.push("ngSanitize")
module.requires.push("ui.directives")
module.filter "iso8601", ->
(value) -> (new Date(value)).toISOString()
module.filter "markdown", ->
converter = new Showdown.converter()
(value) -> converter.makeHtml(value)
module.directive "chatMessage", ["$timeout", ($timeout) ->
restrict: "E"
replace: true
template: """
<li class="message">
<div class="body" ng-bind-html="message.body | markdown"></div>
<div class="meta">
<a href="javascript:void(0)" ng-click="targetMessage(message.user)" title="{{message.user.name}}">
<img class="gravatar" ng-src="http://www.gravatar.com/avatar/{{message.user.gravatar_id}}?s=18&d=mm" />
<span class="username" ng-class="{existing: message.user.type == 'registered'}">{{message.user.name}}</span>
</a>
<abbr class="timeago posted_at" title="{{message.posted_at | iso8601}}">{{message.posted_at | date:'MM/dd/yyyy @ h:mma'}}</abbr>
</div>
</li>
"""
link: ($scope, $el, attrs) ->
converter = new Showdown.converter()
$timeout ->
$(".timeago", $el).timeago()
prettyPrint()
$scope.$watch "message.body", (body) ->
$scope.markdown = converter.makeHtml(body)
]
module.directive "plunkerDiscussion", [ "$timeout", "$location", "panels", "session", "scratch", ($timeout, $location, panels, session, scratch) ->
restrict: "E"
replace: true
scope:
room: "="
template: """
<div class="plunker-discussion">
<ul class="thumbnails">
<li class="user" ng-repeat="(public_id, user) in users">
<a href="javascript:void(0)" ng-click="targetMessage(user)" class="thumbnail" title="{{user.name}}">
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}?s=32&d=mm" />
<span class="username" title="{{user.name}}">{{user.name}}</span>
</a>
</li>
</ul>
<form ng-submit="postChatMessage()">
<label>Discussion:</label>
<textarea ui-keypress="{'ctrl-enter':'postChatMessage()'}" id="comments-message" type="text" placeholder="Enter message..." class="span4" ng-model="message"></textarea>
<span class="help-block">Comments are markdown formatted.</span>
<button class="btn btn-primary" ng-click="postChatMessage()">Comment</button>
</form>
<ul class="chat-messages">
<chat-message message="message" ng-repeat="message in messages | orderBy:'posted_at':true"></chat-message>
</ul>
</div>
"""
link: ($scope, el, attrs) ->
self = @
roomRef = null
chatRef = null
usersRef = null
presenceRef = null
handlePresenceValue = (snapshot) ->
if snapshot.val() is null then setOwnPresence(presenceRef)
handleUsersValue = (snapshot) ->
if (users = snapshot.val()) isnt null then $scope.$apply ->
angular.copy(users, $scope.users)
handleChatAdded = (snapshot) -> $timeout ->
$scope.messages.push(snapshot.val())
$scope.$emit "discussion.message", snapshot.val()
$scope.message = ""
$scope.messages = []
$scope.users = {}
$scope.$watch ( -> session.user), (user) ->
$scope.user = do ->
if user
type: "registered"
name: user.login
pubId: session.public_id
gravatar_id: user.gravatar_id
else
type: "anonymous"
name: $.cookie("plnk_anonName") or do ->
$.cookie "plnk_anonName", prompt("You are not logged in. Please provide a name for streaming:", genid(5, "Anon-")) or genid(5, "Anon-")
$.cookie "plnk_anonName"
pubId: session.public_id
gravatar_id: 0
$scope.$watch "user", (user) ->
setOwnPresence(presenceRef) if presenceRef
$scope.$watch "room", (room) ->
# Reset messages
$scope.messages.length = 0
# Remove presenceRef
if presenceRef
presenceRef.off "value", handlePresenceValue
usersRef.off "value", handleUsersValue
presenceRef.remove()
roomRef = null
chatRef = null
return unless room
roomRef = new Firebase("https://filearts.firebaseio.com/rooms/#{room}/")
chatRef = roomRef.child("messages")
usersRef = roomRef.child("users")
presenceRef = usersRef.child(session.public_id)
setOwnPresence(presenceRef)
chatRef.limit(50).on "child_added", handleChatAdded
presenceRef.on "value", handlePresenceValue
usersRef.on "value", handleUsersValue
setOwnPresence = (presenceRef) -> $timeout ->
presenceRef.removeOnDisconnect()
presenceRef.set($scope.user)
$scope.postChatMessage = ->
if chatRef and $scope.message
message =
body: $scope.message
posted_at: +new Date
user: $scope.user
chatRef.push(message)
$scope.message = ""
$scope.targetMessage = (user) ->
unless $scope.message then $scope.message = "@#{user.name} "
$("#comments-message").focus()
]
|
[
{
"context": "sed under the MIT License\nDate: 11-08-2015\nAuthor: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-",
"end": 104,
"score": 0.9998642802238464,
"start": 86,
"tag": "NAME",
"value": "Julio Cesar Fausto"
},
{
"context": "or: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-rails\n###\n\n@Portfolio = React.create",
"end": 140,
"score": 0.9706160426139832,
"start": 132,
"tag": "USERNAME",
"value": "jcfausto"
},
{
"context": "lio\">See more code on <a href=\"https://github.com/jcfausto\" target=\"_blank\">GitHub</a> and some designs on <",
"end": 1041,
"score": 0.8818085789680481,
"start": 1033,
"tag": "USERNAME",
"value": "jcfausto"
}
] | app/assets/javascripts/components/portfolio.js.jsx.coffee | jcfausto/jcfausto-rails-website | 1 | ###
Portfolio React Component
Released under the MIT License
Date: 11-08-2015
Author: Julio Cesar Fausto
Source: https://github.com/jcfausto/jcfausto-com-rails
###
@Portfolio = React.createClass
getInitialState: ->
portfolio_items: this.props.portfolio_items
#The portfolio is composed of rows with 2 items each. Will be necessary to
#pre-process the portfolio_items in order to produce rows with 2 items.
#Those rows will turn rendering easier
rows: []
#This method mount an array of array representing rows where each
#one have no more than 2 items
mountRows: ->
temp_items = this.state.portfolio_items
this.state.rows.push(temp_items.splice(0, 2)) while temp_items.length
render: ->
this.mountRows()
`<section className="inverted">
<h3><span>Portfolio</span></h3>
{this.state.rows.map(function(row, index){
return (<PortfolioRow key={index} row={row} />)
})
}
<p className="more-portfolio">See more code on <a href="https://github.com/jcfausto" target="_blank">GitHub</a> and some designs on <a href="https://www.behance.net/jcfausto" target="_blank">Bēhance</a>.</p>
</section>`
| 55793 | ###
Portfolio React Component
Released under the MIT License
Date: 11-08-2015
Author: <NAME>
Source: https://github.com/jcfausto/jcfausto-com-rails
###
@Portfolio = React.createClass
getInitialState: ->
portfolio_items: this.props.portfolio_items
#The portfolio is composed of rows with 2 items each. Will be necessary to
#pre-process the portfolio_items in order to produce rows with 2 items.
#Those rows will turn rendering easier
rows: []
#This method mount an array of array representing rows where each
#one have no more than 2 items
mountRows: ->
temp_items = this.state.portfolio_items
this.state.rows.push(temp_items.splice(0, 2)) while temp_items.length
render: ->
this.mountRows()
`<section className="inverted">
<h3><span>Portfolio</span></h3>
{this.state.rows.map(function(row, index){
return (<PortfolioRow key={index} row={row} />)
})
}
<p className="more-portfolio">See more code on <a href="https://github.com/jcfausto" target="_blank">GitHub</a> and some designs on <a href="https://www.behance.net/jcfausto" target="_blank">Bēhance</a>.</p>
</section>`
| true | ###
Portfolio React Component
Released under the MIT License
Date: 11-08-2015
Author: PI:NAME:<NAME>END_PI
Source: https://github.com/jcfausto/jcfausto-com-rails
###
@Portfolio = React.createClass
getInitialState: ->
portfolio_items: this.props.portfolio_items
#The portfolio is composed of rows with 2 items each. Will be necessary to
#pre-process the portfolio_items in order to produce rows with 2 items.
#Those rows will turn rendering easier
rows: []
#This method mount an array of array representing rows where each
#one have no more than 2 items
mountRows: ->
temp_items = this.state.portfolio_items
this.state.rows.push(temp_items.splice(0, 2)) while temp_items.length
render: ->
this.mountRows()
`<section className="inverted">
<h3><span>Portfolio</span></h3>
{this.state.rows.map(function(row, index){
return (<PortfolioRow key={index} row={row} />)
})
}
<p className="more-portfolio">See more code on <a href="https://github.com/jcfausto" target="_blank">GitHub</a> and some designs on <a href="https://www.behance.net/jcfausto" target="_blank">Bēhance</a>.</p>
</section>`
|
[
{
"context": "bars = [\n {\n name: \"Williams and Graham\"\n address: \"3160 Tejon St\"\n coordinates:\n ",
"end": 43,
"score": 0.9998672604560852,
"start": 24,
"tag": "NAME",
"value": "Williams and Graham"
},
{
"context": " close: \"0100\"\n recommendation:\n who: \"joshua\"\n what: \"Any of the house cocktails\"\n w",
"end": 224,
"score": 0.9549579620361328,
"start": 218,
"tag": "NAME",
"value": "joshua"
},
{
"context": "e with an old fashioned feel.\"\n }\n {\n name: \"Great Divide\"\n address: \"2201 Arapahoe St\"\n coordinates:",
"end": 395,
"score": 0.995887815952301,
"start": 383,
"tag": "NAME",
"value": "Great Divide"
},
{
"context": " close: \"2200\"\n recommendation:\n who: \"andrew\"\n what: \"Espresso Oak Aged Yeti\"\n why: ",
"end": 579,
"score": 0.8257275223731995,
"start": 573,
"tag": "NAME",
"value": "andrew"
},
{
"context": "ed. Every beer is phenomenal.\"\n }\n {\n name: \"Crooked Stave\"\n address: \"3350 Brighton Blvd\"\n coordinate",
"end": 753,
"score": 0.9998582005500793,
"start": 740,
"tag": "NAME",
"value": "Crooked Stave"
},
{
"context": " close: \"2300\"\n recommendation:\n who: \"andrew\"\n what: \"Any beer\"\n why: \"If you love s",
"end": 939,
"score": 0.8735735416412354,
"start": 933,
"tag": "NAME",
"value": "andrew"
},
{
"context": "t sour brewery in the nation.\"\n }\n {\n name: \"Blackshirt Brewing\"\n address: \"3719 Walnut St\"\n coordinates:\n ",
"end": 1095,
"score": 0.9969186782836914,
"start": 1077,
"tag": "NAME",
"value": "Blackshirt Brewing"
},
{
"context": " close: \"2300\"\n recommendation:\n who: \"andrew\"\n what: \"Any beer\"\n why: \"They are curr",
"end": 1277,
"score": 0.8349249362945557,
"start": 1271,
"tag": "NAME",
"value": "andrew"
},
{
"context": "vibe and that’s a good thing.\"\n }\n {\n name: \"Lost Highway Brewing\"\n address: \"520 E Colfax Ave\"\n coordinates:",
"end": 1463,
"score": 0.9975073337554932,
"start": 1443,
"tag": "NAME",
"value": "Lost Highway Brewing"
},
{
"context": " close: \"2200\"\n recommendation:\n who: \"andrew\"\n what: \"Too many to list\"\n why: \"Tradi",
"end": 1647,
"score": 0.9185131192207336,
"start": 1641,
"tag": "NAME",
"value": "andrew"
},
{
"context": "by the owners of Cheeky Monk.\"\n }\n {\n name: \"Mile High Spirits & Distillery\"\n address: \"2201 Lawrence St\"\n coordinates:",
"end": 1819,
"score": 0.9875060319900513,
"start": 1789,
"tag": "NAME",
"value": "Mile High Spirits & Distillery"
},
{
"context": " close: \"0200\"\n recommendation:\n who: \"andrew\"\n what: \"Denver Gold Rush\"\n why: \"Great",
"end": 2003,
"score": 0.8920386433601379,
"start": 1997,
"tag": "NAME",
"value": "andrew"
},
{
"context": " recommendation:\n who: \"andrew\"\n what: \"Denver Gold Rush\"\n why: \"Great atmosphere with food trucks, g",
"end": 2034,
"score": 0.8565601110458374,
"start": 2018,
"tag": "NAME",
"value": "Denver Gold Rush"
},
{
"context": "verything distilled in house.\"\n }\n {\n name: \"Grandma’s House Brewery\"\n address: \"1710 S Broadway\"\n coordinates:\n",
"end": 2183,
"score": 0.9983895421028137,
"start": 2160,
"tag": "NAME",
"value": "Grandma’s House Brewery"
},
{
"context": " close: \"2000\"\n recommendation:\n who: \"andrew\"\n what: \"Red IPA\"\n why: \"Probably the m",
"end": 2366,
"score": 0.970114529132843,
"start": 2360,
"tag": "NAME",
"value": "andrew"
},
{
"context": "rs, crochet koozies, and NES.\"\n }\n {\n name: \"Blake Street Vault\"\n address: \"1526 Blake St\"\n coordinates:\n ",
"end": 2573,
"score": 0.9991298317909241,
"start": 2555,
"tag": "NAME",
"value": "Blake Street Vault"
},
{
"context": " potato fries are really good\"\n }\n {\n name: \"Stem Ciders\"\n address: \"2811 Walnut St\"\n coordinates:\n ",
"end": 2837,
"score": 0.9989473223686218,
"start": 2826,
"tag": "NAME",
"value": "Stem Ciders"
},
{
"context": " close: \"2200\"\n recommendation:\n who: \"elliot\"\n what: \"Ciders are all the rage and this pl",
"end": 3019,
"score": 0.952431321144104,
"start": 3013,
"tag": "USERNAME",
"value": "elliot"
}
] | source/assets/javascripts/picks/bars.coffee | isabella232/summit-guide-2015 | 1 | bars = [
{
name: "Williams and Graham"
address: "3160 Tejon St"
coordinates:
lat: 39.761873
long: -105.011013
hours:
open: "1700"
close: "0100"
recommendation:
who: "joshua"
what: "Any of the house cocktails"
why: "Recently voted the best bar in America. Speakeasy style with an old fashioned feel."
}
{
name: "Great Divide"
address: "2201 Arapahoe St"
coordinates:
lat: 39.753793
long: -104.988466
hours:
open: "1200"
close: "2200"
recommendation:
who: "andrew"
what: "Espresso Oak Aged Yeti"
why: "One of the original microbreweries in Denver that has exploded. Every beer is phenomenal."
}
{
name: "Crooked Stave"
address: "3350 Brighton Blvd"
coordinates:
lat: 39.768611
long: -104.979758
hours:
open: "1200"
close: "2300"
recommendation:
who: "andrew"
what: "Any beer"
why: "If you love sour beers this is the place. Voted best sour brewery in the nation."
}
{
name: "Blackshirt Brewing"
address: "3719 Walnut St"
coordinates:
lat: 39.769858
long: -104.972962
hours:
open: "1200"
close: "2300"
recommendation:
who: "andrew"
what: "Any beer"
why: "They are currently doing ONLY red ale based beers. The brewery has a different vibe and that’s a good thing."
}
{
name: "Lost Highway Brewing"
address: "520 E Colfax Ave"
coordinates:
lat: 39.739778
long: -104.980410
hours:
open: "1400"
close: "2200"
recommendation:
who: "andrew"
what: "Too many to list"
why: "Traditional Belgian-style beers brought to you by the owners of Cheeky Monk."
}
{
name: "Mile High Spirits & Distillery"
address: "2201 Lawrence St"
coordinates:
lat: 39.754540
long: -104.989276
hours:
open: "1500"
close: "0200"
recommendation:
who: "andrew"
what: "Denver Gold Rush"
why: "Great atmosphere with food trucks, great cocktails made from everything distilled in house."
}
{
name: "Grandma’s House Brewery"
address: "1710 S Broadway"
coordinates:
lat: 39.685463
long: -104.987172
hours:
open: "1400"
close: "2000"
recommendation:
who: "andrew"
what: "Red IPA"
why: "Probably the most hipster place you’ll ever enter. It looks like your grandma’s house with rocking chairs, crochet koozies, and NES."
}
{
name: "Blake Street Vault"
address: "1526 Blake St"
coordinates:
lat: 39.749825
long: -104.999620
hours:
open: "1100"
close: "2400"
recommendation:
who: "sean"
what: "The sweet potato fries are really good"
}
{
name: "Stem Ciders"
address: "2811 Walnut St"
coordinates:
lat: 39.761635
long: -104.983791
hours:
open: "1600"
close: "2200"
recommendation:
who: "elliot"
what: "Ciders are all the rage and this place has some good ones. It's tiny inside but well worth it, and the owners are cool."
}
]
localStorage.setItem("bars", JSON.stringify(bars))
| 85982 | bars = [
{
name: "<NAME>"
address: "3160 Tejon St"
coordinates:
lat: 39.761873
long: -105.011013
hours:
open: "1700"
close: "0100"
recommendation:
who: "<NAME>"
what: "Any of the house cocktails"
why: "Recently voted the best bar in America. Speakeasy style with an old fashioned feel."
}
{
name: "<NAME>"
address: "2201 Arapahoe St"
coordinates:
lat: 39.753793
long: -104.988466
hours:
open: "1200"
close: "2200"
recommendation:
who: "<NAME>"
what: "Espresso Oak Aged Yeti"
why: "One of the original microbreweries in Denver that has exploded. Every beer is phenomenal."
}
{
name: "<NAME>"
address: "3350 Brighton Blvd"
coordinates:
lat: 39.768611
long: -104.979758
hours:
open: "1200"
close: "2300"
recommendation:
who: "<NAME>"
what: "Any beer"
why: "If you love sour beers this is the place. Voted best sour brewery in the nation."
}
{
name: "<NAME>"
address: "3719 Walnut St"
coordinates:
lat: 39.769858
long: -104.972962
hours:
open: "1200"
close: "2300"
recommendation:
who: "<NAME>"
what: "Any beer"
why: "They are currently doing ONLY red ale based beers. The brewery has a different vibe and that’s a good thing."
}
{
name: "<NAME>"
address: "520 E Colfax Ave"
coordinates:
lat: 39.739778
long: -104.980410
hours:
open: "1400"
close: "2200"
recommendation:
who: "<NAME>"
what: "Too many to list"
why: "Traditional Belgian-style beers brought to you by the owners of Cheeky Monk."
}
{
name: "<NAME>"
address: "2201 Lawrence St"
coordinates:
lat: 39.754540
long: -104.989276
hours:
open: "1500"
close: "0200"
recommendation:
who: "<NAME>"
what: "<NAME>"
why: "Great atmosphere with food trucks, great cocktails made from everything distilled in house."
}
{
name: "<NAME>"
address: "1710 S Broadway"
coordinates:
lat: 39.685463
long: -104.987172
hours:
open: "1400"
close: "2000"
recommendation:
who: "<NAME>"
what: "Red IPA"
why: "Probably the most hipster place you’ll ever enter. It looks like your grandma’s house with rocking chairs, crochet koozies, and NES."
}
{
name: "<NAME>"
address: "1526 Blake St"
coordinates:
lat: 39.749825
long: -104.999620
hours:
open: "1100"
close: "2400"
recommendation:
who: "sean"
what: "The sweet potato fries are really good"
}
{
name: "<NAME>"
address: "2811 Walnut St"
coordinates:
lat: 39.761635
long: -104.983791
hours:
open: "1600"
close: "2200"
recommendation:
who: "elliot"
what: "Ciders are all the rage and this place has some good ones. It's tiny inside but well worth it, and the owners are cool."
}
]
localStorage.setItem("bars", JSON.stringify(bars))
| true | bars = [
{
name: "PI:NAME:<NAME>END_PI"
address: "3160 Tejon St"
coordinates:
lat: 39.761873
long: -105.011013
hours:
open: "1700"
close: "0100"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "Any of the house cocktails"
why: "Recently voted the best bar in America. Speakeasy style with an old fashioned feel."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "2201 Arapahoe St"
coordinates:
lat: 39.753793
long: -104.988466
hours:
open: "1200"
close: "2200"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "Espresso Oak Aged Yeti"
why: "One of the original microbreweries in Denver that has exploded. Every beer is phenomenal."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "3350 Brighton Blvd"
coordinates:
lat: 39.768611
long: -104.979758
hours:
open: "1200"
close: "2300"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "Any beer"
why: "If you love sour beers this is the place. Voted best sour brewery in the nation."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "3719 Walnut St"
coordinates:
lat: 39.769858
long: -104.972962
hours:
open: "1200"
close: "2300"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "Any beer"
why: "They are currently doing ONLY red ale based beers. The brewery has a different vibe and that’s a good thing."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "520 E Colfax Ave"
coordinates:
lat: 39.739778
long: -104.980410
hours:
open: "1400"
close: "2200"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "Too many to list"
why: "Traditional Belgian-style beers brought to you by the owners of Cheeky Monk."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "2201 Lawrence St"
coordinates:
lat: 39.754540
long: -104.989276
hours:
open: "1500"
close: "0200"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "PI:NAME:<NAME>END_PI"
why: "Great atmosphere with food trucks, great cocktails made from everything distilled in house."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "1710 S Broadway"
coordinates:
lat: 39.685463
long: -104.987172
hours:
open: "1400"
close: "2000"
recommendation:
who: "PI:NAME:<NAME>END_PI"
what: "Red IPA"
why: "Probably the most hipster place you’ll ever enter. It looks like your grandma’s house with rocking chairs, crochet koozies, and NES."
}
{
name: "PI:NAME:<NAME>END_PI"
address: "1526 Blake St"
coordinates:
lat: 39.749825
long: -104.999620
hours:
open: "1100"
close: "2400"
recommendation:
who: "sean"
what: "The sweet potato fries are really good"
}
{
name: "PI:NAME:<NAME>END_PI"
address: "2811 Walnut St"
coordinates:
lat: 39.761635
long: -104.983791
hours:
open: "1600"
close: "2200"
recommendation:
who: "elliot"
what: "Ciders are all the rage and this place has some good ones. It's tiny inside but well worth it, and the owners are cool."
}
]
localStorage.setItem("bars", JSON.stringify(bars))
|
[
{
"context": "sical|pgup|pgdn|perform|pen|pattern|path|password|passw|pass|\\\n parse|parent|parameters|parameter|page",
"end": 5812,
"score": 0.962083101272583,
"start": 5807,
"tag": "PASSWORD",
"value": "passw"
},
{
"context": "pgup|pgdn|perform|pen|pattern|path|password|passw|pass|\\\n parse|parent|parameters|parameter|page|pack",
"end": 5817,
"score": 0.9831317663192749,
"start": 5813,
"tag": "PASSWORD",
"value": "pass"
}
] | grammars/natural.cson | llrt/language-natural | 4 | name: 'Natural'
scopeName: 'source.natural'
fileTypes: [ 'nat', 'nsp', 'nsn', 'nsl' ]
patterns: [
{ include: '#wrong' },
{ include: '#comments' },
{ include: '#hash_vars' },
{ include: '#numbers' },
{ include: '#strings' },
{ include: '#data_definition' },
{ include: '#subroutine' },
{ include: '#operators' },
{ include: '#keywords' },
{ include: '#date_and_time' },
{ include: '#labels' },
{ include: '#placeholder' },
{ include: '#trailing_space' },
{ include: '#keys' },
{ include: '#system_vars' },
{ include: '#variable_modifier' }
]
repository: {
wrong: {
name: 'invalid',
match: '\\t'
},
comments: {
name: 'comment.natural',
match: '(^\\*.*$|\\/\\*.*$)'
},
hash_vars: {
name: 'variable.natural'
match: '\\#[a-zA-Z0-9-]+'
},
numbers: {
patterns: [
{
name: 'constant.numeric.natural',
match: '(?<![\\w-])[\\+\\-]?[0-9]+[,.]?[0-9]*(?![\\w-])'
},
{
name: 'constant.numeric.hex.natural',
match: '([hH]?)\\\'[0-9a-fA-F]+\\\'',
captures: {
'1': { name: 'punctuation.definition.hex.natural' }
}
}
]
},
strings: {
patterns: [
{
name: 'string.natural',
begin: '([uU]?)\\\'',
beginCaptures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
},
end: '\\\'',
applyEndPatternLast: 1,
patterns: [
{
match: '\\\'\\\'',
name: 'constant.character.escape.natural'
}
]
},
{
name: 'string.natural',
begin: '([uU]?)\\\"',
beginCaptures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
},
end: '\\\"',
applyEndPatternLast: 1,
patterns: [
{
match: '\\\"\\\"'
name: 'constant.character.escape.natural'
}
]
},
{
name: 'string.unicode.hex.natural',
match: '(?i:(uh)\\\'[0-9a-f]+\\\')',
captures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
}
}
]
},
data_definition: {
name: 'data.definition.natural',
begin: '(?i:define\\s+data)',
beginCaptures: {
'0': { name: 'keyword.natural' }
},
end: '(?i:end-define)',
endCaptures: {
'0': { name: 'keyword.natural' }
},
patterns: [
{ include: '#comments' },
{ include: '#data_definition_keywords' },
{ include: '#external_storage_area' },
{ include: '#variable_level' },
{ include: '#variable_modifier' },
{ include: '#variable_type' },
{ include: '#view_definition' },
{ include: '#system_vars' },
{ include: '#hash_vars' },
{ include: '#placeholder' },
{ include: '#numbers' },
{ include: '#strings' },
{ include: '#wrong' }
]
},
data_definition_keywords: {
name: 'keyword.natural',
match: '(?<![\\w-])\
(?i:with|view|value|result|redefine|parameter|\
optional|of|object|local|init|independent|global|\
dynamic|context|constant|const|by)\
(?![\\w-])'
},
external_storage_area: {
name: 'storage.definition.using.natural',
match: '(?i:(using)\\s+([a-z0-9]+))',
captures: {
'1': { name: 'keyword.natural' },
'2': { name: 'string.object.natural' }
}
}
variable_level: {
name: 'support.constant.level.natural',
match: '^\\s*[0-9]+'
},
variable_modifier: {
name: 'variable.parameter.natural',
match: '(?<=\\()(?i:ad|al|bx|cd|em|hd|pm)=[^\\)]+'
},
variable_type: {
name: 'storage.type.natural',
match: '(?<=\\()(?i:[abu][0-9]*|[np][0-9\\,\\.]+|i0*[148]|f0*[48]|[cdlt])'
},
view_definition: {
name: 'definition.view.natural',
match: '([a-zA-Z0-9\\-]+)(?=\\s+view)'
},
subroutine: {
name: 'definition.subroutine.natural',
match: '(?<=subroutine)\\s+([a-z0-9\\-]+)',
captures: {
'1': { name: 'entity.name.function.natural' }
}
},
operators: {
name: 'keyword.operator.natural',
match: '(?<![\\w-])(?i:thru|or|notequal|not|ne|lt|less\\s+than\\s+or\\s+equal\\s+to|\
less\\s+than|less\\s+equal|le|gt|greater\\s+than\\s+or\\s+equal\\s+to|\
greater\\s+than|greater\\s+equal|ge|equal\\s+to|equal|eq|but|and)(?![\\w-])'
},
keywords: {
name: 'keyword.natural',
match: '(?<![\\w-])\
(?i:year|xml|write|work|with|window|while|where|when|view|via|\
vertically|vert|variables|variable|vargraphic|values|value|val|\
using|user|used|upper|upload|update|until|unknown|unique|union|\
underlined|types|type|true|treq|translate|transfer|transaction|\
trailer|total|top|to|title|timezone|timestamp|time|thru|then|them|\
than|textvariable|textarea|text|terminate|tan|system|sync|symbol|\
suspend|suppressed|suppress|sum|subtract|substring|substr|subroutine|\
subprograms|subprogram|store|stop|step|status|static|statement|\
starting|start|stack|sqrt|sqlid|sql|specified|space|sound|sortkey|\
sorted|sort|some|skip|size|single|sin|show|short|sgn|settime|sets|\
set|server|sequence|separate|sensitive|send|selection|select|second|\
scroll|screen|scan|same|run|rulevar|rows|row|routine|rounded|rollback|\
right|reversed|returns|return|retry|retained|retain|ret|result|restore|\
response|resize|resetting|reset|required|request|reposition|reporter|\
report|replace|repeat|remainder|release|relationship|relation|rel|\
reject|reinput|referencing|referenced|reduce|redefine|recursively|\
records|record|rec|readonly|read|queryno|quarter|prty|prototype|property|\
program|profile|processing|process|printer|print|prefix|position|pos|\
policy|physical|pgup|pgdn|perform|pen|pattern|path|password|passw|pass|\
parse|parent|parameters|parameter|page|packageset|output|outer|order|or|\
options|optional|optimize|open|only|once|on|old|offset|off|of|occurrences|\
obtain|object|numeric|number|null-handle|null|notitle|notit|not|\
normalized|normalize|none|nohdr|node|no|nmin|newpage|ne|ncount|naver|\
native|namespace|named|name|multiply|multi-fetch|moving|move|more|\
month|module|modified|modal|minute|min|microsecond|mgid|method|messages\
|max|mask|mark|map|macroarea|lt|lower|loop|logical|log-ps|log-ls|log|\
locks|local|listed|lines|lindicator|limit|like|library-password|library|\
libpw|lib|level|less|length|left|leaving|leave|le|last|language|keys|key|\
keep|justified|just|join|isn|is|investigate|inverted|into|intersect|\
intermediate|interface4|interface|intercepted|integer|int|insert|\
insensitive|input|inner|initial|init|indicator|indexed|index|independent|\
incmac|including|included|include|incdir|incdic|inccont|inc|in|import|\
immediate|ignore|if|identical|id|hours|hour|horizontally|horiz|\
hold|histogram|hex|header|having|gui|gt|greater|globals|global|giving|\
give|gfid|get|generated|gen|ge|functions|function|full|from|framed|frac|\
found|forward|forms|formatting|formatted|format|form|for|float|first|find|\
final|filler|fill|file|fields|field|fetch|false|extracting|external|\
export|expand|exp|exit|exists|except|examine|every|event|even|escape|\
errors|error|erase|equal|eq|entire|enter|ending|endhoc|end-work|\
end-toppage|end-subroutine|end-start|end-sort|end-select|end-result|\
end-repeat|end-read|end-prototype|end-property|end-process|end-parse|\
end-parameters|end-norec|end-method|end-loop|end-interface|end-if|\
end-histogram|end-function|end-for|end-find|end-file|end-error|\
end-endpage|end-endfile|end-enddata|end-define|end-decide|end-class|\
end-browse|end-break|end-before|end-all|end|encoded|else|eject|edited|\
dynamic|download|doend|document|do|dnret|dnative|dlogon|dlogoff|divide|\
distinct|display|disp|disabled|direction|digits|dialog-id|dialog|\
descending|desc|delimiters|delimiter|delimited|delete|definition|define|\
decimal|decide|days|day|date|dataarea|data|cursor|current|coupled|count|\
cos|copy|copies|conversation|control|context|constant|const|condition|\
concat|compute|compress|compose|commit|command|codepage|coalesce|close|\
class|cipher|ciph|child|charposition|charlength|char|cdid|case|captioned|\
cap|callnat|calling|calldbproc|call|cabinet|by|but|browse|break|bottom|bot|\
block|between|before|base|backward|backout|avg|aver|auto|authorization|\
auth|attributes|att|atn|at|async|assigning|assign|ascending|asc|as|array|\
application|appl|any|and|alphabetically|alpha|all|alarm|after|add|\
activation|action|accept|absolute|abs)(?![\\w-])'
},
date_and_time: {
name: 'support.constant.datetime.natural',
match: '([tTdDeE]?)\\\'[0-9:\\/\\.\\-]+\\\'',
captures: {
'1': { name: 'punctuation.definition.datetime.natural' }
}
},
labels: {
patterns: [
{
name: 'entity.name.tag.natural',
match: '^\\s*(?i:[a-z0-9]+\\.)(?![\\w])'
},
{
name: 'entity.name.tag.reference.natural',
match: '(?<=\\()(?i:[a-z0-9]+\\.)'
}
]
},
placeholder: {
name: 'support.constant.placeholder.natural',
match: '(?<![\\w-])(?i:[0-9]+x)(?![\\w-])'
},
trailing_space: {
name: 'invalid.deprecated.trailing-whitespace',
match: '[ \\t]+$'
},
keys: {
name: 'support.constant.key.natural',
match: '(?<![\\w-])(?i:p[af][0-9]+|entr|clr|)(?![\\w-])'
},
system_vars: {
name: 'constant.language.natural',
match: "(?i:\\*(winmgrvers|winmgr|window-ps|window-pos|window-ls|username|user\
|ui|ubound|type|tpvers|tpsys|tp|timx|timn|timestmp|timeout|time|timd|\
this-object|subroutine|steplib|startup|server-type|screenio|rowcount|\
program|pid|pf-name|pf-key|patch-level|parse-type|parse-row|\
pars-namespace-uri|parse-level|parse-col|parm-user|pagesize|page-number|\
pagelevel|page-event|osvers|os|opsys|occurrence|number|net-user|natvers|\
machineclass|log-ps|log-ls|locale|linesize|line-count|line|library-id|\
level|length|lbound|language|isn|init-user|init-program|initid|hostname|\
hardware|hardcopy|group|etid|error-ta|error-nr|error-line|devicedatx|datvs|\
datv|datu|datn|datj|dati|datg|date|datd|data|dat4u|dat4j|dat4i|da4e|dat4d|\
cursor|curs-line|curs-field|curs-col|current-unit|cputime|counter|convid|\
com|codepage|browser-io|applic-name|applic-id))"
}
}
| 48180 | name: 'Natural'
scopeName: 'source.natural'
fileTypes: [ 'nat', 'nsp', 'nsn', 'nsl' ]
patterns: [
{ include: '#wrong' },
{ include: '#comments' },
{ include: '#hash_vars' },
{ include: '#numbers' },
{ include: '#strings' },
{ include: '#data_definition' },
{ include: '#subroutine' },
{ include: '#operators' },
{ include: '#keywords' },
{ include: '#date_and_time' },
{ include: '#labels' },
{ include: '#placeholder' },
{ include: '#trailing_space' },
{ include: '#keys' },
{ include: '#system_vars' },
{ include: '#variable_modifier' }
]
repository: {
wrong: {
name: 'invalid',
match: '\\t'
},
comments: {
name: 'comment.natural',
match: '(^\\*.*$|\\/\\*.*$)'
},
hash_vars: {
name: 'variable.natural'
match: '\\#[a-zA-Z0-9-]+'
},
numbers: {
patterns: [
{
name: 'constant.numeric.natural',
match: '(?<![\\w-])[\\+\\-]?[0-9]+[,.]?[0-9]*(?![\\w-])'
},
{
name: 'constant.numeric.hex.natural',
match: '([hH]?)\\\'[0-9a-fA-F]+\\\'',
captures: {
'1': { name: 'punctuation.definition.hex.natural' }
}
}
]
},
strings: {
patterns: [
{
name: 'string.natural',
begin: '([uU]?)\\\'',
beginCaptures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
},
end: '\\\'',
applyEndPatternLast: 1,
patterns: [
{
match: '\\\'\\\'',
name: 'constant.character.escape.natural'
}
]
},
{
name: 'string.natural',
begin: '([uU]?)\\\"',
beginCaptures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
},
end: '\\\"',
applyEndPatternLast: 1,
patterns: [
{
match: '\\\"\\\"'
name: 'constant.character.escape.natural'
}
]
},
{
name: 'string.unicode.hex.natural',
match: '(?i:(uh)\\\'[0-9a-f]+\\\')',
captures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
}
}
]
},
data_definition: {
name: 'data.definition.natural',
begin: '(?i:define\\s+data)',
beginCaptures: {
'0': { name: 'keyword.natural' }
},
end: '(?i:end-define)',
endCaptures: {
'0': { name: 'keyword.natural' }
},
patterns: [
{ include: '#comments' },
{ include: '#data_definition_keywords' },
{ include: '#external_storage_area' },
{ include: '#variable_level' },
{ include: '#variable_modifier' },
{ include: '#variable_type' },
{ include: '#view_definition' },
{ include: '#system_vars' },
{ include: '#hash_vars' },
{ include: '#placeholder' },
{ include: '#numbers' },
{ include: '#strings' },
{ include: '#wrong' }
]
},
data_definition_keywords: {
name: 'keyword.natural',
match: '(?<![\\w-])\
(?i:with|view|value|result|redefine|parameter|\
optional|of|object|local|init|independent|global|\
dynamic|context|constant|const|by)\
(?![\\w-])'
},
external_storage_area: {
name: 'storage.definition.using.natural',
match: '(?i:(using)\\s+([a-z0-9]+))',
captures: {
'1': { name: 'keyword.natural' },
'2': { name: 'string.object.natural' }
}
}
variable_level: {
name: 'support.constant.level.natural',
match: '^\\s*[0-9]+'
},
variable_modifier: {
name: 'variable.parameter.natural',
match: '(?<=\\()(?i:ad|al|bx|cd|em|hd|pm)=[^\\)]+'
},
variable_type: {
name: 'storage.type.natural',
match: '(?<=\\()(?i:[abu][0-9]*|[np][0-9\\,\\.]+|i0*[148]|f0*[48]|[cdlt])'
},
view_definition: {
name: 'definition.view.natural',
match: '([a-zA-Z0-9\\-]+)(?=\\s+view)'
},
subroutine: {
name: 'definition.subroutine.natural',
match: '(?<=subroutine)\\s+([a-z0-9\\-]+)',
captures: {
'1': { name: 'entity.name.function.natural' }
}
},
operators: {
name: 'keyword.operator.natural',
match: '(?<![\\w-])(?i:thru|or|notequal|not|ne|lt|less\\s+than\\s+or\\s+equal\\s+to|\
less\\s+than|less\\s+equal|le|gt|greater\\s+than\\s+or\\s+equal\\s+to|\
greater\\s+than|greater\\s+equal|ge|equal\\s+to|equal|eq|but|and)(?![\\w-])'
},
keywords: {
name: 'keyword.natural',
match: '(?<![\\w-])\
(?i:year|xml|write|work|with|window|while|where|when|view|via|\
vertically|vert|variables|variable|vargraphic|values|value|val|\
using|user|used|upper|upload|update|until|unknown|unique|union|\
underlined|types|type|true|treq|translate|transfer|transaction|\
trailer|total|top|to|title|timezone|timestamp|time|thru|then|them|\
than|textvariable|textarea|text|terminate|tan|system|sync|symbol|\
suspend|suppressed|suppress|sum|subtract|substring|substr|subroutine|\
subprograms|subprogram|store|stop|step|status|static|statement|\
starting|start|stack|sqrt|sqlid|sql|specified|space|sound|sortkey|\
sorted|sort|some|skip|size|single|sin|show|short|sgn|settime|sets|\
set|server|sequence|separate|sensitive|send|selection|select|second|\
scroll|screen|scan|same|run|rulevar|rows|row|routine|rounded|rollback|\
right|reversed|returns|return|retry|retained|retain|ret|result|restore|\
response|resize|resetting|reset|required|request|reposition|reporter|\
report|replace|repeat|remainder|release|relationship|relation|rel|\
reject|reinput|referencing|referenced|reduce|redefine|recursively|\
records|record|rec|readonly|read|queryno|quarter|prty|prototype|property|\
program|profile|processing|process|printer|print|prefix|position|pos|\
policy|physical|pgup|pgdn|perform|pen|pattern|path|password|<PASSWORD>|<PASSWORD>|\
parse|parent|parameters|parameter|page|packageset|output|outer|order|or|\
options|optional|optimize|open|only|once|on|old|offset|off|of|occurrences|\
obtain|object|numeric|number|null-handle|null|notitle|notit|not|\
normalized|normalize|none|nohdr|node|no|nmin|newpage|ne|ncount|naver|\
native|namespace|named|name|multiply|multi-fetch|moving|move|more|\
month|module|modified|modal|minute|min|microsecond|mgid|method|messages\
|max|mask|mark|map|macroarea|lt|lower|loop|logical|log-ps|log-ls|log|\
locks|local|listed|lines|lindicator|limit|like|library-password|library|\
libpw|lib|level|less|length|left|leaving|leave|le|last|language|keys|key|\
keep|justified|just|join|isn|is|investigate|inverted|into|intersect|\
intermediate|interface4|interface|intercepted|integer|int|insert|\
insensitive|input|inner|initial|init|indicator|indexed|index|independent|\
incmac|including|included|include|incdir|incdic|inccont|inc|in|import|\
immediate|ignore|if|identical|id|hours|hour|horizontally|horiz|\
hold|histogram|hex|header|having|gui|gt|greater|globals|global|giving|\
give|gfid|get|generated|gen|ge|functions|function|full|from|framed|frac|\
found|forward|forms|formatting|formatted|format|form|for|float|first|find|\
final|filler|fill|file|fields|field|fetch|false|extracting|external|\
export|expand|exp|exit|exists|except|examine|every|event|even|escape|\
errors|error|erase|equal|eq|entire|enter|ending|endhoc|end-work|\
end-toppage|end-subroutine|end-start|end-sort|end-select|end-result|\
end-repeat|end-read|end-prototype|end-property|end-process|end-parse|\
end-parameters|end-norec|end-method|end-loop|end-interface|end-if|\
end-histogram|end-function|end-for|end-find|end-file|end-error|\
end-endpage|end-endfile|end-enddata|end-define|end-decide|end-class|\
end-browse|end-break|end-before|end-all|end|encoded|else|eject|edited|\
dynamic|download|doend|document|do|dnret|dnative|dlogon|dlogoff|divide|\
distinct|display|disp|disabled|direction|digits|dialog-id|dialog|\
descending|desc|delimiters|delimiter|delimited|delete|definition|define|\
decimal|decide|days|day|date|dataarea|data|cursor|current|coupled|count|\
cos|copy|copies|conversation|control|context|constant|const|condition|\
concat|compute|compress|compose|commit|command|codepage|coalesce|close|\
class|cipher|ciph|child|charposition|charlength|char|cdid|case|captioned|\
cap|callnat|calling|calldbproc|call|cabinet|by|but|browse|break|bottom|bot|\
block|between|before|base|backward|backout|avg|aver|auto|authorization|\
auth|attributes|att|atn|at|async|assigning|assign|ascending|asc|as|array|\
application|appl|any|and|alphabetically|alpha|all|alarm|after|add|\
activation|action|accept|absolute|abs)(?![\\w-])'
},
date_and_time: {
name: 'support.constant.datetime.natural',
match: '([tTdDeE]?)\\\'[0-9:\\/\\.\\-]+\\\'',
captures: {
'1': { name: 'punctuation.definition.datetime.natural' }
}
},
labels: {
patterns: [
{
name: 'entity.name.tag.natural',
match: '^\\s*(?i:[a-z0-9]+\\.)(?![\\w])'
},
{
name: 'entity.name.tag.reference.natural',
match: '(?<=\\()(?i:[a-z0-9]+\\.)'
}
]
},
placeholder: {
name: 'support.constant.placeholder.natural',
match: '(?<![\\w-])(?i:[0-9]+x)(?![\\w-])'
},
trailing_space: {
name: 'invalid.deprecated.trailing-whitespace',
match: '[ \\t]+$'
},
keys: {
name: 'support.constant.key.natural',
match: '(?<![\\w-])(?i:p[af][0-9]+|entr|clr|)(?![\\w-])'
},
system_vars: {
name: 'constant.language.natural',
match: "(?i:\\*(winmgrvers|winmgr|window-ps|window-pos|window-ls|username|user\
|ui|ubound|type|tpvers|tpsys|tp|timx|timn|timestmp|timeout|time|timd|\
this-object|subroutine|steplib|startup|server-type|screenio|rowcount|\
program|pid|pf-name|pf-key|patch-level|parse-type|parse-row|\
pars-namespace-uri|parse-level|parse-col|parm-user|pagesize|page-number|\
pagelevel|page-event|osvers|os|opsys|occurrence|number|net-user|natvers|\
machineclass|log-ps|log-ls|locale|linesize|line-count|line|library-id|\
level|length|lbound|language|isn|init-user|init-program|initid|hostname|\
hardware|hardcopy|group|etid|error-ta|error-nr|error-line|devicedatx|datvs|\
datv|datu|datn|datj|dati|datg|date|datd|data|dat4u|dat4j|dat4i|da4e|dat4d|\
cursor|curs-line|curs-field|curs-col|current-unit|cputime|counter|convid|\
com|codepage|browser-io|applic-name|applic-id))"
}
}
| true | name: 'Natural'
scopeName: 'source.natural'
fileTypes: [ 'nat', 'nsp', 'nsn', 'nsl' ]
patterns: [
{ include: '#wrong' },
{ include: '#comments' },
{ include: '#hash_vars' },
{ include: '#numbers' },
{ include: '#strings' },
{ include: '#data_definition' },
{ include: '#subroutine' },
{ include: '#operators' },
{ include: '#keywords' },
{ include: '#date_and_time' },
{ include: '#labels' },
{ include: '#placeholder' },
{ include: '#trailing_space' },
{ include: '#keys' },
{ include: '#system_vars' },
{ include: '#variable_modifier' }
]
repository: {
wrong: {
name: 'invalid',
match: '\\t'
},
comments: {
name: 'comment.natural',
match: '(^\\*.*$|\\/\\*.*$)'
},
hash_vars: {
name: 'variable.natural'
match: '\\#[a-zA-Z0-9-]+'
},
numbers: {
patterns: [
{
name: 'constant.numeric.natural',
match: '(?<![\\w-])[\\+\\-]?[0-9]+[,.]?[0-9]*(?![\\w-])'
},
{
name: 'constant.numeric.hex.natural',
match: '([hH]?)\\\'[0-9a-fA-F]+\\\'',
captures: {
'1': { name: 'punctuation.definition.hex.natural' }
}
}
]
},
strings: {
patterns: [
{
name: 'string.natural',
begin: '([uU]?)\\\'',
beginCaptures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
},
end: '\\\'',
applyEndPatternLast: 1,
patterns: [
{
match: '\\\'\\\'',
name: 'constant.character.escape.natural'
}
]
},
{
name: 'string.natural',
begin: '([uU]?)\\\"',
beginCaptures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
},
end: '\\\"',
applyEndPatternLast: 1,
patterns: [
{
match: '\\\"\\\"'
name: 'constant.character.escape.natural'
}
]
},
{
name: 'string.unicode.hex.natural',
match: '(?i:(uh)\\\'[0-9a-f]+\\\')',
captures: {
'1': { name: 'punctuation.definition.string.unicode.natural' }
}
}
]
},
data_definition: {
name: 'data.definition.natural',
begin: '(?i:define\\s+data)',
beginCaptures: {
'0': { name: 'keyword.natural' }
},
end: '(?i:end-define)',
endCaptures: {
'0': { name: 'keyword.natural' }
},
patterns: [
{ include: '#comments' },
{ include: '#data_definition_keywords' },
{ include: '#external_storage_area' },
{ include: '#variable_level' },
{ include: '#variable_modifier' },
{ include: '#variable_type' },
{ include: '#view_definition' },
{ include: '#system_vars' },
{ include: '#hash_vars' },
{ include: '#placeholder' },
{ include: '#numbers' },
{ include: '#strings' },
{ include: '#wrong' }
]
},
data_definition_keywords: {
name: 'keyword.natural',
match: '(?<![\\w-])\
(?i:with|view|value|result|redefine|parameter|\
optional|of|object|local|init|independent|global|\
dynamic|context|constant|const|by)\
(?![\\w-])'
},
external_storage_area: {
name: 'storage.definition.using.natural',
match: '(?i:(using)\\s+([a-z0-9]+))',
captures: {
'1': { name: 'keyword.natural' },
'2': { name: 'string.object.natural' }
}
}
variable_level: {
name: 'support.constant.level.natural',
match: '^\\s*[0-9]+'
},
variable_modifier: {
name: 'variable.parameter.natural',
match: '(?<=\\()(?i:ad|al|bx|cd|em|hd|pm)=[^\\)]+'
},
variable_type: {
name: 'storage.type.natural',
match: '(?<=\\()(?i:[abu][0-9]*|[np][0-9\\,\\.]+|i0*[148]|f0*[48]|[cdlt])'
},
view_definition: {
name: 'definition.view.natural',
match: '([a-zA-Z0-9\\-]+)(?=\\s+view)'
},
subroutine: {
name: 'definition.subroutine.natural',
match: '(?<=subroutine)\\s+([a-z0-9\\-]+)',
captures: {
'1': { name: 'entity.name.function.natural' }
}
},
operators: {
name: 'keyword.operator.natural',
match: '(?<![\\w-])(?i:thru|or|notequal|not|ne|lt|less\\s+than\\s+or\\s+equal\\s+to|\
less\\s+than|less\\s+equal|le|gt|greater\\s+than\\s+or\\s+equal\\s+to|\
greater\\s+than|greater\\s+equal|ge|equal\\s+to|equal|eq|but|and)(?![\\w-])'
},
keywords: {
name: 'keyword.natural',
match: '(?<![\\w-])\
(?i:year|xml|write|work|with|window|while|where|when|view|via|\
vertically|vert|variables|variable|vargraphic|values|value|val|\
using|user|used|upper|upload|update|until|unknown|unique|union|\
underlined|types|type|true|treq|translate|transfer|transaction|\
trailer|total|top|to|title|timezone|timestamp|time|thru|then|them|\
than|textvariable|textarea|text|terminate|tan|system|sync|symbol|\
suspend|suppressed|suppress|sum|subtract|substring|substr|subroutine|\
subprograms|subprogram|store|stop|step|status|static|statement|\
starting|start|stack|sqrt|sqlid|sql|specified|space|sound|sortkey|\
sorted|sort|some|skip|size|single|sin|show|short|sgn|settime|sets|\
set|server|sequence|separate|sensitive|send|selection|select|second|\
scroll|screen|scan|same|run|rulevar|rows|row|routine|rounded|rollback|\
right|reversed|returns|return|retry|retained|retain|ret|result|restore|\
response|resize|resetting|reset|required|request|reposition|reporter|\
report|replace|repeat|remainder|release|relationship|relation|rel|\
reject|reinput|referencing|referenced|reduce|redefine|recursively|\
records|record|rec|readonly|read|queryno|quarter|prty|prototype|property|\
program|profile|processing|process|printer|print|prefix|position|pos|\
policy|physical|pgup|pgdn|perform|pen|pattern|path|password|PI:PASSWORD:<PASSWORD>END_PI|PI:PASSWORD:<PASSWORD>END_PI|\
parse|parent|parameters|parameter|page|packageset|output|outer|order|or|\
options|optional|optimize|open|only|once|on|old|offset|off|of|occurrences|\
obtain|object|numeric|number|null-handle|null|notitle|notit|not|\
normalized|normalize|none|nohdr|node|no|nmin|newpage|ne|ncount|naver|\
native|namespace|named|name|multiply|multi-fetch|moving|move|more|\
month|module|modified|modal|minute|min|microsecond|mgid|method|messages\
|max|mask|mark|map|macroarea|lt|lower|loop|logical|log-ps|log-ls|log|\
locks|local|listed|lines|lindicator|limit|like|library-password|library|\
libpw|lib|level|less|length|left|leaving|leave|le|last|language|keys|key|\
keep|justified|just|join|isn|is|investigate|inverted|into|intersect|\
intermediate|interface4|interface|intercepted|integer|int|insert|\
insensitive|input|inner|initial|init|indicator|indexed|index|independent|\
incmac|including|included|include|incdir|incdic|inccont|inc|in|import|\
immediate|ignore|if|identical|id|hours|hour|horizontally|horiz|\
hold|histogram|hex|header|having|gui|gt|greater|globals|global|giving|\
give|gfid|get|generated|gen|ge|functions|function|full|from|framed|frac|\
found|forward|forms|formatting|formatted|format|form|for|float|first|find|\
final|filler|fill|file|fields|field|fetch|false|extracting|external|\
export|expand|exp|exit|exists|except|examine|every|event|even|escape|\
errors|error|erase|equal|eq|entire|enter|ending|endhoc|end-work|\
end-toppage|end-subroutine|end-start|end-sort|end-select|end-result|\
end-repeat|end-read|end-prototype|end-property|end-process|end-parse|\
end-parameters|end-norec|end-method|end-loop|end-interface|end-if|\
end-histogram|end-function|end-for|end-find|end-file|end-error|\
end-endpage|end-endfile|end-enddata|end-define|end-decide|end-class|\
end-browse|end-break|end-before|end-all|end|encoded|else|eject|edited|\
dynamic|download|doend|document|do|dnret|dnative|dlogon|dlogoff|divide|\
distinct|display|disp|disabled|direction|digits|dialog-id|dialog|\
descending|desc|delimiters|delimiter|delimited|delete|definition|define|\
decimal|decide|days|day|date|dataarea|data|cursor|current|coupled|count|\
cos|copy|copies|conversation|control|context|constant|const|condition|\
concat|compute|compress|compose|commit|command|codepage|coalesce|close|\
class|cipher|ciph|child|charposition|charlength|char|cdid|case|captioned|\
cap|callnat|calling|calldbproc|call|cabinet|by|but|browse|break|bottom|bot|\
block|between|before|base|backward|backout|avg|aver|auto|authorization|\
auth|attributes|att|atn|at|async|assigning|assign|ascending|asc|as|array|\
application|appl|any|and|alphabetically|alpha|all|alarm|after|add|\
activation|action|accept|absolute|abs)(?![\\w-])'
},
date_and_time: {
name: 'support.constant.datetime.natural',
match: '([tTdDeE]?)\\\'[0-9:\\/\\.\\-]+\\\'',
captures: {
'1': { name: 'punctuation.definition.datetime.natural' }
}
},
labels: {
patterns: [
{
name: 'entity.name.tag.natural',
match: '^\\s*(?i:[a-z0-9]+\\.)(?![\\w])'
},
{
name: 'entity.name.tag.reference.natural',
match: '(?<=\\()(?i:[a-z0-9]+\\.)'
}
]
},
placeholder: {
name: 'support.constant.placeholder.natural',
match: '(?<![\\w-])(?i:[0-9]+x)(?![\\w-])'
},
trailing_space: {
name: 'invalid.deprecated.trailing-whitespace',
match: '[ \\t]+$'
},
keys: {
name: 'support.constant.key.natural',
match: '(?<![\\w-])(?i:p[af][0-9]+|entr|clr|)(?![\\w-])'
},
system_vars: {
name: 'constant.language.natural',
match: "(?i:\\*(winmgrvers|winmgr|window-ps|window-pos|window-ls|username|user\
|ui|ubound|type|tpvers|tpsys|tp|timx|timn|timestmp|timeout|time|timd|\
this-object|subroutine|steplib|startup|server-type|screenio|rowcount|\
program|pid|pf-name|pf-key|patch-level|parse-type|parse-row|\
pars-namespace-uri|parse-level|parse-col|parm-user|pagesize|page-number|\
pagelevel|page-event|osvers|os|opsys|occurrence|number|net-user|natvers|\
machineclass|log-ps|log-ls|locale|linesize|line-count|line|library-id|\
level|length|lbound|language|isn|init-user|init-program|initid|hostname|\
hardware|hardcopy|group|etid|error-ta|error-nr|error-line|devicedatx|datvs|\
datv|datu|datn|datj|dati|datg|date|datd|data|dat4u|dat4j|dat4i|da4e|dat4d|\
cursor|curs-line|curs-field|curs-col|current-unit|cputime|counter|convid|\
com|codepage|browser-io|applic-name|applic-id))"
}
}
|
[
{
"context": "s file is part of the Konsserto package.\n *\n * (c) Marvin Frachet <marvin@konsserto.com>\n * (c) Jessym Reziga <jess",
"end": 75,
"score": 0.9998891949653625,
"start": 61,
"tag": "NAME",
"value": "Marvin Frachet"
},
{
"context": " the Konsserto package.\n *\n * (c) Marvin Frachet <marvin@konsserto.com>\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n ",
"end": 97,
"score": 0.9999356865882874,
"start": 77,
"tag": "EMAIL",
"value": "marvin@konsserto.com"
},
{
"context": "* (c) Marvin Frachet <marvin@konsserto.com>\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig",
"end": 119,
"score": 0.9999015927314758,
"start": 106,
"tag": "NAME",
"value": "Jessym Reziga"
},
{
"context": "chet <marvin@konsserto.com>\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyright and license informa",
"end": 141,
"score": 0.9999364614486694,
"start": 121,
"tag": "EMAIL",
"value": "jessym@konsserto.com"
},
{
"context": "/Finder/Directory')\n\n# DirectoryFinder\n#\n# @author Marvin Frachet <marvin@konsserto.com>\nclass DirectoryFinder\n\n #",
"end": 396,
"score": 0.9998908042907715,
"start": 382,
"tag": "NAME",
"value": "Marvin Frachet"
},
{
"context": "')\n\n# DirectoryFinder\n#\n# @author Marvin Frachet <marvin@konsserto.com>\nclass DirectoryFinder\n\n # Class constructor\n c",
"end": 418,
"score": 0.999934732913971,
"start": 398,
"tag": "EMAIL",
"value": "marvin@konsserto.com"
}
] | node_modules/konsserto/lib/src/Konsserto/Component/Finder/DirectoryFinder.coffee | konsserto/konsserto | 2 | ###
* This file is part of the Konsserto package.
*
* (c) Marvin Frachet <marvin@konsserto.com>
* (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.
###
fs = use('fs')
Directory = use('@Konsserto/Component/Finder/Directory')
# DirectoryFinder
#
# @author Marvin Frachet <marvin@konsserto.com>
class DirectoryFinder
# Class constructor
constructor: ()->
@directories = []
# Method finding and pushing the directories found in the directories variable
# @param {String} rootDir Root directory where the search starts
# @param {Boolean} recursive Is the search recursive in folders ?
getDirs: (rootDir, recursive)->
files = fs.readdirSync(rootDir)
for file in files
if file[0] != '.'
filePath = "#{rootDir}/#{file}"
stat = fs.statSync(filePath)
if stat.isDirectory()
@directories.push(new Directory(file, rootDir))
if recursive
@getDirs(rootDir + "/" + file, recursive)
# Method filtering the directories by name
# @param {String} name Name that should filters the directories variable
name: (name)->
new_directories = []
for file in @directories
if file.getName().match name
new_directories.push file
@directories = new_directories
# Method filtering the directories by name (doesn't contain the name are kept)
# @param {String} name Name that should filters the directories variable
notName: (name)->
new_directories = []
for file in @directories
if !file.getName().match name
new_directories.push file
@directories = new_directories
# Method ordering the directories resultset
# @param {String} orderby Order by the attribute
# @param {Boolean} orderway Order by the orderway direction (DESC, ASC)
sortBy: (orderby, orderway) ->
if !orderway
@directories.sort (a, b)->
return if a[orderby] >= b[orderby] then 1 else -1
else
@directories.sort (a, b)->
return if a[orderby] >= b[orderby] then -1 else 1
# Method returning the directories variable
# @return [Directory] directories
getResult: ()->
return @directories
module.exports = DirectoryFinder | 174617 | ###
* This file is part of the Konsserto package.
*
* (c) <NAME> <<EMAIL>>
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
###
fs = use('fs')
Directory = use('@Konsserto/Component/Finder/Directory')
# DirectoryFinder
#
# @author <NAME> <<EMAIL>>
class DirectoryFinder
# Class constructor
constructor: ()->
@directories = []
# Method finding and pushing the directories found in the directories variable
# @param {String} rootDir Root directory where the search starts
# @param {Boolean} recursive Is the search recursive in folders ?
getDirs: (rootDir, recursive)->
files = fs.readdirSync(rootDir)
for file in files
if file[0] != '.'
filePath = "#{rootDir}/#{file}"
stat = fs.statSync(filePath)
if stat.isDirectory()
@directories.push(new Directory(file, rootDir))
if recursive
@getDirs(rootDir + "/" + file, recursive)
# Method filtering the directories by name
# @param {String} name Name that should filters the directories variable
name: (name)->
new_directories = []
for file in @directories
if file.getName().match name
new_directories.push file
@directories = new_directories
# Method filtering the directories by name (doesn't contain the name are kept)
# @param {String} name Name that should filters the directories variable
notName: (name)->
new_directories = []
for file in @directories
if !file.getName().match name
new_directories.push file
@directories = new_directories
# Method ordering the directories resultset
# @param {String} orderby Order by the attribute
# @param {Boolean} orderway Order by the orderway direction (DESC, ASC)
sortBy: (orderby, orderway) ->
if !orderway
@directories.sort (a, b)->
return if a[orderby] >= b[orderby] then 1 else -1
else
@directories.sort (a, b)->
return if a[orderby] >= b[orderby] then -1 else 1
# Method returning the directories variable
# @return [Directory] directories
getResult: ()->
return @directories
module.exports = DirectoryFinder | true | ###
* This file is part of the Konsserto package.
*
* (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
* (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.
###
fs = use('fs')
Directory = use('@Konsserto/Component/Finder/Directory')
# DirectoryFinder
#
# @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
class DirectoryFinder
# Class constructor
constructor: ()->
@directories = []
# Method finding and pushing the directories found in the directories variable
# @param {String} rootDir Root directory where the search starts
# @param {Boolean} recursive Is the search recursive in folders ?
getDirs: (rootDir, recursive)->
files = fs.readdirSync(rootDir)
for file in files
if file[0] != '.'
filePath = "#{rootDir}/#{file}"
stat = fs.statSync(filePath)
if stat.isDirectory()
@directories.push(new Directory(file, rootDir))
if recursive
@getDirs(rootDir + "/" + file, recursive)
# Method filtering the directories by name
# @param {String} name Name that should filters the directories variable
name: (name)->
new_directories = []
for file in @directories
if file.getName().match name
new_directories.push file
@directories = new_directories
# Method filtering the directories by name (doesn't contain the name are kept)
# @param {String} name Name that should filters the directories variable
notName: (name)->
new_directories = []
for file in @directories
if !file.getName().match name
new_directories.push file
@directories = new_directories
# Method ordering the directories resultset
# @param {String} orderby Order by the attribute
# @param {Boolean} orderway Order by the orderway direction (DESC, ASC)
sortBy: (orderby, orderway) ->
if !orderway
@directories.sort (a, b)->
return if a[orderby] >= b[orderby] then 1 else -1
else
@directories.sort (a, b)->
return if a[orderby] >= b[orderby] then -1 else 1
# Method returning the directories variable
# @return [Directory] directories
getResult: ()->
return @directories
module.exports = DirectoryFinder |
[
{
"context": "\n ))\n\n # Test variables\n userId = 1\n token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRldiIsIm9yaWdfaWF0IjoxNDI4OTI5OTA4LCJ1c2VyX2lkIjoxLCJlbWFpbCI6Im1heGltZS5tb3JpbGxlQGdtYWlsLmNvbSIsImV4cCI6MTQyODkzMDIwOH0.0sOnguP31sXIklgmZOginVciR0b6m-aJCMs5uWDDYu8'\n newToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVC",
"end": 492,
"score": 0.999697208404541,
"start": 272,
"tag": "KEY",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRldiIsIm9yaWdfaWF0IjoxNDI4OTI5OTA4LCJ1c2VyX2lkIjoxLCJlbWFpbCI6Im1heGltZS5tb3JpbGxlQGdtYWlsLmNvbSIsImV4cCI6MTQyODkzMDIwOH0.0sOnguP31sXIklgmZOginVciR0b6m-aJCMs5uWDDYu8"
},
{
"context": "sXIklgmZOginVciR0b6m-aJCMs5uWDDYu8'\n newToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'\n\n it('should create a session', () ->\n expec",
"end": 657,
"score": 0.9997029900550842,
"start": 508,
"tag": "KEY",
"value": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
}
] | test/spec/services/session.coffee | MaximeMorille/BoardGamesCriticsClient | 0 | 'use strict'
describe('Service: session', ->
# load the service's module
beforeEach(module('boardGamesCriticsClientApp'))
# instantiate service
session = {}
beforeEach(inject((Session) ->
session = Session
))
# Test variables
userId = 1
token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImRldiIsIm9yaWdfaWF0IjoxNDI4OTI5OTA4LCJ1c2VyX2lkIjoxLCJlbWFpbCI6Im1heGltZS5tb3JpbGxlQGdtYWlsLmNvbSIsImV4cCI6MTQyODkzMDIwOH0.0sOnguP31sXIklgmZOginVciR0b6m-aJCMs5uWDDYu8'
newToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ'
it('should create a session', () ->
expect(!!session).toBe(true)
expect(!!session.create).toBe(true)
session.create(token)
# A session must have an userId and a token
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
)
it('should destroy a session', () ->
expect(!!session).toBe(true)
expect(!!session.destroy).toBe(true)
session.create(token)
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
session.destroy()
# Once destroyed, a session's properties should be undefined
expect(session.user).toBeUndefined()
expect(session.token).toBeUndefined()
)
it('should update a token', () ->
expect(!!session).toBe(true)
expect(!!session.updateToken).toBe(true)
session.create(token)
# Check the session's creation
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
session.updateToken(newToken)
# If no oldToken, the token is updated
expect(session.token).toBe(newToken)
session.updateToken(token, token)
# If oldToken is not the session's token, the token is not updated
expect(session.token).not.toBe(token)
session.updateToken(token, newToken)
# If oldToken is the session's token, the token is updated
expect(session.token).toBe(token)
)
)
| 135437 | 'use strict'
describe('Service: session', ->
# load the service's module
beforeEach(module('boardGamesCriticsClientApp'))
# instantiate service
session = {}
beforeEach(inject((Session) ->
session = Session
))
# Test variables
userId = 1
token = '<KEY>'
newToken = '<KEY>'
it('should create a session', () ->
expect(!!session).toBe(true)
expect(!!session.create).toBe(true)
session.create(token)
# A session must have an userId and a token
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
)
it('should destroy a session', () ->
expect(!!session).toBe(true)
expect(!!session.destroy).toBe(true)
session.create(token)
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
session.destroy()
# Once destroyed, a session's properties should be undefined
expect(session.user).toBeUndefined()
expect(session.token).toBeUndefined()
)
it('should update a token', () ->
expect(!!session).toBe(true)
expect(!!session.updateToken).toBe(true)
session.create(token)
# Check the session's creation
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
session.updateToken(newToken)
# If no oldToken, the token is updated
expect(session.token).toBe(newToken)
session.updateToken(token, token)
# If oldToken is not the session's token, the token is not updated
expect(session.token).not.toBe(token)
session.updateToken(token, newToken)
# If oldToken is the session's token, the token is updated
expect(session.token).toBe(token)
)
)
| true | 'use strict'
describe('Service: session', ->
# load the service's module
beforeEach(module('boardGamesCriticsClientApp'))
# instantiate service
session = {}
beforeEach(inject((Session) ->
session = Session
))
# Test variables
userId = 1
token = 'PI:KEY:<KEY>END_PI'
newToken = 'PI:KEY:<KEY>END_PI'
it('should create a session', () ->
expect(!!session).toBe(true)
expect(!!session.create).toBe(true)
session.create(token)
# A session must have an userId and a token
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
)
it('should destroy a session', () ->
expect(!!session).toBe(true)
expect(!!session.destroy).toBe(true)
session.create(token)
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
session.destroy()
# Once destroyed, a session's properties should be undefined
expect(session.user).toBeUndefined()
expect(session.token).toBeUndefined()
)
it('should update a token', () ->
expect(!!session).toBe(true)
expect(!!session.updateToken).toBe(true)
session.create(token)
# Check the session's creation
expect(session.user.id).toBe(userId)
expect(session.token).toBe(token)
session.updateToken(newToken)
# If no oldToken, the token is updated
expect(session.token).toBe(newToken)
session.updateToken(token, token)
# If oldToken is not the session's token, the token is not updated
expect(session.token).not.toBe(token)
session.updateToken(token, newToken)
# If oldToken is the session's token, the token is updated
expect(session.token).toBe(token)
)
)
|
[
{
"context": "Module\n\n@namespace Quo\n@class Environment\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\n",
"end": 86,
"score": 0.9998422265052795,
"start": 65,
"tag": "NAME",
"value": "Javier Jimenez Villar"
},
{
"context": "class Environment\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\ndo ($$ = Quo) ->\n",
"end": 103,
"score": 0.9999369382858276,
"start": 88,
"tag": "EMAIL",
"value": "javi@tapquo.com"
}
] | source/quo.environment.coffee | TNT-RoX/QuoJS | 1 | ###
Basic Quo Module
@namespace Quo
@class Environment
@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
_current = null
IS_WEBKIT = /WebKit\/([\d.]+)/
SUPPORTED_OS =
Android : /(Android)\s+([\d.]+)/
ipad : /(iPad).*OS\s([\d_]+)/
iphone : /(iPhone\sOS)\s([\d_]+)/
Blackberry: /(BlackBerry|BB10|Playbook).*Version\/([\d.]+)/
FirefoxOS : /(Mozilla).*Mobile[^\/]*\/([\d\.]*)/
webOS : /(webOS|hpwOS)[\s\/]([\d.]+)/
###
Remove attribute to a given instance element
@method isMobile
@return {boolean} True if it's mobile, False if not.
###
$$.isMobile = ->
@environment()
_current.isMobile
###
Remove attribute to a given instance element
@method environment
@return {object} Environment attributes
###
$$.environment = ->
unless _current
user_agent = navigator.userAgent
os = _detectOS(user_agent)
_current =
browser : _detectBrowser(user_agent)
isMobile: !!os
screen : _detectScreen()
os : os
_current
# ---------------------------------------------------------------------------
# Private Methods
# ---------------------------------------------------------------------------
_detectBrowser = (user_agent) ->
webkit = user_agent.match(IS_WEBKIT)
if webkit then webkit[0] else user_agent
_detectOS = (user_agent) ->
for os of SUPPORTED_OS
supported = user_agent.match SUPPORTED_OS[os]
if supported
detected_os =
name : if os in ["iphone", "ipad", "ipod"] then "ios" else os
version : supported[2].replace("_", ".")
break
detected_os
_detectScreen = ->
width: window.innerWidth
height: window.innerHeight
| 29073 | ###
Basic Quo Module
@namespace Quo
@class Environment
@author <NAME> <<EMAIL>> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
_current = null
IS_WEBKIT = /WebKit\/([\d.]+)/
SUPPORTED_OS =
Android : /(Android)\s+([\d.]+)/
ipad : /(iPad).*OS\s([\d_]+)/
iphone : /(iPhone\sOS)\s([\d_]+)/
Blackberry: /(BlackBerry|BB10|Playbook).*Version\/([\d.]+)/
FirefoxOS : /(Mozilla).*Mobile[^\/]*\/([\d\.]*)/
webOS : /(webOS|hpwOS)[\s\/]([\d.]+)/
###
Remove attribute to a given instance element
@method isMobile
@return {boolean} True if it's mobile, False if not.
###
$$.isMobile = ->
@environment()
_current.isMobile
###
Remove attribute to a given instance element
@method environment
@return {object} Environment attributes
###
$$.environment = ->
unless _current
user_agent = navigator.userAgent
os = _detectOS(user_agent)
_current =
browser : _detectBrowser(user_agent)
isMobile: !!os
screen : _detectScreen()
os : os
_current
# ---------------------------------------------------------------------------
# Private Methods
# ---------------------------------------------------------------------------
_detectBrowser = (user_agent) ->
webkit = user_agent.match(IS_WEBKIT)
if webkit then webkit[0] else user_agent
_detectOS = (user_agent) ->
for os of SUPPORTED_OS
supported = user_agent.match SUPPORTED_OS[os]
if supported
detected_os =
name : if os in ["iphone", "ipad", "ipod"] then "ios" else os
version : supported[2].replace("_", ".")
break
detected_os
_detectScreen = ->
width: window.innerWidth
height: window.innerHeight
| true | ###
Basic Quo Module
@namespace Quo
@class Environment
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
_current = null
IS_WEBKIT = /WebKit\/([\d.]+)/
SUPPORTED_OS =
Android : /(Android)\s+([\d.]+)/
ipad : /(iPad).*OS\s([\d_]+)/
iphone : /(iPhone\sOS)\s([\d_]+)/
Blackberry: /(BlackBerry|BB10|Playbook).*Version\/([\d.]+)/
FirefoxOS : /(Mozilla).*Mobile[^\/]*\/([\d\.]*)/
webOS : /(webOS|hpwOS)[\s\/]([\d.]+)/
###
Remove attribute to a given instance element
@method isMobile
@return {boolean} True if it's mobile, False if not.
###
$$.isMobile = ->
@environment()
_current.isMobile
###
Remove attribute to a given instance element
@method environment
@return {object} Environment attributes
###
$$.environment = ->
unless _current
user_agent = navigator.userAgent
os = _detectOS(user_agent)
_current =
browser : _detectBrowser(user_agent)
isMobile: !!os
screen : _detectScreen()
os : os
_current
# ---------------------------------------------------------------------------
# Private Methods
# ---------------------------------------------------------------------------
_detectBrowser = (user_agent) ->
webkit = user_agent.match(IS_WEBKIT)
if webkit then webkit[0] else user_agent
_detectOS = (user_agent) ->
for os of SUPPORTED_OS
supported = user_agent.match SUPPORTED_OS[os]
if supported
detected_os =
name : if os in ["iphone", "ipad", "ipod"] then "ios" else os
version : supported[2].replace("_", ".")
break
detected_os
_detectScreen = ->
width: window.innerWidth
height: window.innerHeight
|
[
{
"context": "# Description:\n# When Steve Holt hears his name, Steve Holt makes his presence kno",
"end": 34,
"score": 0.9994603991508484,
"start": 24,
"tag": "NAME",
"value": "Steve Holt"
},
{
"context": "# Description:\n# When Steve Holt hears his name, Steve Holt makes his presence known\n#\n# Dependencies:\n# No",
"end": 61,
"score": 0.9994659423828125,
"start": 51,
"tag": "NAME",
"value": "Steve Holt"
},
{
"context": "#\n# Commands:\n# steve holt - Display an image of Steve Holt\n#\n# Author:\n# klamping\n\nsteves = [\n \"http://ww",
"end": 203,
"score": 0.997565507888794,
"start": 193,
"tag": "NAME",
"value": "Steve Holt"
},
{
"context": "t - Display an image of Steve Holt\n#\n# Author:\n# klamping\n\nsteves = [\n \"http://www.ivygateblog.com/wp-cont",
"end": 228,
"score": 0.9995625019073486,
"start": 220,
"tag": "USERNAME",
"value": "klamping"
},
{
"context": "\"\n]\n\nmodule.exports = (robot) ->\n robot.hear /\\b(steve holt)\\b/i, (msg) ->\n msg.send msg.random ste",
"end": 1504,
"score": 0.6705441474914551,
"start": 1501,
"tag": "NAME",
"value": "ste"
}
] | src/scripts/steveholt.coffee | contolini/hubot-scripts | 1,450 | # Description:
# When Steve Holt hears his name, Steve Holt makes his presence known
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# steve holt - Display an image of Steve Holt
#
# Author:
# klamping
steves = [
"http://www.ivygateblog.com/wp-content/uploads/2011/04/steve-holt.jpg",
"http://blog.zap2it.com/frominsidethebox/arrested-development-will-arnett-justin-grant-wade-gob-steve-holt-season-3.jpg",
"http://images2.fanpop.com/images/photos/3000000/Notapusy-steve-holt-3033209-1280-720.jpg",
"http://images3.wikia.nocookie.net/__cb20121216182908/arresteddevelopment/images/c/c1/2x05_Sad_Sack_(17).png",
"http://b68389.medialib.glogster.com/media/e3d4598233559b40af63f4b3ef93c66d57554b6b2c44e8ab094408d4af9c23bd/steve-holt-7.jpg",
"http://i.imgur.com/mqDYUQV.png",
"http://images1.wikia.nocookie.net/__cb20130601231816/arresteddevelopment/images/5/5d/4x07_Colony_Collapse_%28112%29.png",
"http://images3.wikia.nocookie.net/__cb20130129170211/arresteddevelopment/images/thumb/5/5e/2x14_The_Immaculate_Election_%2877%29.png/200px-2x14_The_Immaculate_Election_%2877%29.png",
"http://images1.wikia.nocookie.net/__cb20121216182908/arresteddevelopment/images/thumb/6/69/2x05_Sad_Sack_%2815%29.png/200px-2x05_Sad_Sack_%2815%29.png",
"http://images2.wikia.nocookie.net/__cb20120123070042/arresteddevelopment/images/thumb/2/2b/1x03_Bringing_Up_Buster_%2811%29.png/200px-1x03_Bringing_Up_Buster_%2811%29.png"
]
module.exports = (robot) ->
robot.hear /\b(steve holt)\b/i, (msg) ->
msg.send msg.random steves | 172940 | # Description:
# When <NAME> hears his name, <NAME> makes his presence known
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# steve holt - Display an image of <NAME>
#
# Author:
# klamping
steves = [
"http://www.ivygateblog.com/wp-content/uploads/2011/04/steve-holt.jpg",
"http://blog.zap2it.com/frominsidethebox/arrested-development-will-arnett-justin-grant-wade-gob-steve-holt-season-3.jpg",
"http://images2.fanpop.com/images/photos/3000000/Notapusy-steve-holt-3033209-1280-720.jpg",
"http://images3.wikia.nocookie.net/__cb20121216182908/arresteddevelopment/images/c/c1/2x05_Sad_Sack_(17).png",
"http://b68389.medialib.glogster.com/media/e3d4598233559b40af63f4b3ef93c66d57554b6b2c44e8ab094408d4af9c23bd/steve-holt-7.jpg",
"http://i.imgur.com/mqDYUQV.png",
"http://images1.wikia.nocookie.net/__cb20130601231816/arresteddevelopment/images/5/5d/4x07_Colony_Collapse_%28112%29.png",
"http://images3.wikia.nocookie.net/__cb20130129170211/arresteddevelopment/images/thumb/5/5e/2x14_The_Immaculate_Election_%2877%29.png/200px-2x14_The_Immaculate_Election_%2877%29.png",
"http://images1.wikia.nocookie.net/__cb20121216182908/arresteddevelopment/images/thumb/6/69/2x05_Sad_Sack_%2815%29.png/200px-2x05_Sad_Sack_%2815%29.png",
"http://images2.wikia.nocookie.net/__cb20120123070042/arresteddevelopment/images/thumb/2/2b/1x03_Bringing_Up_Buster_%2811%29.png/200px-1x03_Bringing_Up_Buster_%2811%29.png"
]
module.exports = (robot) ->
robot.hear /\b(<NAME>ve holt)\b/i, (msg) ->
msg.send msg.random steves | true | # Description:
# When PI:NAME:<NAME>END_PI hears his name, PI:NAME:<NAME>END_PI makes his presence known
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# steve holt - Display an image of PI:NAME:<NAME>END_PI
#
# Author:
# klamping
steves = [
"http://www.ivygateblog.com/wp-content/uploads/2011/04/steve-holt.jpg",
"http://blog.zap2it.com/frominsidethebox/arrested-development-will-arnett-justin-grant-wade-gob-steve-holt-season-3.jpg",
"http://images2.fanpop.com/images/photos/3000000/Notapusy-steve-holt-3033209-1280-720.jpg",
"http://images3.wikia.nocookie.net/__cb20121216182908/arresteddevelopment/images/c/c1/2x05_Sad_Sack_(17).png",
"http://b68389.medialib.glogster.com/media/e3d4598233559b40af63f4b3ef93c66d57554b6b2c44e8ab094408d4af9c23bd/steve-holt-7.jpg",
"http://i.imgur.com/mqDYUQV.png",
"http://images1.wikia.nocookie.net/__cb20130601231816/arresteddevelopment/images/5/5d/4x07_Colony_Collapse_%28112%29.png",
"http://images3.wikia.nocookie.net/__cb20130129170211/arresteddevelopment/images/thumb/5/5e/2x14_The_Immaculate_Election_%2877%29.png/200px-2x14_The_Immaculate_Election_%2877%29.png",
"http://images1.wikia.nocookie.net/__cb20121216182908/arresteddevelopment/images/thumb/6/69/2x05_Sad_Sack_%2815%29.png/200px-2x05_Sad_Sack_%2815%29.png",
"http://images2.wikia.nocookie.net/__cb20120123070042/arresteddevelopment/images/thumb/2/2b/1x03_Bringing_Up_Buster_%2811%29.png/200px-1x03_Bringing_Up_Buster_%2811%29.png"
]
module.exports = (robot) ->
robot.hear /\b(PI:NAME:<NAME>END_PIve holt)\b/i, (msg) ->
msg.send msg.random steves |
[
{
"context": "tring} Password to login to the api. Defaults to 'guest'\n #\n constructor: (options = {}) ->\n ",
"end": 961,
"score": 0.987116277217865,
"start": 956,
"tag": "PASSWORD",
"value": "guest"
},
{
"context": ": 5672\n vhost: '/'\n login: 'guest'\n password: 'guest'\n @options =",
"end": 1124,
"score": 0.6288982033729553,
"start": 1119,
"tag": "USERNAME",
"value": "guest"
},
{
"context": " login: 'guest'\n password: 'guest'\n @options = _.extend {}, defaults, option",
"end": 1154,
"score": 0.9994534254074097,
"start": 1149,
"tag": "PASSWORD",
"value": "guest"
}
] | src/Client.coffee | topliceanu/rabbitmq-client | 1 | _ = require 'underscore'
# Base class for Rabbitmq client implementations.
# Acts as an abstract class documenting the api for all implementations.
#
# @abstract This class should not be instantiated directly.
#
class Client
# {Object} holding options for the specific rabbitmq connection.
options: {}
# Builds an client for rabbitmq server. All available options are detailed
# here, but one should only pass only the needed options for the specific
# implementations.
#
# @param {Object} options
# @option host {String} Ip of machine where rabbitmq server is installed. Defaults to 'localhost'.
# @option port {Number} Port where the rabbitmq server is listening. Defaults to 5672 for amqp.
# @option vhost {String} Rabbitmq virtual host. Defaults to '/'.
# @option login {String} Username to login to the api. Defaults to 'guest'
# @option password {String} Password to login to the api. Defaults to 'guest'
#
constructor: (options = {}) ->
defaults =
host: 'localhost'
port: 5672
vhost: '/'
login: 'guest'
password: 'guest'
@options = _.extend {}, defaults, options
# Publishes a message to the specified queue.
#
# @abstract
# @param queueName {String} The queue will be created if it does not exist.
# @param data {Mixed} Message payload is passed through JSON.stringify.
# @param options {Object} Options specific to the protocol implementation.
# @return {Q.Promise} Resolves when the message is published.
#
publish: (queueName, data, options = {}) ->
# Subscribes to a queue. Whenever a new message is available the
# provided callback is executed with that message.
# Make sure you ack() to consume the message.
#
# @abstract
# @param queueName {String} The queue will be created if it does not exist.
# @param callback {Function} function (error, message, ack) {...}
# @param options {Object} Options specific to the protocol implementation.
#
subscribe: (queueName, callback, options = {}) ->
# Log method allows users to hook custom logging infrastructure to easter.
#
# @param level {String} Can be anything, usually info, warn, debug, error.
# @param message {String} Actuall log message.
# @param context {Array<Object>} various objects relevant to message.
log: (level, message, context...) ->
console.log level, message, context...
# Public API.
module.exports = Client
| 144299 | _ = require 'underscore'
# Base class for Rabbitmq client implementations.
# Acts as an abstract class documenting the api for all implementations.
#
# @abstract This class should not be instantiated directly.
#
class Client
# {Object} holding options for the specific rabbitmq connection.
options: {}
# Builds an client for rabbitmq server. All available options are detailed
# here, but one should only pass only the needed options for the specific
# implementations.
#
# @param {Object} options
# @option host {String} Ip of machine where rabbitmq server is installed. Defaults to 'localhost'.
# @option port {Number} Port where the rabbitmq server is listening. Defaults to 5672 for amqp.
# @option vhost {String} Rabbitmq virtual host. Defaults to '/'.
# @option login {String} Username to login to the api. Defaults to 'guest'
# @option password {String} Password to login to the api. Defaults to '<PASSWORD>'
#
constructor: (options = {}) ->
defaults =
host: 'localhost'
port: 5672
vhost: '/'
login: 'guest'
password: '<PASSWORD>'
@options = _.extend {}, defaults, options
# Publishes a message to the specified queue.
#
# @abstract
# @param queueName {String} The queue will be created if it does not exist.
# @param data {Mixed} Message payload is passed through JSON.stringify.
# @param options {Object} Options specific to the protocol implementation.
# @return {Q.Promise} Resolves when the message is published.
#
publish: (queueName, data, options = {}) ->
# Subscribes to a queue. Whenever a new message is available the
# provided callback is executed with that message.
# Make sure you ack() to consume the message.
#
# @abstract
# @param queueName {String} The queue will be created if it does not exist.
# @param callback {Function} function (error, message, ack) {...}
# @param options {Object} Options specific to the protocol implementation.
#
subscribe: (queueName, callback, options = {}) ->
# Log method allows users to hook custom logging infrastructure to easter.
#
# @param level {String} Can be anything, usually info, warn, debug, error.
# @param message {String} Actuall log message.
# @param context {Array<Object>} various objects relevant to message.
log: (level, message, context...) ->
console.log level, message, context...
# Public API.
module.exports = Client
| true | _ = require 'underscore'
# Base class for Rabbitmq client implementations.
# Acts as an abstract class documenting the api for all implementations.
#
# @abstract This class should not be instantiated directly.
#
class Client
# {Object} holding options for the specific rabbitmq connection.
options: {}
# Builds an client for rabbitmq server. All available options are detailed
# here, but one should only pass only the needed options for the specific
# implementations.
#
# @param {Object} options
# @option host {String} Ip of machine where rabbitmq server is installed. Defaults to 'localhost'.
# @option port {Number} Port where the rabbitmq server is listening. Defaults to 5672 for amqp.
# @option vhost {String} Rabbitmq virtual host. Defaults to '/'.
# @option login {String} Username to login to the api. Defaults to 'guest'
# @option password {String} Password to login to the api. Defaults to 'PI:PASSWORD:<PASSWORD>END_PI'
#
constructor: (options = {}) ->
defaults =
host: 'localhost'
port: 5672
vhost: '/'
login: 'guest'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
@options = _.extend {}, defaults, options
# Publishes a message to the specified queue.
#
# @abstract
# @param queueName {String} The queue will be created if it does not exist.
# @param data {Mixed} Message payload is passed through JSON.stringify.
# @param options {Object} Options specific to the protocol implementation.
# @return {Q.Promise} Resolves when the message is published.
#
publish: (queueName, data, options = {}) ->
# Subscribes to a queue. Whenever a new message is available the
# provided callback is executed with that message.
# Make sure you ack() to consume the message.
#
# @abstract
# @param queueName {String} The queue will be created if it does not exist.
# @param callback {Function} function (error, message, ack) {...}
# @param options {Object} Options specific to the protocol implementation.
#
subscribe: (queueName, callback, options = {}) ->
# Log method allows users to hook custom logging infrastructure to easter.
#
# @param level {String} Can be anything, usually info, warn, debug, error.
# @param message {String} Actuall log message.
# @param context {Array<Object>} various objects relevant to message.
log: (level, message, context...) ->
console.log level, message, context...
# Public API.
module.exports = Client
|
[
{
"context": "t\n params:\n owner: owner\n name: name\n\n ownerClasses = classNames {\n \"owner\": t",
"end": 1725,
"score": 0.5817363262176514,
"start": 1721,
"tag": "NAME",
"value": "name"
}
] | app/partials/collection-card.cjsx | alexbfree/Panoptes-Front-End | 0 | React = require 'react'
{Link} = require 'react-router'
apiClient = require 'panoptes-client/lib/api-client'
Translate = require 'react-translate-component'
classNames = require 'classnames'
FlexibleLink = React.createClass
displayName: 'FlexibleLink'
propTypes:
to: React.PropTypes.string.isRequired
skipOwner: React.PropTypes.bool
contextTypes:
geordi: React.PropTypes.object
isExternal: ->
@props.to.indexOf('http') > -1
render: ->
@logClick = @context.geordi?.makeHandler? 'profile-menu'
if @isExternal()
<a href={@props.to}>{@props.children}</a>
else
<Link
{...@props}
onClick={@logClick?.bind(this, @props.logText)}>{@props.children}</Link>
module.exports = React.createClass
displayName: 'CollectionCard'
propTypes:
collection: React.PropTypes.object.isRequired
imagePromise: React.PropTypes.object.isRequired
linkTo: React.PropTypes.string.isRequired
translationObjectName: React.PropTypes.string.isRequired
collectionOwner: ->
apiClient.type(@props.collection.links.owner.type).get(@props.collection.links.owner.id)
componentDidMount: ->
card = @refs.collectionCard
@props.imagePromise
.then (src) =>
card.style.backgroundImage = "url('#{src}')"
card.style.backgroundSize = "contain"
.catch =>
card.style.background = "url('/assets/simple-pattern.jpg') center center repeat"
render: ->
[owner, name] = @props.collection.slug.split('/')
dataText = "view-#{@props.translationObjectName?.toLowerCase().replace(/page$/,'').replace(/s?$/,'')}"
linkProps =
to: @props.linkTo
logText: dataText
params:
owner: owner
name: name
ownerClasses = classNames {
"owner": true
"owner-private": @props.collection.private
"owner-public": !@props.collection.private
}
<FlexibleLink {...linkProps}>
<div className="collection-card" ref="collectionCard">
<svg className="card-space-maker" viewBox="0 0 2 1" width="100%"></svg>
<div className="details">
<div className="name"><span>{@props.collection.display_name}</span></div>
{<div className="private"><i className="fa fa-lock"></i> Private</div> if @props.collection.private}
{if !@props.skipOwner
<div className={ownerClasses}>{@props.collection.links.owner.display_name}</div>}
{<div className="description">{@props.collection.description}</div> if @props.collection.description?}
</div>
</div>
</FlexibleLink>
| 134717 | React = require 'react'
{Link} = require 'react-router'
apiClient = require 'panoptes-client/lib/api-client'
Translate = require 'react-translate-component'
classNames = require 'classnames'
FlexibleLink = React.createClass
displayName: 'FlexibleLink'
propTypes:
to: React.PropTypes.string.isRequired
skipOwner: React.PropTypes.bool
contextTypes:
geordi: React.PropTypes.object
isExternal: ->
@props.to.indexOf('http') > -1
render: ->
@logClick = @context.geordi?.makeHandler? 'profile-menu'
if @isExternal()
<a href={@props.to}>{@props.children}</a>
else
<Link
{...@props}
onClick={@logClick?.bind(this, @props.logText)}>{@props.children}</Link>
module.exports = React.createClass
displayName: 'CollectionCard'
propTypes:
collection: React.PropTypes.object.isRequired
imagePromise: React.PropTypes.object.isRequired
linkTo: React.PropTypes.string.isRequired
translationObjectName: React.PropTypes.string.isRequired
collectionOwner: ->
apiClient.type(@props.collection.links.owner.type).get(@props.collection.links.owner.id)
componentDidMount: ->
card = @refs.collectionCard
@props.imagePromise
.then (src) =>
card.style.backgroundImage = "url('#{src}')"
card.style.backgroundSize = "contain"
.catch =>
card.style.background = "url('/assets/simple-pattern.jpg') center center repeat"
render: ->
[owner, name] = @props.collection.slug.split('/')
dataText = "view-#{@props.translationObjectName?.toLowerCase().replace(/page$/,'').replace(/s?$/,'')}"
linkProps =
to: @props.linkTo
logText: dataText
params:
owner: owner
name: <NAME>
ownerClasses = classNames {
"owner": true
"owner-private": @props.collection.private
"owner-public": !@props.collection.private
}
<FlexibleLink {...linkProps}>
<div className="collection-card" ref="collectionCard">
<svg className="card-space-maker" viewBox="0 0 2 1" width="100%"></svg>
<div className="details">
<div className="name"><span>{@props.collection.display_name}</span></div>
{<div className="private"><i className="fa fa-lock"></i> Private</div> if @props.collection.private}
{if !@props.skipOwner
<div className={ownerClasses}>{@props.collection.links.owner.display_name}</div>}
{<div className="description">{@props.collection.description}</div> if @props.collection.description?}
</div>
</div>
</FlexibleLink>
| true | React = require 'react'
{Link} = require 'react-router'
apiClient = require 'panoptes-client/lib/api-client'
Translate = require 'react-translate-component'
classNames = require 'classnames'
FlexibleLink = React.createClass
displayName: 'FlexibleLink'
propTypes:
to: React.PropTypes.string.isRequired
skipOwner: React.PropTypes.bool
contextTypes:
geordi: React.PropTypes.object
isExternal: ->
@props.to.indexOf('http') > -1
render: ->
@logClick = @context.geordi?.makeHandler? 'profile-menu'
if @isExternal()
<a href={@props.to}>{@props.children}</a>
else
<Link
{...@props}
onClick={@logClick?.bind(this, @props.logText)}>{@props.children}</Link>
module.exports = React.createClass
displayName: 'CollectionCard'
propTypes:
collection: React.PropTypes.object.isRequired
imagePromise: React.PropTypes.object.isRequired
linkTo: React.PropTypes.string.isRequired
translationObjectName: React.PropTypes.string.isRequired
collectionOwner: ->
apiClient.type(@props.collection.links.owner.type).get(@props.collection.links.owner.id)
componentDidMount: ->
card = @refs.collectionCard
@props.imagePromise
.then (src) =>
card.style.backgroundImage = "url('#{src}')"
card.style.backgroundSize = "contain"
.catch =>
card.style.background = "url('/assets/simple-pattern.jpg') center center repeat"
render: ->
[owner, name] = @props.collection.slug.split('/')
dataText = "view-#{@props.translationObjectName?.toLowerCase().replace(/page$/,'').replace(/s?$/,'')}"
linkProps =
to: @props.linkTo
logText: dataText
params:
owner: owner
name: PI:NAME:<NAME>END_PI
ownerClasses = classNames {
"owner": true
"owner-private": @props.collection.private
"owner-public": !@props.collection.private
}
<FlexibleLink {...linkProps}>
<div className="collection-card" ref="collectionCard">
<svg className="card-space-maker" viewBox="0 0 2 1" width="100%"></svg>
<div className="details">
<div className="name"><span>{@props.collection.display_name}</span></div>
{<div className="private"><i className="fa fa-lock"></i> Private</div> if @props.collection.private}
{if !@props.skipOwner
<div className={ownerClasses}>{@props.collection.links.owner.display_name}</div>}
{<div className="description">{@props.collection.description}</div> if @props.collection.description?}
</div>
</div>
</FlexibleLink>
|
[
{
"context": "anels\n\ndaysOfWeek = () ->\n\tchoices = {\n\t\tmonday: \"Lunes\",\n\t\ttuesday: \"Martes\",\n\t\twednesday: \"Miércoles\",\n",
"end": 280,
"score": 0.9593788385391235,
"start": 275,
"tag": "NAME",
"value": "Lunes"
},
{
"context": "() ->\n\tchoices = {\n\t\tmonday: \"Lunes\",\n\t\ttuesday: \"Martes\",\n\t\twednesday: \"Miércoles\",\n\t\tthursday: \"Jueves\",",
"end": 301,
"score": 0.9807434678077698,
"start": 295,
"tag": "NAME",
"value": "Martes"
},
{
"context": "nday: \"Lunes\",\n\t\ttuesday: \"Martes\",\n\t\twednesday: \"Miércoles\",\n\t\tthursday: \"Jueves\",\n\t\tfriday: \"Viernes\",\n\t\tsa",
"end": 327,
"score": 0.9623252153396606,
"start": 318,
"tag": "NAME",
"value": "Miércoles"
},
{
"context": " \"Martes\",\n\t\twednesday: \"Miércoles\",\n\t\tthursday: \"Jueves\",\n\t\tfriday: \"Viernes\",\n\t\tsaturday: \"Sábado\",",
"end": 344,
"score": 0.9000903367996216,
"start": 343,
"tag": "NAME",
"value": "J"
},
{
"context": "artes\",\n\t\twednesday: \"Miércoles\",\n\t\tthursday: \"Jueves\",\n\t\tfriday: \"Viernes\",\n\t\tsaturday: \"Sábado\",\n\t\tsu",
"end": 349,
"score": 0.7312024235725403,
"start": 346,
"tag": "NAME",
"value": "ves"
},
{
"context": "ay: \"Miércoles\",\n\t\tthursday: \"Jueves\",\n\t\tfriday: \"Viernes\",\n\t\tsaturday: \"Sábado\",\n\t\tsunday: \"Domingo\"\n\t}\n\n\t",
"end": 370,
"score": 0.7716946005821228,
"start": 363,
"tag": "NAME",
"value": "Viernes"
}
] | meteor-webapp/client/steps/days-of-week.coffee | alepulver/my-thesis | 0 | _ = lodash
create_handler_default = (choices, create_shape) ->
() ->
panels = Steps.createPanels choices, Steps.colors, Panels.DrawingNoOverlap, create_shape
layer = panels.shapes.layer
Widgets.addBorder layer
panels
daysOfWeek = () ->
choices = {
monday: "Lunes",
tuesday: "Martes",
wednesday: "Miércoles",
thursday: "Jueves",
friday: "Viernes",
saturday: "Sábado",
sunday: "Domingo"
}
create_shape = (item, panel) ->
shape = new Widgets.FilledRect()
interactive_shape = new Widgets.SquareBoundedIS(shape, item, panel)
interactive_shape
panels = Steps.createPanels(choices, Steps.colors, Panels.DrawingNoOverlap, create_shape)
new Steps.HandleControlFlow("days_of_week", panels)
@Steps ?= {}
_.merge(@Steps, {
daysOfWeek: daysOfWeek
}) | 147156 | _ = lodash
create_handler_default = (choices, create_shape) ->
() ->
panels = Steps.createPanels choices, Steps.colors, Panels.DrawingNoOverlap, create_shape
layer = panels.shapes.layer
Widgets.addBorder layer
panels
daysOfWeek = () ->
choices = {
monday: "<NAME>",
tuesday: "<NAME>",
wednesday: "<NAME>",
thursday: "<NAME>ue<NAME>",
friday: "<NAME>",
saturday: "Sábado",
sunday: "Domingo"
}
create_shape = (item, panel) ->
shape = new Widgets.FilledRect()
interactive_shape = new Widgets.SquareBoundedIS(shape, item, panel)
interactive_shape
panels = Steps.createPanels(choices, Steps.colors, Panels.DrawingNoOverlap, create_shape)
new Steps.HandleControlFlow("days_of_week", panels)
@Steps ?= {}
_.merge(@Steps, {
daysOfWeek: daysOfWeek
}) | true | _ = lodash
create_handler_default = (choices, create_shape) ->
() ->
panels = Steps.createPanels choices, Steps.colors, Panels.DrawingNoOverlap, create_shape
layer = panels.shapes.layer
Widgets.addBorder layer
panels
daysOfWeek = () ->
choices = {
monday: "PI:NAME:<NAME>END_PI",
tuesday: "PI:NAME:<NAME>END_PI",
wednesday: "PI:NAME:<NAME>END_PI",
thursday: "PI:NAME:<NAME>END_PIuePI:NAME:<NAME>END_PI",
friday: "PI:NAME:<NAME>END_PI",
saturday: "Sábado",
sunday: "Domingo"
}
create_shape = (item, panel) ->
shape = new Widgets.FilledRect()
interactive_shape = new Widgets.SquareBoundedIS(shape, item, panel)
interactive_shape
panels = Steps.createPanels(choices, Steps.colors, Panels.DrawingNoOverlap, create_shape)
new Steps.HandleControlFlow("days_of_week", panels)
@Steps ?= {}
_.merge(@Steps, {
daysOfWeek: daysOfWeek
}) |
[
{
"context": " Admin.count\n name: req.body.name\n password: req.body.password\n , (err, count)->\n if count > 0\n res.red",
"end": 314,
"score": 0.9653481245040894,
"start": 297,
"tag": "PASSWORD",
"value": "req.body.password"
}
] | zblog/coffee/server/routes/admin.coffee | zoei/zblog | 0 | express = require 'express'
router = express.Router()
mongoose = require 'mongoose'
Admin = mongoose.model 'Admin'
Blog = mongoose.model 'Blog'
router.get '/', (req, res, next)->
res.render 'login'
router.post '/verify', (req, res, next)->
Admin.count
name: req.body.name
password: req.body.password
, (err, count)->
if count > 0
res.redirect '/admin/console'
else
res.render 'login', {message: 'NG'}
router.get '/console', (req, res, next)->
res.render 'console'
router.get '/blogs', (req, res, next)->
res.render 'console/blogs',
blogs: Blog.find()
router.get '/blog/delete/:id', (req, res, next)->
Blog.findById req.params.id, (err, blog)=>
if err
res.send JSON.stringify
status: 'NG'
message: 'can not find blog by ' + req.params.id
else
blog.remove (err, blog)->
if err
res.send JSON.stringify
status: 'NG'
message: 'can not find blog by ' + req.params.id
else
res.send JSON.stringify
status: 'OK'
message: 'delete success'
module.exports = router | 39700 | express = require 'express'
router = express.Router()
mongoose = require 'mongoose'
Admin = mongoose.model 'Admin'
Blog = mongoose.model 'Blog'
router.get '/', (req, res, next)->
res.render 'login'
router.post '/verify', (req, res, next)->
Admin.count
name: req.body.name
password: <PASSWORD>
, (err, count)->
if count > 0
res.redirect '/admin/console'
else
res.render 'login', {message: 'NG'}
router.get '/console', (req, res, next)->
res.render 'console'
router.get '/blogs', (req, res, next)->
res.render 'console/blogs',
blogs: Blog.find()
router.get '/blog/delete/:id', (req, res, next)->
Blog.findById req.params.id, (err, blog)=>
if err
res.send JSON.stringify
status: 'NG'
message: 'can not find blog by ' + req.params.id
else
blog.remove (err, blog)->
if err
res.send JSON.stringify
status: 'NG'
message: 'can not find blog by ' + req.params.id
else
res.send JSON.stringify
status: 'OK'
message: 'delete success'
module.exports = router | true | express = require 'express'
router = express.Router()
mongoose = require 'mongoose'
Admin = mongoose.model 'Admin'
Blog = mongoose.model 'Blog'
router.get '/', (req, res, next)->
res.render 'login'
router.post '/verify', (req, res, next)->
Admin.count
name: req.body.name
password: PI:PASSWORD:<PASSWORD>END_PI
, (err, count)->
if count > 0
res.redirect '/admin/console'
else
res.render 'login', {message: 'NG'}
router.get '/console', (req, res, next)->
res.render 'console'
router.get '/blogs', (req, res, next)->
res.render 'console/blogs',
blogs: Blog.find()
router.get '/blog/delete/:id', (req, res, next)->
Blog.findById req.params.id, (err, blog)=>
if err
res.send JSON.stringify
status: 'NG'
message: 'can not find blog by ' + req.params.id
else
blog.remove (err, blog)->
if err
res.send JSON.stringify
status: 'NG'
message: 'can not find blog by ' + req.params.id
else
res.send JSON.stringify
status: 'OK'
message: 'delete success'
module.exports = router |
[
{
"context": "rd submitted', ->\n @scope.spending_password = \"password\"\n @scope.submitForm()\n @deferred.resolve()\n",
"end": 603,
"score": 0.9994124174118042,
"start": 595,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "ock rejected', ->\n @scope.spending_password = \"password\"\n @scope.submitForm()\n @deferred.reject 'wr",
"end": 873,
"score": 0.999519944190979,
"start": 865,
"tag": "PASSWORD",
"value": "password"
}
] | spec/controllers/unlockwallet_controller_spec.coffee | AlexChien/web_wallet | 0 | describe "controller: UnlockWalletController", ->
beforeEach -> module("app")
beforeEach inject ($q, $controller, @$rootScope, @$state, Wallet) ->
@scope = @$rootScope.$new()
@deferred = $q.defer()
@wallet = spyOn(Wallet, 'wallet_unlock').andReturn(@deferred.promise)
@controller = $controller('UnlockWalletController', {$scope: @scope, @wallet})
spyOn(@$rootScope, 'history_back')
spyOn(@$rootScope, 'showLoadingIndicator')
spyOn(Wallet, 'check_wallet_status')
it 'should return user back if correct password submitted', ->
@scope.spending_password = "password"
@scope.submitForm()
@deferred.resolve()
@$rootScope.$apply()
expect(@scope.wrongPass).toBeFalsy
expect(@$rootScope.history_back).toHaveBeenCalled()
it 'should set wrongPass if wallet_unlock rejected', ->
@scope.spending_password = "password"
@scope.submitForm()
@deferred.reject 'wrong password'
@$rootScope.$apply()
expect(@scope.wrongPass).toBeTruthy
| 44724 | describe "controller: UnlockWalletController", ->
beforeEach -> module("app")
beforeEach inject ($q, $controller, @$rootScope, @$state, Wallet) ->
@scope = @$rootScope.$new()
@deferred = $q.defer()
@wallet = spyOn(Wallet, 'wallet_unlock').andReturn(@deferred.promise)
@controller = $controller('UnlockWalletController', {$scope: @scope, @wallet})
spyOn(@$rootScope, 'history_back')
spyOn(@$rootScope, 'showLoadingIndicator')
spyOn(Wallet, 'check_wallet_status')
it 'should return user back if correct password submitted', ->
@scope.spending_password = "<PASSWORD>"
@scope.submitForm()
@deferred.resolve()
@$rootScope.$apply()
expect(@scope.wrongPass).toBeFalsy
expect(@$rootScope.history_back).toHaveBeenCalled()
it 'should set wrongPass if wallet_unlock rejected', ->
@scope.spending_password = "<PASSWORD>"
@scope.submitForm()
@deferred.reject 'wrong password'
@$rootScope.$apply()
expect(@scope.wrongPass).toBeTruthy
| true | describe "controller: UnlockWalletController", ->
beforeEach -> module("app")
beforeEach inject ($q, $controller, @$rootScope, @$state, Wallet) ->
@scope = @$rootScope.$new()
@deferred = $q.defer()
@wallet = spyOn(Wallet, 'wallet_unlock').andReturn(@deferred.promise)
@controller = $controller('UnlockWalletController', {$scope: @scope, @wallet})
spyOn(@$rootScope, 'history_back')
spyOn(@$rootScope, 'showLoadingIndicator')
spyOn(Wallet, 'check_wallet_status')
it 'should return user back if correct password submitted', ->
@scope.spending_password = "PI:PASSWORD:<PASSWORD>END_PI"
@scope.submitForm()
@deferred.resolve()
@$rootScope.$apply()
expect(@scope.wrongPass).toBeFalsy
expect(@$rootScope.history_back).toHaveBeenCalled()
it 'should set wrongPass if wallet_unlock rejected', ->
@scope.spending_password = "PI:PASSWORD:<PASSWORD>END_PI"
@scope.submitForm()
@deferred.reject 'wrong password'
@$rootScope.$apply()
expect(@scope.wrongPass).toBeTruthy
|
[
{
"context": "s\\xa0]*Samuel))|(?:(?:I(?:lk|\\.)|[iİı]lk)[\\s\\xa0]*Samuel|1(?:\\.[\\s\\xa0]*|[\\s\\xa0]*)?Sa|I[\\s\\xa0]*Samuel|Bi",
"end": 8034,
"score": 0.9350614547729492,
"start": 8028,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "0]*Samuel|1(?:\\.[\\s\\xa0]*|[\\s\\xa0]*)?Sa|I[\\s\\xa0]*Samuel|Bir(?:inci)?[\\s\\xa0]*Samuel)\n\t\t\t)(?:(?=[\\d\\s\\xa0.",
"end": 8081,
"score": 0.6913458108901978,
"start": 8075,
"tag": "NAME",
"value": "Samuel"
},
{
"context": "9\\[\\]/\"'\\*=~\\-\\u2013\\u2014])|$)///gi\n\t,\n\t\tosis: [\"John\"]\n\t\tregexp: ///(^|#{bcv_parser::regexps.pre_book}",
"end": 18832,
"score": 0.7359717488288879,
"start": 18828,
"tag": "NAME",
"value": "John"
},
{
"context": "cil|ya[\\s\\xa0]*G[o\\xF6]re[\\s\\xa0]*[Iİı]ncil)))?)?|John)|(?:Yuhanna(?:['’](?:(?:n(?:[Iuİı]n[\\s\\xa0]*i|in[",
"end": 19211,
"score": 0.9996047616004944,
"start": 19207,
"tag": "NAME",
"value": "John"
},
{
"context": "\\xa0]*G[o\\xF6]re[\\s\\xa0]*[Iİı]ncil)))?)?|John)|(?:Yuhanna(?:['’](?:(?:n(?:[Iuİı]n[\\s\\xa0]*i|in[\\s\\xa0]*[Iiİ",
"end": 19223,
"score": 0.9997034668922424,
"start": 19216,
"tag": "NAME",
"value": "Yuhanna"
}
] | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/tr/regexps.coffee | saiba-mais/bible-lessons | 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]
| ba[şs]l[İIiı]k (?! [a-z] ) #could be followed by a number
| baplar | ayeti | ayet | bap | ile | a\. | bp | vs | vd | ve
| [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* ba[şs]l[İIiı]k
| \d \W* (?:vs|vd) (?: [\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 = "(?:1|I|Bir|Birinci|[İIiı]lk)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:2|II|[İIiı]ki|[İIiı]kinci)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:3|III|[ÜU][çc]|[ÜU][çc][üu]nc[üu])\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|ve|ile)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|ile)"
# 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: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Te(?:sn[Iİı]ye|kv[Iİı]n)|Gen|Yar(?:at[Iİı]l[Iİı][sş])?)|(?:Yarat(?:il[Iiİı][sş]|[Iİı]li[sş])|Te(?:sniye|kvin))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M[Iİı]s[Iİı]r(?:['’]dan[\s\xa0]*[C\xC7][Iİı]k[Iİı][sş]|dan[\s\xa0]*[C\xC7][Iİı]k[Iİı][sş])|[C\xC7][Iİı]k|Exod)|(?:M(?:[Iİı]s(?:[Iİı]r(?:['’]dan[\s\xa0]*[C\xC7](?:ik[Iiİı][sş]|[Iİı]ki[sş])|dan[\s\xa0]*[C\xC7](?:ik[Iiİı][sş]|[Iİı]ki[sş]))|ir(?:['’]dan[\s\xa0]*[C\xC7][Iiİı]|dan[\s\xa0]*[C\xC7][Iiİı])k[Iiİı][sş])|is[Iiİı]r(?:['’]dan[\s\xa0]*[C\xC7][Iiİı]|dan[\s\xa0]*[C\xC7][Iiİı])k[Iiİı][sş])|[C\xC7]ik[Iiİı][sş]|[C\xC7]ik|[C\xC7][Iİı]k[Iiİı][sş])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*ve[\s\xa0]*Ejderha)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Lev(?:[Iiİı]l[Iiİı]ler)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[C\xC7][o\xF6]lde[\s\xa0]*Say[Iİı]m|Say(?:[Iİı]lar)?|Num)|(?:[C\xC7][o\xF6]lde[\s\xa0]*Sayim|Sayilar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ir(?:ak)?|[Iİı]rak))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[Iiİı]lgelik|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:A[gğ][Iiİı](?:tlar)?|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yeremya(?:['’]n[Iiİı]|n[Iiİı])n[\s\xa0]*Mektubu|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Va(?:h(?:[Iiİı]y)?)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mana[sş][sş]e(?:['’]n[Iİı]n[\s\xa0]*Duas[Iİı]|n[Iİı]n[\s\xa0]*Duas[Iİı])|PrMan)|(?:Mana[sş][sş]e(?:['’]n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)|n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yas(?:a(?:['’]n[Iİı]n[\s\xa0]*Tekrar[Iİı]|n[Iİı]n[\s\xa0]*Tekrar[Iİı]))?|Deut)|(?:Yasa(?:['’]n(?:in[\s\xa0]*Tekrar[Iiİı]|[Iİı]n[\s\xa0]*Tekrari)|n(?:in[\s\xa0]*Tekrar[Iiİı]|[Iİı]n[\s\xa0]*Tekrari)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Y(?:e[sş]|[sş])u|Josh)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hak(?:[Iiİı]mler)?|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ruth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[iİı]lk|1\.|I(?:lk|\.))[\s\xa0]*Esdras|[1I][\s\xa0]*Esdras|1Esd|Bir(?:inci)?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Esdras|Esd|\.[\s\xa0]*Esdras)|[iİı]ki(?:nci)?[\s\xa0]*Esdras|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Y(?:e[sş]ay|[sş])|Is)a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Samuel|Sam|\.[\s\xa0]*Samuel))|(?:[iİı]ki(?:nci)?[\s\xa0]*Samuel|2(?:\.[\s\xa0]*|[\s\xa0]*)?Sa|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Samuel|Sam|\.[\s\xa0]*Samuel))|(?:(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Samuel|1(?:\.[\s\xa0]*|[\s\xa0]*)?Sa|I[\s\xa0]*Samuel|Bir(?:inci)?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2\.?[\s\xa0]*Krallar)|(?:[iİı]ki(?:nci)?[\s\xa0]*Krallar|2(?:K(?:gs|r)|\.?[\s\xa0]*Kr)|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Krallar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1\.?[\s\xa0]*Krallar)|(?:1(?:K(?:gs|r)|\.?[\s\xa0]*Kr)|I[\s\xa0]*Krallar|(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Krallar|Bir(?:inci)?[\s\xa0]*Krallar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[İı]ki(?:nci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])hler|2(?:\.?[\s\xa0]*Tar[Iİı]hler|(?:\.?[\s\xa0]*)?Ta|Chr)|I(?:ki(?:nci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])|I(?:\.[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı]))hler)|(?:(?:(?:(?:II|2)\.|II|2|Iki(?:nci)?|[İı]ki(?:nci)?)[\s\xa0]*Tari|iki(?:nci[\s\xa0]*Tar[Iiİı]|[\s\xa0]*Tar[Iiİı]))hler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Tar[Iİı]hler|(?:\.?[\s\xa0]*)?Ta|Chr)|I[\s\xa0]*Tar[Iİı]hler|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Tar[Iİı]hler|Bir(?:inci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])hler)|(?:(?:(?:I(?:lk|\.)|[İı]lk|1\.)[\s\xa0]*Tari|ilk[\s\xa0]*Tar[Iiİı]|[1I][\s\xa0]*Tari|Bir(?:inci)?[\s\xa0]*Tari)hler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ezra?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:emya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:rek[c\xE7]e[\s\xa0]*Ester|kEsth)|Yunanca[\s\xa0]*Ester)
)(?:(?=[\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})(
(?:Ey[u\xFC]p?|Job)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mez(?:mur(?:lar)?)?|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarya(?:['’]n[Iİı]n[\s\xa0]*Duas[Iİı]|n[Iİı]n[\s\xa0]*Duas[Iİı])|PrAzar)|(?:Azarya(?:['’]n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)|n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S[u\xFC]leyman(?:['’][Iİı]n[\s\xa0]*(?:[O\xD6]zdey[Iİı][sş]ler[Iİı]|Meseller[Iİı])|[Iİı]n[\s\xa0]*(?:[O\xD6]zdey[Iİı][sş]ler[Iİı]|Meseller[Iİı]))|[O\xD6]zd|Prov|Meseller)|(?:S[u\xFC]leyman(?:['’](?:[Iİı]n[\s\xa0]*(?:[O\xD6]zdey(?:i[sş]ler[Iiİı]|[Iİı][sş]leri)|Meselleri)|in[\s\xa0]*(?:[O\xD6]zdey[Iiİı][sş]ler[Iiİı]|Meseller[Iiİı]))|[Iİı]n[\s\xa0]*(?:[O\xD6]zdey(?:i[sş]ler[Iiİı]|[Iİı][sş]leri)|Meselleri)|in[\s\xa0]*(?:[O\xD6]zdey[Iiİı][sş]ler[Iiİı]|Meseller[Iiİı])))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Va(?:[Iiİı]z|[Iiİı])|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[U\xDC][c\xE7][\s\xa0]*Gen[c\xE7][\s\xa0]*Adam[Iİı]n[\s\xa0]*Ezg[Iİı]s[Iİı]|SgThree)|(?:[U\xDC][c\xE7][\s\xa0]*Gen[c\xE7][\s\xa0]*Adam(?:[Iİı]n[\s\xa0]*Ezgis[Iiİı]|[Iİı]n[\s\xa0]*Ezg[Iİı]si|in[\s\xa0]*Ezg[Iiİı]s[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ezg(?:[Iİı]ler[\s\xa0]*Ezg[Iİı]s[Iİı])?|Song)|(?:Ezg(?:[Iİı]ler[\s\xa0]*Ezgis[Iiİı]|[Iİı]ler[\s\xa0]*Ezg[Iİı]si|iler[\s\xa0]*Ezg[Iiİı]s[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yer(?:emya)?|Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hez(?:ek[Iiİı]el)?|Ezek)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:[Iiİı]el)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ho(?:s(?:ea)?|ş))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yoel?|Joel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Amos?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:O(?:va(?:dya)?|bad))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yun(?:us)?|Jonah)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:i(?:ka?|c)|[Iİı]ka?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Nah(?:um)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:akkuk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sef(?:anya)?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hag(?:ay)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ze(?:k(?:er[Iiİı]ya)?|ch))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:ak[Iiİı])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mat(?:t(?:a(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?)|(?:Matta(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:(?:[Iuİı]n[\s\xa0]*)?i|in[\s\xa0]*[Iiİı]|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı]))ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mar(?:k(?:os(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?)|(?:Markos(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:(?:[Iuİı]n[\s\xa0]*)?i|in[\s\xa0]*[Iiİı]|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı]))ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Luk(?:a(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil))|e)?)|(?:Luka(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:in(?:[\s\xa0]*[Iiİı]n)?|[Iuİı]n[\s\xa0]*in|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])n)cili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1\.?[\s\xa0]*Yuhanna)|(?:1(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|I[\s\xa0]*Yuhanna|(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Yuhanna|Bir(?:inci)?[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2\.?[\s\xa0]*Yuhanna)|(?:[iİı]ki(?:nci)?[\s\xa0]*Yuhanna|2(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3\.?[\s\xa0]*Yuhanna)|(?:3(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|III[\s\xa0]*Yuhanna|III\.[\s\xa0]*Yuhanna|[U\xDC][c\xE7](?:[u\xFC]nc[u\xFC])?[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["John"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yu(?:h(?:anna(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?|John)|(?:Yuhanna(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:in(?:[\s\xa0]*[Iiİı]n)?|[Iuİı]n[\s\xa0]*in|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])n)cili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:El[c\xE7](?:[Iİı]ler[Iİı]n[\s\xa0]*[Iİı][sş]ler[Iİı])?|Acts)|(?:El[c\xE7](?:[Iİı]ler[Iİı]n[\s\xa0]*i[sş]ler[Iiİı]|[Iİı]ler[Iİı]n[\s\xa0]*[Iİı][sş]leri|[Iİı]lerin[\s\xa0]*[Iiİı][sş]ler[Iiİı]|iler[Iiİı]n[\s\xa0]*[Iiİı][sş]ler[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Rom(?:al[Iiİı]lar)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ki(?:nci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))|I(?:\.[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)))r|[İı]ki(?:nci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))r|2(?:\.?[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:\.?[\s\xa0]*)?Ko|Cor))|(?:(?:(?:(?:II|2)\.[\s\xa0]*Kor[Iİı]|(?:II|2)[\s\xa0]*Kor[Iİı]|Iki(?:nci[\s\xa0]*Kor[Iİı]|[\s\xa0]*Kor[Iİı])|[İı]ki(?:nci[\s\xa0]*Kor[Iİı]|[\s\xa0]*Kor[Iİı]))ntlile|(?:(?:II|2)\.|II|2|Iki(?:nci)?|[İı]ki(?:nci)?)[\s\xa0]*Korint(?:l[Iiİı]le|oslula)|iki(?:nci[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)|[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)))r)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:\.?[\s\xa0]*)?Ko|Cor)|I[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|Bir(?:inci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))r)|(?:(?:[1I][\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|ilk[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)|(?:[1I]\.|Ilk|[İı]lk)[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|Bir(?:inci[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)))r)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Gal(?:atyal[Iiİı]lar)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:f(?:e(?:sl[Iiİı]ler)?)?|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:[Iİı]l[Iİı]p[Iİı]l[Iİı]ler|lp)|Phil)|(?:F(?:[Iİı]l(?:[Iİı]p(?:il[Iiİı]|[Iİı]li)|ip[Iiİı]l[Iiİı])|il[Iiİı]p[Iiİı]l[Iiİı])ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kol(?:osel[Iiİı]ler)?|Col)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ki(?:nci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])|I(?:\.[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı]))ler|[İı]ki(?:nci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])ler|2(?:\.?[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Thess|Se|\.?[\s\xa0]*Se))|(?:(?:iki(?:nci[\s\xa0]*Selan[Iiİı]|[\s\xa0]*Selan[Iiİı])kl[Iiİı]|(?:II|2)[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|(?:II|2)\.[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|Iki(?:nci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli))|[İı]ki(?:nci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)))ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Thess|Se|\.?[\s\xa0]*Se)|I[\s\xa0]*Selan[Iİı]kl[Iİı]ler|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Bir(?:inci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])ler)|(?:(?:[1I][\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|ilk[\s\xa0]*Selan[Iiİı]kl[Iiİı]|(?:[1I]\.|Ilk|[İı]lk)[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|Bir(?:inci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)))ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Tim)|(?:2(?:(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]|Ti)|[İı]ki(?:nci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|I(?:ki(?:nci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])|I(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]))moteos)|(?:(?:I(?:ki(?:nci)?|I\.?)|[İı]ki(?:nci)?)[\s\xa0]*Timoteos|2(?:\.?[\s\xa0]*Timoteos|\.?[\s\xa0]*Ti)|iki(?:nci[\s\xa0]*T[Iiİı]|[\s\xa0]*T[Iiİı])moteos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Tim)|(?:1(?:(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]|Ti)|I[\s\xa0]*T[Iİı]moteos|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*T[Iİı]moteos|Bir(?:inci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos)|(?:1(?:\.?[\s\xa0]*Timoteos|\.?[\s\xa0]*Ti)|ilk[\s\xa0]*T[Iiİı]moteos|I[\s\xa0]*Timoteos|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Timoteos|Bir(?:inci)?[\s\xa0]*Timoteos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T[Iiİı]t(?:us)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:[Iiİı]l[Iiİı]mon|lm)|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[Iİı]br(?:an[Iİı]ler)?|Heb)|(?:ibr(?:an[Iiİı]ler)?|[Iİı]braniler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yak(?:up)?|Jas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Petrus|Pet|\.[\s\xa0]*Petrus))|(?:[iİı]ki(?:nci)?[\s\xa0]*Petrus|2(?:\.[\s\xa0]*|[\s\xa0]*)?Pe|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Petrus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Petrus|Pet|\.[\s\xa0]*Petrus))|(?:(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Petrus|1(?:\.[\s\xa0]*|[\s\xa0]*)?Pe|I[\s\xa0]*Petrus|Bir(?:inci)?[\s\xa0]*Petrus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yah(?:uda)?|Jude)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob(?:[Iiİı]t)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Yud[Iiİı]|Jd)t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar(?:uk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Su(?:zanna|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Makabeler|Macc|\.[\s\xa0]*Makabeler)|[iİı]ki(?:nci)?[\s\xa0]*Makabeler|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Makabeler|3Macc|(?:III|3)\.[\s\xa0]*Makabeler|[U\xDC][c\xE7](?:[u\xFC]nc[u\xFC])?[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*Makabeler|4Macc|(?:IV|4)\.[\s\xa0]*Makabeler|D[o\xF6]r(?:d[u\xFC]nc[u\xFC]|t)[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[iİı]lk|1\.|I(?:lk|\.))[\s\xa0]*Makabeler|[1I][\s\xa0]*Makabeler|1Macc|Bir(?:inci)?[\s\xa0]*Makabeler)
)(?:(?=[\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"
| 209237 | 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]
| ba[şs]l[İIiı]k (?! [a-z] ) #could be followed by a number
| baplar | ayeti | ayet | bap | ile | a\. | bp | vs | vd | ve
| [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* ba[şs]l[İIiı]k
| \d \W* (?:vs|vd) (?: [\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 = "(?:1|I|Bir|Birinci|[İIiı]lk)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:2|II|[İIiı]ki|[İIiı]kinci)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:3|III|[ÜU][çc]|[ÜU][çc][üu]nc[üu])\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|ve|ile)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|ile)"
# 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: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Te(?:sn[Iİı]ye|kv[Iİı]n)|Gen|Yar(?:at[Iİı]l[Iİı][sş])?)|(?:Yarat(?:il[Iiİı][sş]|[Iİı]li[sş])|Te(?:sniye|kvin))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M[Iİı]s[Iİı]r(?:['’]dan[\s\xa0]*[C\xC7][Iİı]k[Iİı][sş]|dan[\s\xa0]*[C\xC7][Iİı]k[Iİı][sş])|[C\xC7][Iİı]k|Exod)|(?:M(?:[Iİı]s(?:[Iİı]r(?:['’]dan[\s\xa0]*[C\xC7](?:ik[Iiİı][sş]|[Iİı]ki[sş])|dan[\s\xa0]*[C\xC7](?:ik[Iiİı][sş]|[Iİı]ki[sş]))|ir(?:['’]dan[\s\xa0]*[C\xC7][Iiİı]|dan[\s\xa0]*[C\xC7][Iiİı])k[Iiİı][sş])|is[Iiİı]r(?:['’]dan[\s\xa0]*[C\xC7][Iiİı]|dan[\s\xa0]*[C\xC7][Iiİı])k[Iiİı][sş])|[C\xC7]ik[Iiİı][sş]|[C\xC7]ik|[C\xC7][Iİı]k[Iiİı][sş])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*ve[\s\xa0]*Ejderha)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Lev(?:[Iiİı]l[Iiİı]ler)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[C\xC7][o\xF6]lde[\s\xa0]*Say[Iİı]m|Say(?:[Iİı]lar)?|Num)|(?:[C\xC7][o\xF6]lde[\s\xa0]*Sayim|Sayilar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ir(?:ak)?|[Iİı]rak))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[Iiİı]lgelik|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:A[gğ][Iiİı](?:tlar)?|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yeremya(?:['’]n[Iiİı]|n[Iiİı])n[\s\xa0]*Mektubu|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Va(?:h(?:[Iiİı]y)?)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mana[sş][sş]e(?:['’]n[Iİı]n[\s\xa0]*Duas[Iİı]|n[Iİı]n[\s\xa0]*Duas[Iİı])|PrMan)|(?:Mana[sş][sş]e(?:['’]n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)|n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yas(?:a(?:['’]n[Iİı]n[\s\xa0]*Tekrar[Iİı]|n[Iİı]n[\s\xa0]*Tekrar[Iİı]))?|Deut)|(?:Yasa(?:['’]n(?:in[\s\xa0]*Tekrar[Iiİı]|[Iİı]n[\s\xa0]*Tekrari)|n(?:in[\s\xa0]*Tekrar[Iiİı]|[Iİı]n[\s\xa0]*Tekrari)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Y(?:e[sş]|[sş])u|Josh)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hak(?:[Iiİı]mler)?|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ruth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[iİı]lk|1\.|I(?:lk|\.))[\s\xa0]*Esdras|[1I][\s\xa0]*Esdras|1Esd|Bir(?:inci)?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Esdras|Esd|\.[\s\xa0]*Esdras)|[iİı]ki(?:nci)?[\s\xa0]*Esdras|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Y(?:e[sş]ay|[sş])|Is)a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Samuel|Sam|\.[\s\xa0]*Samuel))|(?:[iİı]ki(?:nci)?[\s\xa0]*Samuel|2(?:\.[\s\xa0]*|[\s\xa0]*)?Sa|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Samuel|Sam|\.[\s\xa0]*Samuel))|(?:(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*<NAME>|1(?:\.[\s\xa0]*|[\s\xa0]*)?Sa|I[\s\xa0]*<NAME>|Bir(?:inci)?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2\.?[\s\xa0]*Krallar)|(?:[iİı]ki(?:nci)?[\s\xa0]*Krallar|2(?:K(?:gs|r)|\.?[\s\xa0]*Kr)|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Krallar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1\.?[\s\xa0]*Krallar)|(?:1(?:K(?:gs|r)|\.?[\s\xa0]*Kr)|I[\s\xa0]*Krallar|(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Krallar|Bir(?:inci)?[\s\xa0]*Krallar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[İı]ki(?:nci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])hler|2(?:\.?[\s\xa0]*Tar[Iİı]hler|(?:\.?[\s\xa0]*)?Ta|Chr)|I(?:ki(?:nci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])|I(?:\.[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı]))hler)|(?:(?:(?:(?:II|2)\.|II|2|Iki(?:nci)?|[İı]ki(?:nci)?)[\s\xa0]*Tari|iki(?:nci[\s\xa0]*Tar[Iiİı]|[\s\xa0]*Tar[Iiİı]))hler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Tar[Iİı]hler|(?:\.?[\s\xa0]*)?Ta|Chr)|I[\s\xa0]*Tar[Iİı]hler|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Tar[Iİı]hler|Bir(?:inci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])hler)|(?:(?:(?:I(?:lk|\.)|[İı]lk|1\.)[\s\xa0]*Tari|ilk[\s\xa0]*Tar[Iiİı]|[1I][\s\xa0]*Tari|Bir(?:inci)?[\s\xa0]*Tari)hler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ezra?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:emya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:rek[c\xE7]e[\s\xa0]*Ester|kEsth)|Yunanca[\s\xa0]*Ester)
)(?:(?=[\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})(
(?:Ey[u\xFC]p?|Job)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mez(?:mur(?:lar)?)?|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarya(?:['’]n[Iİı]n[\s\xa0]*Duas[Iİı]|n[Iİı]n[\s\xa0]*Duas[Iİı])|PrAzar)|(?:Azarya(?:['’]n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)|n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S[u\xFC]leyman(?:['’][Iİı]n[\s\xa0]*(?:[O\xD6]zdey[Iİı][sş]ler[Iİı]|Meseller[Iİı])|[Iİı]n[\s\xa0]*(?:[O\xD6]zdey[Iİı][sş]ler[Iİı]|Meseller[Iİı]))|[O\xD6]zd|Prov|Meseller)|(?:S[u\xFC]leyman(?:['’](?:[Iİı]n[\s\xa0]*(?:[O\xD6]zdey(?:i[sş]ler[Iiİı]|[Iİı][sş]leri)|Meselleri)|in[\s\xa0]*(?:[O\xD6]zdey[Iiİı][sş]ler[Iiİı]|Meseller[Iiİı]))|[Iİı]n[\s\xa0]*(?:[O\xD6]zdey(?:i[sş]ler[Iiİı]|[Iİı][sş]leri)|Meselleri)|in[\s\xa0]*(?:[O\xD6]zdey[Iiİı][sş]ler[Iiİı]|Meseller[Iiİı])))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Va(?:[Iiİı]z|[Iiİı])|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[U\xDC][c\xE7][\s\xa0]*Gen[c\xE7][\s\xa0]*Adam[Iİı]n[\s\xa0]*Ezg[Iİı]s[Iİı]|SgThree)|(?:[U\xDC][c\xE7][\s\xa0]*Gen[c\xE7][\s\xa0]*Adam(?:[Iİı]n[\s\xa0]*Ezgis[Iiİı]|[Iİı]n[\s\xa0]*Ezg[Iİı]si|in[\s\xa0]*Ezg[Iiİı]s[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ezg(?:[Iİı]ler[\s\xa0]*Ezg[Iİı]s[Iİı])?|Song)|(?:Ezg(?:[Iİı]ler[\s\xa0]*Ezgis[Iiİı]|[Iİı]ler[\s\xa0]*Ezg[Iİı]si|iler[\s\xa0]*Ezg[Iiİı]s[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yer(?:emya)?|Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hez(?:ek[Iiİı]el)?|Ezek)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:[Iiİı]el)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ho(?:s(?:ea)?|ş))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yoel?|Joel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Amos?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:O(?:va(?:dya)?|bad))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yun(?:us)?|Jonah)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:i(?:ka?|c)|[Iİı]ka?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Nah(?:um)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:akkuk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sef(?:anya)?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hag(?:ay)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ze(?:k(?:er[Iiİı]ya)?|ch))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:ak[Iiİı])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mat(?:t(?:a(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?)|(?:Matta(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:(?:[Iuİı]n[\s\xa0]*)?i|in[\s\xa0]*[Iiİı]|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı]))ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mar(?:k(?:os(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?)|(?:Markos(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:(?:[Iuİı]n[\s\xa0]*)?i|in[\s\xa0]*[Iiİı]|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı]))ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Luk(?:a(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil))|e)?)|(?:Luka(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:in(?:[\s\xa0]*[Iiİı]n)?|[Iuİı]n[\s\xa0]*in|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])n)cili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1\.?[\s\xa0]*Yuhanna)|(?:1(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|I[\s\xa0]*Yuhanna|(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Yuhanna|Bir(?:inci)?[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2\.?[\s\xa0]*Yuhanna)|(?:[iİı]ki(?:nci)?[\s\xa0]*Yuhanna|2(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3\.?[\s\xa0]*Yuhanna)|(?:3(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|III[\s\xa0]*Yuhanna|III\.[\s\xa0]*Yuhanna|[U\xDC][c\xE7](?:[u\xFC]nc[u\xFC])?[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["<NAME>"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yu(?:h(?:anna(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?|<NAME>)|(?:<NAME>(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:in(?:[\s\xa0]*[Iiİı]n)?|[Iuİı]n[\s\xa0]*in|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])n)cili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:El[c\xE7](?:[Iİı]ler[Iİı]n[\s\xa0]*[Iİı][sş]ler[Iİı])?|Acts)|(?:El[c\xE7](?:[Iİı]ler[Iİı]n[\s\xa0]*i[sş]ler[Iiİı]|[Iİı]ler[Iİı]n[\s\xa0]*[Iİı][sş]leri|[Iİı]lerin[\s\xa0]*[Iiİı][sş]ler[Iiİı]|iler[Iiİı]n[\s\xa0]*[Iiİı][sş]ler[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Rom(?:al[Iiİı]lar)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ki(?:nci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))|I(?:\.[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)))r|[İı]ki(?:nci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))r|2(?:\.?[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:\.?[\s\xa0]*)?Ko|Cor))|(?:(?:(?:(?:II|2)\.[\s\xa0]*Kor[Iİı]|(?:II|2)[\s\xa0]*Kor[Iİı]|Iki(?:nci[\s\xa0]*Kor[Iİı]|[\s\xa0]*Kor[Iİı])|[İı]ki(?:nci[\s\xa0]*Kor[Iİı]|[\s\xa0]*Kor[Iİı]))ntlile|(?:(?:II|2)\.|II|2|Iki(?:nci)?|[İı]ki(?:nci)?)[\s\xa0]*Korint(?:l[Iiİı]le|oslula)|iki(?:nci[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)|[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)))r)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:\.?[\s\xa0]*)?Ko|Cor)|I[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|Bir(?:inci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))r)|(?:(?:[1I][\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|ilk[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)|(?:[1I]\.|Ilk|[İı]lk)[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|Bir(?:inci[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)))r)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Gal(?:atyal[Iiİı]lar)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:f(?:e(?:sl[Iiİı]ler)?)?|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:[Iİı]l[Iİı]p[Iİı]l[Iİı]ler|lp)|Phil)|(?:F(?:[Iİı]l(?:[Iİı]p(?:il[Iiİı]|[Iİı]li)|ip[Iiİı]l[Iiİı])|il[Iiİı]p[Iiİı]l[Iiİı])ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kol(?:osel[Iiİı]ler)?|Col)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ki(?:nci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])|I(?:\.[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı]))ler|[İı]ki(?:nci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])ler|2(?:\.?[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Thess|Se|\.?[\s\xa0]*Se))|(?:(?:iki(?:nci[\s\xa0]*Selan[Iiİı]|[\s\xa0]*Selan[Iiİı])kl[Iiİı]|(?:II|2)[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|(?:II|2)\.[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|Iki(?:nci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli))|[İı]ki(?:nci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)))ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Thess|Se|\.?[\s\xa0]*Se)|I[\s\xa0]*Selan[Iİı]kl[Iİı]ler|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Bir(?:inci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])ler)|(?:(?:[1I][\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|ilk[\s\xa0]*Selan[Iiİı]kl[Iiİı]|(?:[1I]\.|Ilk|[İı]lk)[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|Bir(?:inci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)))ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Tim)|(?:2(?:(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]|Ti)|[İı]ki(?:nci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|I(?:ki(?:nci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])|I(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]))moteos)|(?:(?:I(?:ki(?:nci)?|I\.?)|[İı]ki(?:nci)?)[\s\xa0]*Timoteos|2(?:\.?[\s\xa0]*Timoteos|\.?[\s\xa0]*Ti)|iki(?:nci[\s\xa0]*T[Iiİı]|[\s\xa0]*T[Iiİı])moteos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Tim)|(?:1(?:(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]|Ti)|I[\s\xa0]*T[Iİı]moteos|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*T[Iİı]moteos|Bir(?:inci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos)|(?:1(?:\.?[\s\xa0]*Timoteos|\.?[\s\xa0]*Ti)|ilk[\s\xa0]*T[Iiİı]moteos|I[\s\xa0]*Timoteos|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Timoteos|Bir(?:inci)?[\s\xa0]*Timoteos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T[Iiİı]t(?:us)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:[Iiİı]l[Iiİı]mon|lm)|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[Iİı]br(?:an[Iİı]ler)?|Heb)|(?:ibr(?:an[Iiİı]ler)?|[Iİı]braniler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yak(?:up)?|Jas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Petrus|Pet|\.[\s\xa0]*Petrus))|(?:[iİı]ki(?:nci)?[\s\xa0]*Petrus|2(?:\.[\s\xa0]*|[\s\xa0]*)?Pe|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Petrus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Petrus|Pet|\.[\s\xa0]*Petrus))|(?:(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Petrus|1(?:\.[\s\xa0]*|[\s\xa0]*)?Pe|I[\s\xa0]*Petrus|Bir(?:inci)?[\s\xa0]*Petrus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yah(?:uda)?|Jude)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob(?:[Iiİı]t)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Yud[Iiİı]|Jd)t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar(?:uk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Su(?:zanna|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Makabeler|Macc|\.[\s\xa0]*Makabeler)|[iİı]ki(?:nci)?[\s\xa0]*Makabeler|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Makabeler|3Macc|(?:III|3)\.[\s\xa0]*Makabeler|[U\xDC][c\xE7](?:[u\xFC]nc[u\xFC])?[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*Makabeler|4Macc|(?:IV|4)\.[\s\xa0]*Makabeler|D[o\xF6]r(?:d[u\xFC]nc[u\xFC]|t)[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[iİı]lk|1\.|I(?:lk|\.))[\s\xa0]*Makabeler|[1I][\s\xa0]*Makabeler|1Macc|Bir(?:inci)?[\s\xa0]*Makabeler)
)(?:(?=[\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]
| ba[şs]l[İIiı]k (?! [a-z] ) #could be followed by a number
| baplar | ayeti | ayet | bap | ile | a\. | bp | vs | vd | ve
| [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* ba[şs]l[İIiı]k
| \d \W* (?:vs|vd) (?: [\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 = "(?:1|I|Bir|Birinci|[İIiı]lk)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.second = "(?:2|II|[İIiı]ki|[İIiı]kinci)\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.third = "(?:3|III|[ÜU][çc]|[ÜU][çc][üu]nc[üu])\\.?#{bcv_parser::regexps.space}*"
bcv_parser::regexps.range_and = "(?:[&\u2013\u2014-]|ve|ile)"
bcv_parser::regexps.range_only = "(?:[\u2013\u2014-]|ile)"
# 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: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Te(?:sn[Iİı]ye|kv[Iİı]n)|Gen|Yar(?:at[Iİı]l[Iİı][sş])?)|(?:Yarat(?:il[Iiİı][sş]|[Iİı]li[sş])|Te(?:sniye|kvin))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Exod"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M[Iİı]s[Iİı]r(?:['’]dan[\s\xa0]*[C\xC7][Iİı]k[Iİı][sş]|dan[\s\xa0]*[C\xC7][Iİı]k[Iİı][sş])|[C\xC7][Iİı]k|Exod)|(?:M(?:[Iİı]s(?:[Iİı]r(?:['’]dan[\s\xa0]*[C\xC7](?:ik[Iiİı][sş]|[Iİı]ki[sş])|dan[\s\xa0]*[C\xC7](?:ik[Iiİı][sş]|[Iİı]ki[sş]))|ir(?:['’]dan[\s\xa0]*[C\xC7][Iiİı]|dan[\s\xa0]*[C\xC7][Iiİı])k[Iiİı][sş])|is[Iiİı]r(?:['’]dan[\s\xa0]*[C\xC7][Iiİı]|dan[\s\xa0]*[C\xC7][Iiİı])k[Iiİı][sş])|[C\xC7]ik[Iiİı][sş]|[C\xC7]ik|[C\xC7][Iİı]k[Iiİı][sş])
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bel"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bel(?:[\s\xa0]*ve[\s\xa0]*Ejderha)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Lev(?:[Iiİı]l[Iiİı]ler)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Num"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[C\xC7][o\xF6]lde[\s\xa0]*Say[Iİı]m|Say(?:[Iİı]lar)?|Num)|(?:[C\xC7][o\xF6]lde[\s\xa0]*Sayim|Sayilar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sir"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S(?:ir(?:ak)?|[Iİı]rak))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Wis"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:B[Iiİı]lgelik|Wis)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Lam"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:A[gğ][Iiİı](?:tlar)?|Lam)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["EpJer"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yeremya(?:['’]n[Iiİı]|n[Iiİı])n[\s\xa0]*Mektubu|EpJer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rev"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Va(?:h(?:[Iiİı]y)?)?|Rev)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrMan"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mana[sş][sş]e(?:['’]n[Iİı]n[\s\xa0]*Duas[Iİı]|n[Iİı]n[\s\xa0]*Duas[Iİı])|PrMan)|(?:Mana[sş][sş]e(?:['’]n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)|n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Deut"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yas(?:a(?:['’]n[Iİı]n[\s\xa0]*Tekrar[Iİı]|n[Iİı]n[\s\xa0]*Tekrar[Iİı]))?|Deut)|(?:Yasa(?:['’]n(?:in[\s\xa0]*Tekrar[Iiİı]|[Iİı]n[\s\xa0]*Tekrari)|n(?:in[\s\xa0]*Tekrar[Iiİı]|[Iİı]n[\s\xa0]*Tekrari)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Josh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Y(?:e[sş]|[sş])u|Josh)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Judg"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hak(?:[Iiİı]mler)?|Judg)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ruth"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ruth?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[iİı]lk|1\.|I(?:lk|\.))[\s\xa0]*Esdras|[1I][\s\xa0]*Esdras|1Esd|Bir(?:inci)?[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Esd"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Esdras|Esd|\.[\s\xa0]*Esdras)|[iİı]ki(?:nci)?[\s\xa0]*Esdras|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Esdras)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Isa"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Y(?:e[sş]ay|[sş])|Is)a)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Samuel|Sam|\.[\s\xa0]*Samuel))|(?:[iİı]ki(?:nci)?[\s\xa0]*Samuel|2(?:\.[\s\xa0]*|[\s\xa0]*)?Sa|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Sam"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Samuel|Sam|\.[\s\xa0]*Samuel))|(?:(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*PI:NAME:<NAME>END_PI|1(?:\.[\s\xa0]*|[\s\xa0]*)?Sa|I[\s\xa0]*PI:NAME:<NAME>END_PI|Bir(?:inci)?[\s\xa0]*Samuel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2\.?[\s\xa0]*Krallar)|(?:[iİı]ki(?:nci)?[\s\xa0]*Krallar|2(?:K(?:gs|r)|\.?[\s\xa0]*Kr)|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Krallar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Kgs"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1\.?[\s\xa0]*Krallar)|(?:1(?:K(?:gs|r)|\.?[\s\xa0]*Kr)|I[\s\xa0]*Krallar|(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Krallar|Bir(?:inci)?[\s\xa0]*Krallar)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:[İı]ki(?:nci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])hler|2(?:\.?[\s\xa0]*Tar[Iİı]hler|(?:\.?[\s\xa0]*)?Ta|Chr)|I(?:ki(?:nci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])|I(?:\.[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı]))hler)|(?:(?:(?:(?:II|2)\.|II|2|Iki(?:nci)?|[İı]ki(?:nci)?)[\s\xa0]*Tari|iki(?:nci[\s\xa0]*Tar[Iiİı]|[\s\xa0]*Tar[Iiİı]))hler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Chr"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Tar[Iİı]hler|(?:\.?[\s\xa0]*)?Ta|Chr)|I[\s\xa0]*Tar[Iİı]hler|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Tar[Iİı]hler|Bir(?:inci[\s\xa0]*Tar[Iİı]|[\s\xa0]*Tar[Iİı])hler)|(?:(?:(?:I(?:lk|\.)|[İı]lk|1\.)[\s\xa0]*Tari|ilk[\s\xa0]*Tar[Iiİı]|[1I][\s\xa0]*Tari|Bir(?:inci)?[\s\xa0]*Tari)hler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezra"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ezra?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Neh"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Neh(?:emya)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["GkEsth"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:G(?:rek[c\xE7]e[\s\xa0]*Ester|kEsth)|Yunanca[\s\xa0]*Ester)
)(?:(?=[\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})(
(?:Ey[u\xFC]p?|Job)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ps"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mez(?:mur(?:lar)?)?|Ps)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PrAzar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Azarya(?:['’]n[Iİı]n[\s\xa0]*Duas[Iİı]|n[Iİı]n[\s\xa0]*Duas[Iİı])|PrAzar)|(?:Azarya(?:['’]n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)|n(?:in[\s\xa0]*Duas[Iiİı]|[Iİı]n[\s\xa0]*Duasi)))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Prov"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:S[u\xFC]leyman(?:['’][Iİı]n[\s\xa0]*(?:[O\xD6]zdey[Iİı][sş]ler[Iİı]|Meseller[Iİı])|[Iİı]n[\s\xa0]*(?:[O\xD6]zdey[Iİı][sş]ler[Iİı]|Meseller[Iİı]))|[O\xD6]zd|Prov|Meseller)|(?:S[u\xFC]leyman(?:['’](?:[Iİı]n[\s\xa0]*(?:[O\xD6]zdey(?:i[sş]ler[Iiİı]|[Iİı][sş]leri)|Meselleri)|in[\s\xa0]*(?:[O\xD6]zdey[Iiİı][sş]ler[Iiİı]|Meseller[Iiİı]))|[Iİı]n[\s\xa0]*(?:[O\xD6]zdey(?:i[sş]ler[Iiİı]|[Iİı][sş]leri)|Meselleri)|in[\s\xa0]*(?:[O\xD6]zdey[Iiİı][sş]ler[Iiİı]|Meseller[Iiİı])))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eccl"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Va(?:[Iiİı]z|[Iiİı])|Eccl)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["SgThree"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[U\xDC][c\xE7][\s\xa0]*Gen[c\xE7][\s\xa0]*Adam[Iİı]n[\s\xa0]*Ezg[Iİı]s[Iİı]|SgThree)|(?:[U\xDC][c\xE7][\s\xa0]*Gen[c\xE7][\s\xa0]*Adam(?:[Iİı]n[\s\xa0]*Ezgis[Iiİı]|[Iİı]n[\s\xa0]*Ezg[Iİı]si|in[\s\xa0]*Ezg[Iiİı]s[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Song"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ezg(?:[Iİı]ler[\s\xa0]*Ezg[Iİı]s[Iİı])?|Song)|(?:Ezg(?:[Iİı]ler[\s\xa0]*Ezgis[Iiİı]|[Iİı]ler[\s\xa0]*Ezg[Iİı]si|iler[\s\xa0]*Ezg[Iiİı]s[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jer"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yer(?:emya)?|Jer)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Ezek"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hez(?:ek[Iiİı]el)?|Ezek)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Dan"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Dan(?:[Iiİı]el)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ho(?:s(?:ea)?|ş))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Joel"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yoel?|Joel)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Amos"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Amos?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Obad"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:O(?:va(?:dya)?|bad))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jonah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yun(?:us)?|Jonah)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mic"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:M(?:i(?:ka?|c)|[Iİı]ka?))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Nah"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Nah(?:um)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hab"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hab(?:akkuk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zeph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Sef(?:anya)?|Zeph)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Hag"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Hag(?:ay)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Zech"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Ze(?:k(?:er[Iiİı]ya)?|ch))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mal(?:ak[Iiİı])?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Matt"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mat(?:t(?:a(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?)|(?:Matta(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:(?:[Iuİı]n[\s\xa0]*)?i|in[\s\xa0]*[Iiİı]|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı]))ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Mark"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Mar(?:k(?:os(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?)|(?:Markos(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:(?:[Iuİı]n[\s\xa0]*)?i|in[\s\xa0]*[Iiİı]|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı]))ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Luke"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Luk(?:a(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil))|e)?)|(?:Luka(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:in(?:[\s\xa0]*[Iiİı]n)?|[Iuİı]n[\s\xa0]*in|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])n)cili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1\.?[\s\xa0]*Yuhanna)|(?:1(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|I[\s\xa0]*Yuhanna|(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Yuhanna|Bir(?:inci)?[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2\.?[\s\xa0]*Yuhanna)|(?:[iİı]ki(?:nci)?[\s\xa0]*Yuhanna|2(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3John"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:3\.?[\s\xa0]*Yuhanna)|(?:3(?:John|Yu|[\s\xa0]*Yu|\.[\s\xa0]*Yu)|III[\s\xa0]*Yuhanna|III\.[\s\xa0]*Yuhanna|[U\xDC][c\xE7](?:[u\xFC]nc[u\xFC])?[\s\xa0]*Yuhanna)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["PI:NAME:<NAME>END_PI"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yu(?:h(?:anna(?:(?:[Iİı]n[\s\xa0]*[Iİı]|[Iİı]|un[\s\xa0]*[Iİı]|n[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|['’](?:(?:n[Iuİı]n[\s\xa0]*[Iİı]|[Iuİı]n[\s\xa0]*[Iİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*[Iİı]ncil)))?)?|PI:NAME:<NAME>END_PI)|(?:PI:NAME:<NAME>END_PI(?:['’](?:(?:n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])|[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])ncili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)|(?:in(?:[\s\xa0]*[Iiİı]n)?|[Iuİı]n[\s\xa0]*in|n(?:[Iuİı]n[\s\xa0]*i|in[\s\xa0]*[Iiİı])n)cili|a[\s\xa0]*G[o\xF6]re[\s\xa0]*incil|ya[\s\xa0]*G[o\xF6]re[\s\xa0]*incil)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Acts"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:El[c\xE7](?:[Iİı]ler[Iİı]n[\s\xa0]*[Iİı][sş]ler[Iİı])?|Acts)|(?:El[c\xE7](?:[Iİı]ler[Iİı]n[\s\xa0]*i[sş]ler[Iiİı]|[Iİı]ler[Iİı]n[\s\xa0]*[Iİı][sş]leri|[Iİı]lerin[\s\xa0]*[Iiİı][sş]ler[Iiİı]|iler[Iiİı]n[\s\xa0]*[Iiİı][sş]ler[Iiİı]))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Rom"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Rom(?:al[Iiİı]lar)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ki(?:nci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))|I(?:\.[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)))r|[İı]ki(?:nci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))r|2(?:\.?[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:\.?[\s\xa0]*)?Ko|Cor))|(?:(?:(?:(?:II|2)\.[\s\xa0]*Kor[Iİı]|(?:II|2)[\s\xa0]*Kor[Iİı]|Iki(?:nci[\s\xa0]*Kor[Iİı]|[\s\xa0]*Kor[Iİı])|[İı]ki(?:nci[\s\xa0]*Kor[Iİı]|[\s\xa0]*Kor[Iİı]))ntlile|(?:(?:II|2)\.|II|2|Iki(?:nci)?|[İı]ki(?:nci)?)[\s\xa0]*Korint(?:l[Iiİı]le|oslula)|iki(?:nci[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)|[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)))r)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Cor"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:\.?[\s\xa0]*)?Ko|Cor)|I[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)r|Bir(?:inci[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula)|[\s\xa0]*Kor[Iİı]nt(?:l[Iİı]le|oslula))r)|(?:(?:[1I][\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|ilk[\s\xa0]*Kor[Iiİı]nt(?:l[Iiİı]le|oslula)|(?:[1I]\.|Ilk|[İı]lk)[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|Bir(?:inci[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)|[\s\xa0]*Kor(?:int(?:l[Iiİı]le|oslula)|[Iİı]ntlile)))r)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Gal"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Gal(?:atyal[Iiİı]lar)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Eph"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:E(?:f(?:e(?:sl[Iiİı]ler)?)?|ph))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phil"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:[Iİı]l[Iİı]p[Iİı]l[Iİı]ler|lp)|Phil)|(?:F(?:[Iİı]l(?:[Iİı]p(?:il[Iiİı]|[Iİı]li)|ip[Iiİı]l[Iiİı])|il[Iiİı]p[Iiİı]l[Iiİı])ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Col"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Kol(?:osel[Iiİı]ler)?|Col)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:I(?:ki(?:nci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])|I(?:\.[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı]))ler|[İı]ki(?:nci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])ler|2(?:\.?[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Thess|Se|\.?[\s\xa0]*Se))|(?:(?:iki(?:nci[\s\xa0]*Selan[Iiİı]|[\s\xa0]*Selan[Iiİı])kl[Iiİı]|(?:II|2)[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|(?:II|2)\.[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|Iki(?:nci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli))|[İı]ki(?:nci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)))ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Thess"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:\.?[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Thess|Se|\.?[\s\xa0]*Se)|I[\s\xa0]*Selan[Iİı]kl[Iİı]ler|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Selan[Iİı]kl[Iİı]ler|Bir(?:inci[\s\xa0]*Selan[Iİı]kl[Iİı]|[\s\xa0]*Selan[Iİı]kl[Iİı])ler)|(?:(?:[1I][\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|ilk[\s\xa0]*Selan[Iiİı]kl[Iiİı]|(?:[1I]\.|Ilk|[İı]lk)[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|Bir(?:inci[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)|[\s\xa0]*Selan(?:ikl[Iiİı]|[Iİı]kli)))ler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2Tim)|(?:2(?:(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]|Ti)|[İı]ki(?:nci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|I(?:ki(?:nci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])|I(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]))moteos)|(?:(?:I(?:ki(?:nci)?|I\.?)|[İı]ki(?:nci)?)[\s\xa0]*Timoteos|2(?:\.?[\s\xa0]*Timoteos|\.?[\s\xa0]*Ti)|iki(?:nci[\s\xa0]*T[Iiİı]|[\s\xa0]*T[Iiİı])moteos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Tim"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1Tim)|(?:1(?:(?:\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos|\.[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı]|Ti)|I[\s\xa0]*T[Iİı]moteos|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*T[Iİı]moteos|Bir(?:inci[\s\xa0]*T[Iİı]|[\s\xa0]*T[Iİı])moteos)|(?:1(?:\.?[\s\xa0]*Timoteos|\.?[\s\xa0]*Ti)|ilk[\s\xa0]*T[Iiİı]moteos|I[\s\xa0]*Timoteos|(?:I(?:lk|\.)|[İı]lk)[\s\xa0]*Timoteos|Bir(?:inci)?[\s\xa0]*Timoteos)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Titus"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:T[Iiİı]t(?:us)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Phlm"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:F(?:[Iiİı]l[Iiİı]mon|lm)|Phlm)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Heb"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:[Iİı]br(?:an[Iİı]ler)?|Heb)|(?:ibr(?:an[Iiİı]ler)?|[Iİı]braniler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jas"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yak(?:up)?|Jas)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Petrus|Pet|\.[\s\xa0]*Petrus))|(?:[iİı]ki(?:nci)?[\s\xa0]*Petrus|2(?:\.[\s\xa0]*|[\s\xa0]*)?Pe|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Petrus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Pet"]
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:1(?:[\s\xa0]*Petrus|Pet|\.[\s\xa0]*Petrus))|(?:(?:I(?:lk|\.)|[iİı]lk)[\s\xa0]*Petrus|1(?:\.[\s\xa0]*|[\s\xa0]*)?Pe|I[\s\xa0]*Petrus|Bir(?:inci)?[\s\xa0]*Petrus)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jude"]
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Yah(?:uda)?|Jude)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Tob"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Tob(?:[Iiİı]t)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Jdt"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:(?:Yud[Iiİı]|Jd)t)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Bar"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Bar(?:uk)?)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["Sus"]
apocrypha: true
regexp: ///(^|#{bcv_parser::regexps.pre_book})(
(?:Su(?:zanna|s))
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["2Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:2(?:[\s\xa0]*Makabeler|Macc|\.[\s\xa0]*Makabeler)|[iİı]ki(?:nci)?[\s\xa0]*Makabeler|I(?:ki(?:nci)?|I\.?)[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["3Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:III|3)[\s\xa0]*Makabeler|3Macc|(?:III|3)\.[\s\xa0]*Makabeler|[U\xDC][c\xE7](?:[u\xFC]nc[u\xFC])?[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["4Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:IV|4)[\s\xa0]*Makabeler|4Macc|(?:IV|4)\.[\s\xa0]*Makabeler|D[o\xF6]r(?:d[u\xFC]nc[u\xFC]|t)[\s\xa0]*Makabeler)
)(?:(?=[\d\s\xa0.:,;\x1e\x1f&\(\)\uff08\uff09\[\]/"'\*=~\-\u2013\u2014])|$)///gi
,
osis: ["1Macc"]
apocrypha: true
regexp: ///(^|[^0-9A-Za-zªµºÀ-ÖØ-öø-ɏḀ-ỿⱠ-ⱿꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꟿ])(
(?:(?:[iİı]lk|1\.|I(?:lk|\.))[\s\xa0]*Makabeler|[1I][\s\xa0]*Makabeler|1Macc|Bir(?:inci)?[\s\xa0]*Makabeler)
)(?:(?=[\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": "alforage\"\n\n casper.then ->\n @evaluate ->\n michael = new Model\n name: 'Michael Bolton'\n",
"end": 523,
"score": 0.6944465041160583,
"start": 522,
"tag": "NAME",
"value": "m"
},
{
"context": "forage\"\n\n casper.then ->\n @evaluate ->\n michael = new Model\n name: 'Michael Bolton'\n ",
"end": 529,
"score": 0.5166313052177429,
"start": 523,
"tag": "NAME",
"value": "ichael"
},
{
"context": "luate ->\n michael = new Model\n name: 'Michael Bolton'\n job: 'Singer'\n\n Models.add michael\n",
"end": 571,
"score": 0.999858021736145,
"start": 557,
"tag": "NAME",
"value": "Michael Bolton"
},
{
"context": "el Bolton'\n job: 'Singer'\n\n Models.add michael\n michael.save()\n\n casper.reload()\n\n ",
"end": 614,
"score": 0.7733108997344971,
"start": 613,
"tag": "NAME",
"value": "m"
},
{
"context": " Bolton'\n job: 'Singer'\n\n Models.add michael\n michael.save()\n\n casper.reload()\n\n casper",
"end": 620,
"score": 0.4390125870704651,
"start": 614,
"tag": "NAME",
"value": "ichael"
},
{
"context": "ertEval ->\n results = Models.where({name: 'Michael Bolton'})\n results[0].get('job') is \"Singer\"\n ",
"end": 791,
"score": 0.9998332858085632,
"start": 777,
"tag": "NAME",
"value": "Michael Bolton"
},
{
"context": "valuate ->\n results = Models.where({name: 'Michael Bolton'})\n\n results[0].destroy()\n Models.r",
"end": 1023,
"score": 0.9998178482055664,
"start": 1009,
"tag": "NAME",
"value": "Michael Bolton"
},
{
"context": "ssertEval ->\n results = Models.where({name: 'Michael Bolton'})\n results.length is 0\n , \"Backbone adap",
"end": 1191,
"score": 0.9997925758361816,
"start": 1177,
"tag": "NAME",
"value": "Michael Bolton"
},
{
"context": "\"\n\n casper.then ->\n # See: https://github.com/mozilla/localForage/pull/90\n casper.fill '.content for",
"end": 1998,
"score": 0.9981939196586609,
"start": 1991,
"tag": "USERNAME",
"value": "mozilla"
}
] | test/test.backbone.coffee | thebaer/localForage | 1 | 'use strict'
casper.test.begin "Testing Backbone data adapter", (test) ->
casper.start "#{casper.TEST_URL}test.backbone.html", ->
test.info "Testing using global scope (no require.js)"
test.assertEval ->
typeof Backbone.localforage is 'object'
, "localforage storage adapter is attached to Backbone.localforage"
test.assertEval ->
typeof Backbone.localforage.sync is 'function'
, "localforage sync function is attached to Backbone.localforage"
casper.then ->
@evaluate ->
michael = new Model
name: 'Michael Bolton'
job: 'Singer'
Models.add michael
michael.save()
casper.reload()
casper.then ->
@waitForSelector '#ready', ->
test.assertEval ->
results = Models.where({name: 'Michael Bolton'})
results[0].get('job') is "Singer"
, "Backbone adapter should persist data after a reload"
casper.then ->
@waitForSelector '#ready', ->
@evaluate ->
results = Models.where({name: 'Michael Bolton'})
results[0].destroy()
Models.reset()
casper.wait 300
casper.then ->
test.assertEval ->
results = Models.where({name: 'Michael Bolton'})
results.length is 0
, "Backbone adapter should delete data after model is removed"
casper.thenOpen "#{casper.TEST_URL}backbone-example.html", ->
test.info "Test the Backbone example (examples/backbone-example.html)"
@waitForSelector '.content', ->
# Fill the content form and test it saves the content without error.
casper.fill '.content form', {content: 'testing'}, true
casper.reload()
casper.then ->
@waitForSelector '.content .saved-data', ->
test.assertEval ->
$('.saved-data').length is 1
, "Backbone example saves a piece of data between page loads"
test.assertEval ->
$('.saved-data').text() is 'testing'
, "Data saved in Backbone is retrieved properly"
casper.then ->
# See: https://github.com/mozilla/localForage/pull/90
casper.fill '.content form', {content: 'test 2'}, true
casper.fill '.content form', {content: 'test 3'}, true
casper.then ->
test.assertEval ->
$('.saved-data').length is 3
, "Extra data is saved properly"
test.assertEval ->
$('.saved-data').eq(2).text() is 'test 3'
, "Data saved in Backbone is retrieved properly"
casper.then ->
@evaluate ->
localforage.clear()
casper.wait 200
casper.reload()
casper.then ->
@waitForSelector '.content', ->
test.assertEval ->
$('.saved-data').length is 0
, "After running clear() on localforage, no saved-data divs exist"
casper.run ->
test.done()
| 171890 | 'use strict'
casper.test.begin "Testing Backbone data adapter", (test) ->
casper.start "#{casper.TEST_URL}test.backbone.html", ->
test.info "Testing using global scope (no require.js)"
test.assertEval ->
typeof Backbone.localforage is 'object'
, "localforage storage adapter is attached to Backbone.localforage"
test.assertEval ->
typeof Backbone.localforage.sync is 'function'
, "localforage sync function is attached to Backbone.localforage"
casper.then ->
@evaluate ->
<NAME> <NAME> = new Model
name: '<NAME>'
job: 'Singer'
Models.add <NAME> <NAME>
michael.save()
casper.reload()
casper.then ->
@waitForSelector '#ready', ->
test.assertEval ->
results = Models.where({name: '<NAME>'})
results[0].get('job') is "Singer"
, "Backbone adapter should persist data after a reload"
casper.then ->
@waitForSelector '#ready', ->
@evaluate ->
results = Models.where({name: '<NAME>'})
results[0].destroy()
Models.reset()
casper.wait 300
casper.then ->
test.assertEval ->
results = Models.where({name: '<NAME>'})
results.length is 0
, "Backbone adapter should delete data after model is removed"
casper.thenOpen "#{casper.TEST_URL}backbone-example.html", ->
test.info "Test the Backbone example (examples/backbone-example.html)"
@waitForSelector '.content', ->
# Fill the content form and test it saves the content without error.
casper.fill '.content form', {content: 'testing'}, true
casper.reload()
casper.then ->
@waitForSelector '.content .saved-data', ->
test.assertEval ->
$('.saved-data').length is 1
, "Backbone example saves a piece of data between page loads"
test.assertEval ->
$('.saved-data').text() is 'testing'
, "Data saved in Backbone is retrieved properly"
casper.then ->
# See: https://github.com/mozilla/localForage/pull/90
casper.fill '.content form', {content: 'test 2'}, true
casper.fill '.content form', {content: 'test 3'}, true
casper.then ->
test.assertEval ->
$('.saved-data').length is 3
, "Extra data is saved properly"
test.assertEval ->
$('.saved-data').eq(2).text() is 'test 3'
, "Data saved in Backbone is retrieved properly"
casper.then ->
@evaluate ->
localforage.clear()
casper.wait 200
casper.reload()
casper.then ->
@waitForSelector '.content', ->
test.assertEval ->
$('.saved-data').length is 0
, "After running clear() on localforage, no saved-data divs exist"
casper.run ->
test.done()
| true | 'use strict'
casper.test.begin "Testing Backbone data adapter", (test) ->
casper.start "#{casper.TEST_URL}test.backbone.html", ->
test.info "Testing using global scope (no require.js)"
test.assertEval ->
typeof Backbone.localforage is 'object'
, "localforage storage adapter is attached to Backbone.localforage"
test.assertEval ->
typeof Backbone.localforage.sync is 'function'
, "localforage sync function is attached to Backbone.localforage"
casper.then ->
@evaluate ->
PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI = new Model
name: 'PI:NAME:<NAME>END_PI'
job: 'Singer'
Models.add PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
michael.save()
casper.reload()
casper.then ->
@waitForSelector '#ready', ->
test.assertEval ->
results = Models.where({name: 'PI:NAME:<NAME>END_PI'})
results[0].get('job') is "Singer"
, "Backbone adapter should persist data after a reload"
casper.then ->
@waitForSelector '#ready', ->
@evaluate ->
results = Models.where({name: 'PI:NAME:<NAME>END_PI'})
results[0].destroy()
Models.reset()
casper.wait 300
casper.then ->
test.assertEval ->
results = Models.where({name: 'PI:NAME:<NAME>END_PI'})
results.length is 0
, "Backbone adapter should delete data after model is removed"
casper.thenOpen "#{casper.TEST_URL}backbone-example.html", ->
test.info "Test the Backbone example (examples/backbone-example.html)"
@waitForSelector '.content', ->
# Fill the content form and test it saves the content without error.
casper.fill '.content form', {content: 'testing'}, true
casper.reload()
casper.then ->
@waitForSelector '.content .saved-data', ->
test.assertEval ->
$('.saved-data').length is 1
, "Backbone example saves a piece of data between page loads"
test.assertEval ->
$('.saved-data').text() is 'testing'
, "Data saved in Backbone is retrieved properly"
casper.then ->
# See: https://github.com/mozilla/localForage/pull/90
casper.fill '.content form', {content: 'test 2'}, true
casper.fill '.content form', {content: 'test 3'}, true
casper.then ->
test.assertEval ->
$('.saved-data').length is 3
, "Extra data is saved properly"
test.assertEval ->
$('.saved-data').eq(2).text() is 'test 3'
, "Data saved in Backbone is retrieved properly"
casper.then ->
@evaluate ->
localforage.clear()
casper.wait 200
casper.reload()
casper.then ->
@waitForSelector '.content', ->
test.assertEval ->
$('.saved-data').length is 0
, "After running clear() on localforage, no saved-data divs exist"
casper.run ->
test.done()
|
[
{
"context": "quires lodash\n@requires q\n@requires bcrypt\n@author Isaac Johnston <isaac.johnston@joukou.com>\n###\n\n_ ",
"end": 1115,
"score": 0.9998690485954285,
"start": 1101,
"tag": "NAME",
"value": "Isaac Johnston"
},
{
"context": "quires q\n@requires bcrypt\n@author Isaac Johnston <isaac.johnston@joukou.com>\n###\n\n_ = require( 'lodash' )\nQ ",
"end": 1142,
"score": 0.9999346733093262,
"start": 1117,
"tag": "EMAIL",
"value": "isaac.johnston@joukou.com"
}
] | src/agent/model.coffee | joukou/joukou-api | 0 | "use strict"
###*
Copyright 2014 Joukou Ltd
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.
###
###*
An agent is authorized to act on behalf of a persona (called the principal).
By way of a relationship between the principal and an agent the principal
authorizes the agent to work under his control and on his behalf.
Latin: qui facit per alium, facit per se, i.e. the one who acts through
another, acts in his or her own interests.
@class joukou-api/agent/Model
@requires joukou-api/agent/schema
@requires joukou-api/riak/Model
@requires joukou-api/error/BcryptError
@requires lodash
@requires q
@requires bcrypt
@author Isaac Johnston <isaac.johnston@joukou.com>
###
_ = require( 'lodash' )
Q = require( 'q' )
bcrypt = require( 'bcrypt' )
schema = require( './schema')
Model = require( '../riak/Model' )
BcryptError = require( '../error/BcryptError' )
AgentModel = Model.define(
schema: schema
type: 'agent'
bucket: 'agent'
)
###*
After creating an agent model instance, encrypt the password with bcrypt.
###
AgentModel.afterCreate = ( agent ) ->
deferred = Q.defer()
agent.afterRetrieve();
# Hash password
###
bcrypt.genSalt( 10, ( err, salt ) ->
if err
deferred.reject( new BcryptError( err ) )
else
bcrypt.hash( agent.getValue().password, salt, ( err, hash ) ->
if err
deferred.reject( new BcryptError( err ) )
else
agent.setValue( _.assign( agent.getValue(), password: hash ) )
deferred.resolve( agent )
)
)
###
deferred.resolve(agent)
deferred.promise
###*
Verify the given `password` against the stored password.
@method verifyPassword
@return {q.promise}
###
AgentModel::verifyPassword = ( password ) ->
deferred = Q.defer()
bcrypt.compare( password, @getValue().password, ( err, authenticated ) ->
if err
deferred.reject( new BcryptError( err ) )
else
deferred.resolve( authenticated )
)
deferred.promise
AgentModel.retriveByGithubId = ( id ) ->
AgentModel.retrieveBySecondaryIndex( 'githubId_int', id, true )
AgentModel.retrieveByEmail = ( email ) ->
AgentModel.retrieveBySecondaryIndex( 'email_bin', email, true )
AgentModel.deleteByEmail = ( email ) ->
deferred = Q.defer()
AgentModel.retrieveByEmail( email ).then( ( agent ) ->
agent.delete()
)
.then( -> deferred.resolve() )
.fail( ( err ) -> deferred.reject( err ) )
deferred.promise
AgentModel::getRepresentation = ->
_.pick( @getValue(), [ 'email', 'roles', 'name' ] )
AgentModel::getEmail = ->
@getValue().email
AgentModel::getName = ->
@getValue().name
AgentModel::getRoles = ->
@getValue().roles
AgentModel::hasRole = ( role ) ->
roles = [ role ]
@hasSomeRoles( roles )
AgentModel::hasSomeRoles = ( roles ) ->
_.some( roles, ( role ) =>
(@getRoles() or []).indexOf( role ) isnt -1
)
AgentModel::beforeSave = ->
AgentModel::afterRetrieve = ->
this.addSecondaryIndex( 'email' )
this.addSecondaryIndex( 'github_id' )
module.exports = AgentModel
| 86328 | "use strict"
###*
Copyright 2014 Joukou Ltd
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.
###
###*
An agent is authorized to act on behalf of a persona (called the principal).
By way of a relationship between the principal and an agent the principal
authorizes the agent to work under his control and on his behalf.
Latin: qui facit per alium, facit per se, i.e. the one who acts through
another, acts in his or her own interests.
@class joukou-api/agent/Model
@requires joukou-api/agent/schema
@requires joukou-api/riak/Model
@requires joukou-api/error/BcryptError
@requires lodash
@requires q
@requires bcrypt
@author <NAME> <<EMAIL>>
###
_ = require( 'lodash' )
Q = require( 'q' )
bcrypt = require( 'bcrypt' )
schema = require( './schema')
Model = require( '../riak/Model' )
BcryptError = require( '../error/BcryptError' )
AgentModel = Model.define(
schema: schema
type: 'agent'
bucket: 'agent'
)
###*
After creating an agent model instance, encrypt the password with bcrypt.
###
AgentModel.afterCreate = ( agent ) ->
deferred = Q.defer()
agent.afterRetrieve();
# Hash password
###
bcrypt.genSalt( 10, ( err, salt ) ->
if err
deferred.reject( new BcryptError( err ) )
else
bcrypt.hash( agent.getValue().password, salt, ( err, hash ) ->
if err
deferred.reject( new BcryptError( err ) )
else
agent.setValue( _.assign( agent.getValue(), password: hash ) )
deferred.resolve( agent )
)
)
###
deferred.resolve(agent)
deferred.promise
###*
Verify the given `password` against the stored password.
@method verifyPassword
@return {q.promise}
###
AgentModel::verifyPassword = ( password ) ->
deferred = Q.defer()
bcrypt.compare( password, @getValue().password, ( err, authenticated ) ->
if err
deferred.reject( new BcryptError( err ) )
else
deferred.resolve( authenticated )
)
deferred.promise
AgentModel.retriveByGithubId = ( id ) ->
AgentModel.retrieveBySecondaryIndex( 'githubId_int', id, true )
AgentModel.retrieveByEmail = ( email ) ->
AgentModel.retrieveBySecondaryIndex( 'email_bin', email, true )
AgentModel.deleteByEmail = ( email ) ->
deferred = Q.defer()
AgentModel.retrieveByEmail( email ).then( ( agent ) ->
agent.delete()
)
.then( -> deferred.resolve() )
.fail( ( err ) -> deferred.reject( err ) )
deferred.promise
AgentModel::getRepresentation = ->
_.pick( @getValue(), [ 'email', 'roles', 'name' ] )
AgentModel::getEmail = ->
@getValue().email
AgentModel::getName = ->
@getValue().name
AgentModel::getRoles = ->
@getValue().roles
AgentModel::hasRole = ( role ) ->
roles = [ role ]
@hasSomeRoles( roles )
AgentModel::hasSomeRoles = ( roles ) ->
_.some( roles, ( role ) =>
(@getRoles() or []).indexOf( role ) isnt -1
)
AgentModel::beforeSave = ->
AgentModel::afterRetrieve = ->
this.addSecondaryIndex( 'email' )
this.addSecondaryIndex( 'github_id' )
module.exports = AgentModel
| true | "use strict"
###*
Copyright 2014 Joukou Ltd
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.
###
###*
An agent is authorized to act on behalf of a persona (called the principal).
By way of a relationship between the principal and an agent the principal
authorizes the agent to work under his control and on his behalf.
Latin: qui facit per alium, facit per se, i.e. the one who acts through
another, acts in his or her own interests.
@class joukou-api/agent/Model
@requires joukou-api/agent/schema
@requires joukou-api/riak/Model
@requires joukou-api/error/BcryptError
@requires lodash
@requires q
@requires bcrypt
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
_ = require( 'lodash' )
Q = require( 'q' )
bcrypt = require( 'bcrypt' )
schema = require( './schema')
Model = require( '../riak/Model' )
BcryptError = require( '../error/BcryptError' )
AgentModel = Model.define(
schema: schema
type: 'agent'
bucket: 'agent'
)
###*
After creating an agent model instance, encrypt the password with bcrypt.
###
AgentModel.afterCreate = ( agent ) ->
deferred = Q.defer()
agent.afterRetrieve();
# Hash password
###
bcrypt.genSalt( 10, ( err, salt ) ->
if err
deferred.reject( new BcryptError( err ) )
else
bcrypt.hash( agent.getValue().password, salt, ( err, hash ) ->
if err
deferred.reject( new BcryptError( err ) )
else
agent.setValue( _.assign( agent.getValue(), password: hash ) )
deferred.resolve( agent )
)
)
###
deferred.resolve(agent)
deferred.promise
###*
Verify the given `password` against the stored password.
@method verifyPassword
@return {q.promise}
###
AgentModel::verifyPassword = ( password ) ->
deferred = Q.defer()
bcrypt.compare( password, @getValue().password, ( err, authenticated ) ->
if err
deferred.reject( new BcryptError( err ) )
else
deferred.resolve( authenticated )
)
deferred.promise
AgentModel.retriveByGithubId = ( id ) ->
AgentModel.retrieveBySecondaryIndex( 'githubId_int', id, true )
AgentModel.retrieveByEmail = ( email ) ->
AgentModel.retrieveBySecondaryIndex( 'email_bin', email, true )
AgentModel.deleteByEmail = ( email ) ->
deferred = Q.defer()
AgentModel.retrieveByEmail( email ).then( ( agent ) ->
agent.delete()
)
.then( -> deferred.resolve() )
.fail( ( err ) -> deferred.reject( err ) )
deferred.promise
AgentModel::getRepresentation = ->
_.pick( @getValue(), [ 'email', 'roles', 'name' ] )
AgentModel::getEmail = ->
@getValue().email
AgentModel::getName = ->
@getValue().name
AgentModel::getRoles = ->
@getValue().roles
AgentModel::hasRole = ( role ) ->
roles = [ role ]
@hasSomeRoles( roles )
AgentModel::hasSomeRoles = ( roles ) ->
_.some( roles, ( role ) =>
(@getRoles() or []).indexOf( role ) isnt -1
)
AgentModel::beforeSave = ->
AgentModel::afterRetrieve = ->
this.addSecondaryIndex( 'email' )
this.addSecondaryIndex( 'github_id' )
module.exports = AgentModel
|
[
{
"context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li",
"end": 43,
"score": 0.9999173879623413,
"start": 29,
"tag": "EMAIL",
"value": "contact@ppy.sh"
}
] | resources/assets/coffee/_classes/landing-graph.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 @LandingGraph
container: document.getElementsByClassName('js-landing-graph')
constructor: ->
$(window).on 'throttled-resize', @resize
$(document).on 'turbolinks:load', @initialize
initialize: =>
return if !@container[0]?
@container[0]._chart ?= new LandingUserStats
resize: =>
return if !@container[0]?
@container[0]._chart?.resize()
| 168096 | # 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 @LandingGraph
container: document.getElementsByClassName('js-landing-graph')
constructor: ->
$(window).on 'throttled-resize', @resize
$(document).on 'turbolinks:load', @initialize
initialize: =>
return if !@container[0]?
@container[0]._chart ?= new LandingUserStats
resize: =>
return if !@container[0]?
@container[0]._chart?.resize()
| 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 @LandingGraph
container: document.getElementsByClassName('js-landing-graph')
constructor: ->
$(window).on 'throttled-resize', @resize
$(document).on 'turbolinks:load', @initialize
initialize: =>
return if !@container[0]?
@container[0]._chart ?= new LandingUserStats
resize: =>
return if !@container[0]?
@container[0]._chart?.resize()
|
[
{
"context": "ginal', ->\n fn = t 's b', goodName\n fn('Dan').should.equal false\n fn('Danny').should.equ",
"end": 574,
"score": 0.9995474219322205,
"start": 571,
"tag": "NAME",
"value": "Dan"
},
{
"context": "Name\n fn('Dan').should.equal false\n fn('Danny').should.equal true\n\n\n it 'should accept capit",
"end": 611,
"score": 0.998780369758606,
"start": 606,
"tag": "NAME",
"value": "Danny"
},
{
"context": "ature', ->\n fn = t 'S B', goodName\n fn('Dan').should.equal false\n fn('Danny').should.equ",
"end": 746,
"score": 0.9996629357337952,
"start": 743,
"tag": "NAME",
"value": "Dan"
},
{
"context": "Name\n fn('Dan').should.equal false\n fn('Danny').should.equal true\n\n\n it 'should throw an err",
"end": 783,
"score": 0.999129056930542,
"start": 778,
"tag": "NAME",
"value": "Danny"
}
] | test/main.coffee | dmotz/taxa | 4 | require 'should'
require 'coffee-script/register'
t = require '../taxa.coffee'
goodName = (name) -> name.length > 3
add = (a, b) -> a + b
sayHello = -> 'hello'
describe 'taxa', ->
describe '#taxa()', ->
it 'should always return a function', ->
(typeof t 's b', goodName).should.equal 'function'
it 'should throw an error unless a signature string and a function are passed', ->
t.should.throw()
(-> t 1, 2).should.throw()
it 'should return a function that behaves as the original', ->
fn = t 's b', goodName
fn('Dan').should.equal false
fn('Danny').should.equal true
it 'should accept capitalized variants in the type signature', ->
fn = t 'S B', goodName
fn('Dan').should.equal false
fn('Danny').should.equal true
it 'should throw an error if passed the wrong type of arguments', ->
(-> t('n,n n', add) 'hi').should.throw()
it 'should throw an error if the function returns the wrong type', ->
t('_ n', sayHello).should.throw()
it 'should allow optional arguments', ->
t('s? b', -> true).should.not.throw()
it 'should throw when optional types do not match', ->
(-> t('s? b', -> true) 5).should.throw()
it 'should allow functions that return no value', ->
(-> t('s _', ->) 'hi').should.not.throw()
(-> t('s u', ->) 'hi').should.not.throw()
it 'should allow functions that accept no arguments', ->
t('_ b', -> true).should.not.throw()
it 'should allow functions that accept no arguments and return no value', ->
t('_ _', ->).should.not.throw()
it 'should correctly identify arrays passed as arguments', ->
fn = t 'a a', (a) -> []
(-> fn [1, 2, 3]).should.not.throw()
(-> fn {}).should.throw()
it 'should allow disjunctive types for arguments', ->
fn = t 's|n,n b', (x, l) -> String(x).length >= l
(-> fn 123, 3).should.not.throw()
(-> fn '123', 3).should.not.throw()
it 'should allow disjunctive types for return signatures', ->
fn = t 's s|b', (s) ->
if s is 'true'
true
else if s is 'false'
false
else
s
fn('true').should.equal true
fn('false').should.equal false
fn('neither').should.equal 'neither'
it 'should differentiate null from undefined', ->
takesNull = t '0 _', ->
(-> takesNull null).should.not.throw()
takesNull.should.throw()
t('_ 0', ->).should.throw()
(-> t('U _', ->) null).should.throw()
it 'should enforce complex types', ->
bufferMaker = t 'n Buffer', (n) -> new Buffer n
(-> bufferMaker 1).should.not.throw()
takesBuffer = t 'Buffer _', ->
(-> takesBuffer bufferMaker 1).should.not.throw()
(-> takesBuffer 1).should.throw()
describe '#.bind()', ->
it 'should allow partial application with type checking', ->
add3 = t('n,n n', add).bind @, 3
add3(2).should.equal 5
it 'should allow partial application of all expected arguments', ->
add3And4 = t('n,n n', add).bind @, 3, 4
add3And4().should.equal 7
describe '#taxa.disable()', ->
it 'should disable type checking', ->
t.disable()
t('_ n', sayHello)().should.equal 'hello'
describe '#taxa.enable()', ->
it 'should enable type checking', ->
t.enable()
t('_ n', sayHello).should.throw()
describe '#taxa.addAlias()', ->
it 'should allow aliasing other types with abbreviations', ->
t.addAlias 'i8', 'Int8Array'
(-> t('i8 i8', (a) -> a) new Int8Array).should.not.throw()
it 'should disallow alias collisions', ->
(-> t.addAlias 'i8', 'UInt8Array').should.throw()
describe '#taxa.removeAlias()', ->
it 'should allow alias removal', ->
t.removeAlias 'i8'
(-> t('i8 i8', (a) -> a) new Int8Array).should.throw()
it 'should throw when removing an unregistered alias', ->
(-> t.removeAlias 'i8').should.throw()
| 70825 | require 'should'
require 'coffee-script/register'
t = require '../taxa.coffee'
goodName = (name) -> name.length > 3
add = (a, b) -> a + b
sayHello = -> 'hello'
describe 'taxa', ->
describe '#taxa()', ->
it 'should always return a function', ->
(typeof t 's b', goodName).should.equal 'function'
it 'should throw an error unless a signature string and a function are passed', ->
t.should.throw()
(-> t 1, 2).should.throw()
it 'should return a function that behaves as the original', ->
fn = t 's b', goodName
fn('<NAME>').should.equal false
fn('<NAME>').should.equal true
it 'should accept capitalized variants in the type signature', ->
fn = t 'S B', goodName
fn('<NAME>').should.equal false
fn('<NAME>').should.equal true
it 'should throw an error if passed the wrong type of arguments', ->
(-> t('n,n n', add) 'hi').should.throw()
it 'should throw an error if the function returns the wrong type', ->
t('_ n', sayHello).should.throw()
it 'should allow optional arguments', ->
t('s? b', -> true).should.not.throw()
it 'should throw when optional types do not match', ->
(-> t('s? b', -> true) 5).should.throw()
it 'should allow functions that return no value', ->
(-> t('s _', ->) 'hi').should.not.throw()
(-> t('s u', ->) 'hi').should.not.throw()
it 'should allow functions that accept no arguments', ->
t('_ b', -> true).should.not.throw()
it 'should allow functions that accept no arguments and return no value', ->
t('_ _', ->).should.not.throw()
it 'should correctly identify arrays passed as arguments', ->
fn = t 'a a', (a) -> []
(-> fn [1, 2, 3]).should.not.throw()
(-> fn {}).should.throw()
it 'should allow disjunctive types for arguments', ->
fn = t 's|n,n b', (x, l) -> String(x).length >= l
(-> fn 123, 3).should.not.throw()
(-> fn '123', 3).should.not.throw()
it 'should allow disjunctive types for return signatures', ->
fn = t 's s|b', (s) ->
if s is 'true'
true
else if s is 'false'
false
else
s
fn('true').should.equal true
fn('false').should.equal false
fn('neither').should.equal 'neither'
it 'should differentiate null from undefined', ->
takesNull = t '0 _', ->
(-> takesNull null).should.not.throw()
takesNull.should.throw()
t('_ 0', ->).should.throw()
(-> t('U _', ->) null).should.throw()
it 'should enforce complex types', ->
bufferMaker = t 'n Buffer', (n) -> new Buffer n
(-> bufferMaker 1).should.not.throw()
takesBuffer = t 'Buffer _', ->
(-> takesBuffer bufferMaker 1).should.not.throw()
(-> takesBuffer 1).should.throw()
describe '#.bind()', ->
it 'should allow partial application with type checking', ->
add3 = t('n,n n', add).bind @, 3
add3(2).should.equal 5
it 'should allow partial application of all expected arguments', ->
add3And4 = t('n,n n', add).bind @, 3, 4
add3And4().should.equal 7
describe '#taxa.disable()', ->
it 'should disable type checking', ->
t.disable()
t('_ n', sayHello)().should.equal 'hello'
describe '#taxa.enable()', ->
it 'should enable type checking', ->
t.enable()
t('_ n', sayHello).should.throw()
describe '#taxa.addAlias()', ->
it 'should allow aliasing other types with abbreviations', ->
t.addAlias 'i8', 'Int8Array'
(-> t('i8 i8', (a) -> a) new Int8Array).should.not.throw()
it 'should disallow alias collisions', ->
(-> t.addAlias 'i8', 'UInt8Array').should.throw()
describe '#taxa.removeAlias()', ->
it 'should allow alias removal', ->
t.removeAlias 'i8'
(-> t('i8 i8', (a) -> a) new Int8Array).should.throw()
it 'should throw when removing an unregistered alias', ->
(-> t.removeAlias 'i8').should.throw()
| true | require 'should'
require 'coffee-script/register'
t = require '../taxa.coffee'
goodName = (name) -> name.length > 3
add = (a, b) -> a + b
sayHello = -> 'hello'
describe 'taxa', ->
describe '#taxa()', ->
it 'should always return a function', ->
(typeof t 's b', goodName).should.equal 'function'
it 'should throw an error unless a signature string and a function are passed', ->
t.should.throw()
(-> t 1, 2).should.throw()
it 'should return a function that behaves as the original', ->
fn = t 's b', goodName
fn('PI:NAME:<NAME>END_PI').should.equal false
fn('PI:NAME:<NAME>END_PI').should.equal true
it 'should accept capitalized variants in the type signature', ->
fn = t 'S B', goodName
fn('PI:NAME:<NAME>END_PI').should.equal false
fn('PI:NAME:<NAME>END_PI').should.equal true
it 'should throw an error if passed the wrong type of arguments', ->
(-> t('n,n n', add) 'hi').should.throw()
it 'should throw an error if the function returns the wrong type', ->
t('_ n', sayHello).should.throw()
it 'should allow optional arguments', ->
t('s? b', -> true).should.not.throw()
it 'should throw when optional types do not match', ->
(-> t('s? b', -> true) 5).should.throw()
it 'should allow functions that return no value', ->
(-> t('s _', ->) 'hi').should.not.throw()
(-> t('s u', ->) 'hi').should.not.throw()
it 'should allow functions that accept no arguments', ->
t('_ b', -> true).should.not.throw()
it 'should allow functions that accept no arguments and return no value', ->
t('_ _', ->).should.not.throw()
it 'should correctly identify arrays passed as arguments', ->
fn = t 'a a', (a) -> []
(-> fn [1, 2, 3]).should.not.throw()
(-> fn {}).should.throw()
it 'should allow disjunctive types for arguments', ->
fn = t 's|n,n b', (x, l) -> String(x).length >= l
(-> fn 123, 3).should.not.throw()
(-> fn '123', 3).should.not.throw()
it 'should allow disjunctive types for return signatures', ->
fn = t 's s|b', (s) ->
if s is 'true'
true
else if s is 'false'
false
else
s
fn('true').should.equal true
fn('false').should.equal false
fn('neither').should.equal 'neither'
it 'should differentiate null from undefined', ->
takesNull = t '0 _', ->
(-> takesNull null).should.not.throw()
takesNull.should.throw()
t('_ 0', ->).should.throw()
(-> t('U _', ->) null).should.throw()
it 'should enforce complex types', ->
bufferMaker = t 'n Buffer', (n) -> new Buffer n
(-> bufferMaker 1).should.not.throw()
takesBuffer = t 'Buffer _', ->
(-> takesBuffer bufferMaker 1).should.not.throw()
(-> takesBuffer 1).should.throw()
describe '#.bind()', ->
it 'should allow partial application with type checking', ->
add3 = t('n,n n', add).bind @, 3
add3(2).should.equal 5
it 'should allow partial application of all expected arguments', ->
add3And4 = t('n,n n', add).bind @, 3, 4
add3And4().should.equal 7
describe '#taxa.disable()', ->
it 'should disable type checking', ->
t.disable()
t('_ n', sayHello)().should.equal 'hello'
describe '#taxa.enable()', ->
it 'should enable type checking', ->
t.enable()
t('_ n', sayHello).should.throw()
describe '#taxa.addAlias()', ->
it 'should allow aliasing other types with abbreviations', ->
t.addAlias 'i8', 'Int8Array'
(-> t('i8 i8', (a) -> a) new Int8Array).should.not.throw()
it 'should disallow alias collisions', ->
(-> t.addAlias 'i8', 'UInt8Array').should.throw()
describe '#taxa.removeAlias()', ->
it 'should allow alias removal', ->
t.removeAlias 'i8'
(-> t('i8 i8', (a) -> a) new Int8Array).should.throw()
it 'should throw when removing an unregistered alias', ->
(-> t.removeAlias 'i8').should.throw()
|
[
{
"context": "dal: false\n showMessageModal: false\n password: 'New Password Appears Here'\n\n loading: false\n\n # message modal's message\n ",
"end": 1534,
"score": 0.9993767142295837,
"start": 1509,
"tag": "PASSWORD",
"value": "New Password Appears Here"
},
{
"context": "n (res) =>\n @cancelModals()\n @password = res.password\n @loading = false\n @scheduleUpdate()\n ",
"end": 2942,
"score": 0.9987964034080505,
"start": 2930,
"tag": "PASSWORD",
"value": "res.password"
}
] | modules/hanzo-subscribers/index.coffee | hanzo-io/dash2 | 2 | import Daisho from 'daisho/src'
import Promise from 'broken'
import numeral from 'numeral'
import { isRequired } from 'daisho/src/views/middleware'
import subscribersHtml from './templates/subscribers.pug'
import subscriberHtml from './templates/subscriber.pug'
import css from './css/app.styl'
# import TractorBeam from 'tractor-beam'
SubscriberUpdateBalanceEvent = 'subscriber-update-balance'
class HanzoSubscribers extends Daisho.Views.HanzoDynamicTable
tag: 'hanzo-subscribers'
html: subscribersHtml
css: css
name: 'Subscribers'
configs:
'filter': []
initialized: false
loading: false
# a map of all the range facets that should use currency instead of numeric
facetCurrency:
price: true
listPrice: true
inventoryCost: true
# table header configuration
headers: [
# {
# name: 'Image'
# field: 'Slug'
# },
{
name: 'Email'
field: 'Email'
},
{
name: 'Signed Up On'
field: 'CreatedAt'
},
{
name: 'Last Updated'
field: 'UpdatedAt'
}
]
openFilter: false
init: ->
super
create: ()->
@services.page.show 'subscriber', ''
list: (opts) ->
return @client.subscriber.list opts
HanzoSubscribers.register()
class HanzoSubscriber extends Daisho.Views.Dynamic
tag: 'hanzo-subscriber'
html: subscriberHtml
css: css
_dataStaleField: 'id'
showResetModal: false
showResetPasswordModal: false
showSaveModal: false
showMessageModal: false
password: 'New Password Appears Here'
loading: false
# message modal's message
message: ''
# spatial units
dimensionsUnits:
cm: 'cm'
m: 'm'
in: 'in'
ft: 'ft'
# mass units
weightUnits:
g: 'g'
kg: 'kg'
oz: 'oz'
lb: 'lb'
configs:
firstName: [isRequired]
email: [isRequired]
enabled: [isRequired]
init: ->
super
# @one 'updated', ()=>
# beam = new TractorBeam '.tractor-beam'
# beam.on 'dropped', (files) ->
# for filepath in files
# console.log 'Uploading...', filepath
default: ()->
# pull the org information from localstorage
org = @daisho.akasha.get('orgs')[@daisho.akasha.get('activeOrg')]
model =
currency: org.currency
return model
# load things
_refresh: ()->
id = @data.get('id')
if !id
@data.clear()
@data.set @default()
@scheduleUpdate()
return true
@loading = true
return @client.subscriber.get(id).then (res) =>
@cancelModals()
@loading = false
@data.set res
@scheduleUpdate()
.catch (err)=>
@loading = false
# load things but slightly differently
reset: ()->
@_refresh(true).then ()=>
@showMessage 'Reset!'
resetPassword: ->
@loading = true
@scheduleUpdate()
@client.subscriber.resetPassword(@data.get('id')).then (res) =>
@cancelModals()
@password = res.password
@loading = false
@scheduleUpdate()
.catch (err)=>
@loading = false
@showMessage err
getResetPassword: ->
return @password ? ''
# save by using submit to validate inputs
save: ()->
test = @submit()
test.then (val)=>
if !val?
if $('.input .error')[0]?
@cancelModals()
@showMessage 'Some things were missing or incorrect. Try again.'
@scheduleUpdate()
.catch (err)=>
@showMessage err
# show the message modal
showMessage: (msg)->
if !msg?
msg = 'There was an error.'
else
msg = msg.message ? msg
@cancelModals()
@message = msg
@showMessageModal = true
@scheduleUpdate()
@messageTimeoutId = setTimeout ()=>
@cancelModals()
@scheduleUpdate()
, 5000
# show the reset modal
showReset: ()->
@cancelModals()
@showResetModal = true
@scheduleUpdate()
# show the reset password
showResetPassword: ()->
@cancelModals()
@showResetPasswordModal = true
@scheduleUpdate()
# show the save modal
showSave: ()->
@cancelModals()
@showSaveModal = true
@scheduleUpdate()
# close all modals
cancelModals: ()->
clearTimeout @messageTimeoutId
@showResetModal = false
@showResetPasswordModal = false
@showSaveModal = false
@showMessageModal = false
@scheduleUpdate()
# submit the form
_submit: ()->
data = Object.assign {}, @data.get()
delete data.balances
delete data.referrers
delete data.referrals
# presence of id determines method used
api = 'create'
if data.id?
api = 'update'
@loading = true
@client.subscriber[api](data).then (res)=>
@cancelModals()
@loading = false
@data.set res
@showMessage 'Success!'
@scheduleUpdate()
.catch (err)=>
@loading = false
@showMessage err
HanzoSubscriber.register()
class HanzoSubscribers extends Daisho.Views.HanzoDynamicTable
tag: 'hanzo-subscribers'
html: subscribersHtml
css: css
name: 'Subscribers'
configs:
'filter': []
initialized: false
loading: false
# a map of all the range facets that should use currency instead of numeric
facetCurrency:
price: true
listPrice: true
inventoryCost: true
# table header configuration
headers: [
# {
# name: 'Image'
# field: 'Slug'
# },
{
name: 'Email'
field: 'Email'
},
{
name: 'Registered On'
field: 'CreatedAt'
},
{
name: 'Last Updated'
field: 'UpdatedAt'
}
]
openFilter: false
init: ->
super
create: ()->
@services.page.show 'subscriber', ''
list: (opts) ->
return @client.subscriber.list opts
HanzoSubscribers.register()
export default class Subscribers
constructor: (daisho, ps, ms, cs)->
tag = null
opts = {}
ps.register 'subscribers',
->
@el = el = document.createElement 'hanzo-subscribers'
tag = (daisho.mount el)[0]
return el
->
tag.refresh()
return @el
->
ps.register 'subscriber',
(ps, id)->
opts.id = id if id?
@el = el = document.createElement 'hanzo-subscriber'
tag = (daisho.mount el)[0]
tag.data.set 'id', opts.id
return el
(ps, id)->
opts.id = id if id?
tag.data.set 'id', opts.id
tag.refresh()
return @el
->
ms.register 'Subscribers', ->
ps.show 'subscribers'
| 54325 | import Daisho from 'daisho/src'
import Promise from 'broken'
import numeral from 'numeral'
import { isRequired } from 'daisho/src/views/middleware'
import subscribersHtml from './templates/subscribers.pug'
import subscriberHtml from './templates/subscriber.pug'
import css from './css/app.styl'
# import TractorBeam from 'tractor-beam'
SubscriberUpdateBalanceEvent = 'subscriber-update-balance'
class HanzoSubscribers extends Daisho.Views.HanzoDynamicTable
tag: 'hanzo-subscribers'
html: subscribersHtml
css: css
name: 'Subscribers'
configs:
'filter': []
initialized: false
loading: false
# a map of all the range facets that should use currency instead of numeric
facetCurrency:
price: true
listPrice: true
inventoryCost: true
# table header configuration
headers: [
# {
# name: 'Image'
# field: 'Slug'
# },
{
name: 'Email'
field: 'Email'
},
{
name: 'Signed Up On'
field: 'CreatedAt'
},
{
name: 'Last Updated'
field: 'UpdatedAt'
}
]
openFilter: false
init: ->
super
create: ()->
@services.page.show 'subscriber', ''
list: (opts) ->
return @client.subscriber.list opts
HanzoSubscribers.register()
class HanzoSubscriber extends Daisho.Views.Dynamic
tag: 'hanzo-subscriber'
html: subscriberHtml
css: css
_dataStaleField: 'id'
showResetModal: false
showResetPasswordModal: false
showSaveModal: false
showMessageModal: false
password: '<PASSWORD>'
loading: false
# message modal's message
message: ''
# spatial units
dimensionsUnits:
cm: 'cm'
m: 'm'
in: 'in'
ft: 'ft'
# mass units
weightUnits:
g: 'g'
kg: 'kg'
oz: 'oz'
lb: 'lb'
configs:
firstName: [isRequired]
email: [isRequired]
enabled: [isRequired]
init: ->
super
# @one 'updated', ()=>
# beam = new TractorBeam '.tractor-beam'
# beam.on 'dropped', (files) ->
# for filepath in files
# console.log 'Uploading...', filepath
default: ()->
# pull the org information from localstorage
org = @daisho.akasha.get('orgs')[@daisho.akasha.get('activeOrg')]
model =
currency: org.currency
return model
# load things
_refresh: ()->
id = @data.get('id')
if !id
@data.clear()
@data.set @default()
@scheduleUpdate()
return true
@loading = true
return @client.subscriber.get(id).then (res) =>
@cancelModals()
@loading = false
@data.set res
@scheduleUpdate()
.catch (err)=>
@loading = false
# load things but slightly differently
reset: ()->
@_refresh(true).then ()=>
@showMessage 'Reset!'
resetPassword: ->
@loading = true
@scheduleUpdate()
@client.subscriber.resetPassword(@data.get('id')).then (res) =>
@cancelModals()
@password = <PASSWORD>
@loading = false
@scheduleUpdate()
.catch (err)=>
@loading = false
@showMessage err
getResetPassword: ->
return @password ? ''
# save by using submit to validate inputs
save: ()->
test = @submit()
test.then (val)=>
if !val?
if $('.input .error')[0]?
@cancelModals()
@showMessage 'Some things were missing or incorrect. Try again.'
@scheduleUpdate()
.catch (err)=>
@showMessage err
# show the message modal
showMessage: (msg)->
if !msg?
msg = 'There was an error.'
else
msg = msg.message ? msg
@cancelModals()
@message = msg
@showMessageModal = true
@scheduleUpdate()
@messageTimeoutId = setTimeout ()=>
@cancelModals()
@scheduleUpdate()
, 5000
# show the reset modal
showReset: ()->
@cancelModals()
@showResetModal = true
@scheduleUpdate()
# show the reset password
showResetPassword: ()->
@cancelModals()
@showResetPasswordModal = true
@scheduleUpdate()
# show the save modal
showSave: ()->
@cancelModals()
@showSaveModal = true
@scheduleUpdate()
# close all modals
cancelModals: ()->
clearTimeout @messageTimeoutId
@showResetModal = false
@showResetPasswordModal = false
@showSaveModal = false
@showMessageModal = false
@scheduleUpdate()
# submit the form
_submit: ()->
data = Object.assign {}, @data.get()
delete data.balances
delete data.referrers
delete data.referrals
# presence of id determines method used
api = 'create'
if data.id?
api = 'update'
@loading = true
@client.subscriber[api](data).then (res)=>
@cancelModals()
@loading = false
@data.set res
@showMessage 'Success!'
@scheduleUpdate()
.catch (err)=>
@loading = false
@showMessage err
HanzoSubscriber.register()
class HanzoSubscribers extends Daisho.Views.HanzoDynamicTable
tag: 'hanzo-subscribers'
html: subscribersHtml
css: css
name: 'Subscribers'
configs:
'filter': []
initialized: false
loading: false
# a map of all the range facets that should use currency instead of numeric
facetCurrency:
price: true
listPrice: true
inventoryCost: true
# table header configuration
headers: [
# {
# name: 'Image'
# field: 'Slug'
# },
{
name: 'Email'
field: 'Email'
},
{
name: 'Registered On'
field: 'CreatedAt'
},
{
name: 'Last Updated'
field: 'UpdatedAt'
}
]
openFilter: false
init: ->
super
create: ()->
@services.page.show 'subscriber', ''
list: (opts) ->
return @client.subscriber.list opts
HanzoSubscribers.register()
export default class Subscribers
constructor: (daisho, ps, ms, cs)->
tag = null
opts = {}
ps.register 'subscribers',
->
@el = el = document.createElement 'hanzo-subscribers'
tag = (daisho.mount el)[0]
return el
->
tag.refresh()
return @el
->
ps.register 'subscriber',
(ps, id)->
opts.id = id if id?
@el = el = document.createElement 'hanzo-subscriber'
tag = (daisho.mount el)[0]
tag.data.set 'id', opts.id
return el
(ps, id)->
opts.id = id if id?
tag.data.set 'id', opts.id
tag.refresh()
return @el
->
ms.register 'Subscribers', ->
ps.show 'subscribers'
| true | import Daisho from 'daisho/src'
import Promise from 'broken'
import numeral from 'numeral'
import { isRequired } from 'daisho/src/views/middleware'
import subscribersHtml from './templates/subscribers.pug'
import subscriberHtml from './templates/subscriber.pug'
import css from './css/app.styl'
# import TractorBeam from 'tractor-beam'
SubscriberUpdateBalanceEvent = 'subscriber-update-balance'
class HanzoSubscribers extends Daisho.Views.HanzoDynamicTable
tag: 'hanzo-subscribers'
html: subscribersHtml
css: css
name: 'Subscribers'
configs:
'filter': []
initialized: false
loading: false
# a map of all the range facets that should use currency instead of numeric
facetCurrency:
price: true
listPrice: true
inventoryCost: true
# table header configuration
headers: [
# {
# name: 'Image'
# field: 'Slug'
# },
{
name: 'Email'
field: 'Email'
},
{
name: 'Signed Up On'
field: 'CreatedAt'
},
{
name: 'Last Updated'
field: 'UpdatedAt'
}
]
openFilter: false
init: ->
super
create: ()->
@services.page.show 'subscriber', ''
list: (opts) ->
return @client.subscriber.list opts
HanzoSubscribers.register()
class HanzoSubscriber extends Daisho.Views.Dynamic
tag: 'hanzo-subscriber'
html: subscriberHtml
css: css
_dataStaleField: 'id'
showResetModal: false
showResetPasswordModal: false
showSaveModal: false
showMessageModal: false
password: 'PI:PASSWORD:<PASSWORD>END_PI'
loading: false
# message modal's message
message: ''
# spatial units
dimensionsUnits:
cm: 'cm'
m: 'm'
in: 'in'
ft: 'ft'
# mass units
weightUnits:
g: 'g'
kg: 'kg'
oz: 'oz'
lb: 'lb'
configs:
firstName: [isRequired]
email: [isRequired]
enabled: [isRequired]
init: ->
super
# @one 'updated', ()=>
# beam = new TractorBeam '.tractor-beam'
# beam.on 'dropped', (files) ->
# for filepath in files
# console.log 'Uploading...', filepath
default: ()->
# pull the org information from localstorage
org = @daisho.akasha.get('orgs')[@daisho.akasha.get('activeOrg')]
model =
currency: org.currency
return model
# load things
_refresh: ()->
id = @data.get('id')
if !id
@data.clear()
@data.set @default()
@scheduleUpdate()
return true
@loading = true
return @client.subscriber.get(id).then (res) =>
@cancelModals()
@loading = false
@data.set res
@scheduleUpdate()
.catch (err)=>
@loading = false
# load things but slightly differently
reset: ()->
@_refresh(true).then ()=>
@showMessage 'Reset!'
resetPassword: ->
@loading = true
@scheduleUpdate()
@client.subscriber.resetPassword(@data.get('id')).then (res) =>
@cancelModals()
@password = PI:PASSWORD:<PASSWORD>END_PI
@loading = false
@scheduleUpdate()
.catch (err)=>
@loading = false
@showMessage err
getResetPassword: ->
return @password ? ''
# save by using submit to validate inputs
save: ()->
test = @submit()
test.then (val)=>
if !val?
if $('.input .error')[0]?
@cancelModals()
@showMessage 'Some things were missing or incorrect. Try again.'
@scheduleUpdate()
.catch (err)=>
@showMessage err
# show the message modal
showMessage: (msg)->
if !msg?
msg = 'There was an error.'
else
msg = msg.message ? msg
@cancelModals()
@message = msg
@showMessageModal = true
@scheduleUpdate()
@messageTimeoutId = setTimeout ()=>
@cancelModals()
@scheduleUpdate()
, 5000
# show the reset modal
showReset: ()->
@cancelModals()
@showResetModal = true
@scheduleUpdate()
# show the reset password
showResetPassword: ()->
@cancelModals()
@showResetPasswordModal = true
@scheduleUpdate()
# show the save modal
showSave: ()->
@cancelModals()
@showSaveModal = true
@scheduleUpdate()
# close all modals
cancelModals: ()->
clearTimeout @messageTimeoutId
@showResetModal = false
@showResetPasswordModal = false
@showSaveModal = false
@showMessageModal = false
@scheduleUpdate()
# submit the form
_submit: ()->
data = Object.assign {}, @data.get()
delete data.balances
delete data.referrers
delete data.referrals
# presence of id determines method used
api = 'create'
if data.id?
api = 'update'
@loading = true
@client.subscriber[api](data).then (res)=>
@cancelModals()
@loading = false
@data.set res
@showMessage 'Success!'
@scheduleUpdate()
.catch (err)=>
@loading = false
@showMessage err
HanzoSubscriber.register()
class HanzoSubscribers extends Daisho.Views.HanzoDynamicTable
tag: 'hanzo-subscribers'
html: subscribersHtml
css: css
name: 'Subscribers'
configs:
'filter': []
initialized: false
loading: false
# a map of all the range facets that should use currency instead of numeric
facetCurrency:
price: true
listPrice: true
inventoryCost: true
# table header configuration
headers: [
# {
# name: 'Image'
# field: 'Slug'
# },
{
name: 'Email'
field: 'Email'
},
{
name: 'Registered On'
field: 'CreatedAt'
},
{
name: 'Last Updated'
field: 'UpdatedAt'
}
]
openFilter: false
init: ->
super
create: ()->
@services.page.show 'subscriber', ''
list: (opts) ->
return @client.subscriber.list opts
HanzoSubscribers.register()
export default class Subscribers
constructor: (daisho, ps, ms, cs)->
tag = null
opts = {}
ps.register 'subscribers',
->
@el = el = document.createElement 'hanzo-subscribers'
tag = (daisho.mount el)[0]
return el
->
tag.refresh()
return @el
->
ps.register 'subscriber',
(ps, id)->
opts.id = id if id?
@el = el = document.createElement 'hanzo-subscriber'
tag = (daisho.mount el)[0]
tag.data.set 'id', opts.id
return el
(ps, id)->
opts.id = id if id?
tag.data.set 'id', opts.id
tag.refresh()
return @el
->
ms.register 'Subscribers', ->
ps.show 'subscribers'
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.